Vfx.cpp 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739
  1. #include "core/Vfx.h"
  2. #include <algorithm>
  3. #include <atomic>
  4. #include <cmath>
  5. #include <cstring>
  6. #include <functional>
  7. #include "core/FlSynths.h"
  8. #include "core/Song.h"
  9. #include "flp/Flp.h"
  10. namespace lynx::vfx
  11. {
  12. namespace
  13. {
  14. constexpr std::uint32_t lynxMagic = 0x5846564c; // "LVFX"
  15. struct Reader
  16. {
  17. const std::uint8_t* data;
  18. std::size_t size, pos = 0;
  19. bool failed = false;
  20. template <typename T>
  21. T get() noexcept
  22. {
  23. T v {};
  24. if (failed || sizeof (T) > size - pos)
  25. {
  26. failed = true;
  27. return v;
  28. }
  29. std::memcpy (&v, data + pos, sizeof (T));
  30. pos += sizeof (T);
  31. return v;
  32. }
  33. std::int32_t i32() noexcept { return get<std::int32_t>(); }
  34. std::uint32_t u32() noexcept { return get<std::uint32_t>(); }
  35. std::size_t left() const noexcept { return failed ? 0 : size - pos; }
  36. };
  37. template <typename T>
  38. void put (std::vector<std::uint8_t>& out, T v)
  39. {
  40. const auto* p = reinterpret_cast<const std::uint8_t*> (&v);
  41. out.insert (out.end(), p, p + sizeof (T));
  42. }
  43. // Settings handed from the UI thread to the audio thread without locks or allocation on the audio side (the
  44. // Patcher graph's pattern): the UI publishes a new object, the audio thread swaps it in and parks the old one, the
  45. // UI frees it on its next call.
  46. template <typename T>
  47. class Handoff
  48. {
  49. public:
  50. explicit Handoff (T initial) : active (std::make_unique<T> (std::move (initial))) {}
  51. explicit Handoff (std::unique_ptr<T> initial) : active (std::move (initial)) {}
  52. ~Handoff()
  53. {
  54. delete pending.exchange (nullptr);
  55. delete retired.exchange (nullptr);
  56. }
  57. void publish (T value)
  58. {
  59. delete retired.exchange (nullptr);
  60. delete pending.exchange (new T (std::move (value)));
  61. }
  62. void publish (std::unique_ptr<T> value)
  63. {
  64. delete retired.exchange (nullptr);
  65. delete pending.exchange (value.release());
  66. }
  67. // audio thread: true when new settings arrived
  68. bool take() noexcept
  69. {
  70. auto* incoming = pending.exchange (nullptr);
  71. if (incoming == nullptr)
  72. return false;
  73. auto* old = active.release();
  74. active.reset (incoming);
  75. delete retired.exchange (old); // (normally null: the UI frees it on its next call)
  76. return true;
  77. }
  78. const T& get() const noexcept { return *active; }
  79. private:
  80. std::unique_ptr<T> active;
  81. std::atomic<T*> pending { nullptr };
  82. std::atomic<T*> retired { nullptr };
  83. };
  84. } // namespace
  85. int inputId (int key, int colour) noexcept { return (colour & 15) * 128 + (key & 127); }
  86. // ---------------------------------------------------------------------------------------------------------------
  87. const char* flName (Kind kind) noexcept
  88. {
  89. switch (kind)
  90. {
  91. case Kind::keyMapper: return "VFX Key Mapper";
  92. case Kind::colorMapper: return "VFX Color Mapper";
  93. case Kind::envelope: return "VFX Envelope";
  94. case Kind::keyboardSplitter: return "VFX Keyboard Splitter";
  95. case Kind::levelScaler: return "VFX Level Scaler";
  96. case Kind::sequencer: return "VFX Sequencer";
  97. case Kind::script: return "VFX Script";
  98. }
  99. return "VFX";
  100. }
  101. std::optional<Kind> kindOfFlName (std::string_view name) noexcept
  102. {
  103. auto same = [] (std::string_view a, std::string_view b) {
  104. return a.size() == b.size() && std::equal (a.begin(), a.end(), b.begin(), [] (char x, char y) {
  105. return std::tolower ((unsigned char) x) == std::tolower ((unsigned char) y);
  106. });
  107. };
  108. for (const auto k : allKinds)
  109. if (same (name, flName (k)))
  110. return k;
  111. return std::nullopt;
  112. }
  113. void EventList::sortByOffset() noexcept
  114. {
  115. // stable insertion sort in place (std::stable_sort may allocate; the events arrive nearly in order); an "off"
  116. // goes before an "on" on the same sample
  117. const auto before = [] (const Event& a, const Event& b) {
  118. if (a.offset != b.offset)
  119. return a.offset < b.offset;
  120. return a.type == Event::Type::off && b.type != Event::Type::off;
  121. };
  122. for (int i = 1; i < count; ++i)
  123. {
  124. const auto e = events[(std::size_t) i];
  125. auto j = i;
  126. for (; j > 0 && before (e, events[(std::size_t) j - 1]); --j)
  127. events[(std::size_t) j] = events[(std::size_t) j - 1];
  128. events[(std::size_t) j] = e;
  129. }
  130. }
  131. void EventList::removeFirst (int n) noexcept
  132. {
  133. n = std::clamp (n, 0, count);
  134. std::move (events.begin() + n, events.begin() + count, events.begin());
  135. count -= n;
  136. }
  137. // ---------------------------------------------------------------------------------------------------------------
  138. // VFX Key Mapper
  139. KeyMapperSettings defaultKeyMapper()
  140. {
  141. KeyMapperSettings s;
  142. for (int i = 0; i < 12; ++i)
  143. s.rows[(std::size_t) i] = { i };
  144. return s;
  145. }
  146. std::optional<KeyMapperSettings> parseKeyMapper (const std::vector<std::uint8_t>& fl)
  147. {
  148. Reader r { fl.data(), fl.size() };
  149. KeyMapperSettings s;
  150. s.version = r.i32();
  151. if (r.failed || s.version < 1 || s.version > 16)
  152. return std::nullopt;
  153. s.enabled = r.i32() != 0;
  154. s.baseKey = r.i32();
  155. s.offset = r.i32();
  156. s.multimode = r.i32();
  157. s.slide = r.i32();
  158. for (auto& row : s.rows)
  159. {
  160. const auto n = r.i32();
  161. if (r.failed || n < 0 || n > 128)
  162. return std::nullopt;
  163. row.clear();
  164. for (int k = 0; k < n; ++k)
  165. row.push_back (r.get<std::int16_t>());
  166. }
  167. if (r.failed)
  168. return std::nullopt;
  169. s.extra.assign (fl.begin() + (std::ptrdiff_t) r.pos, fl.end());
  170. return s;
  171. }
  172. std::vector<std::uint8_t> writeKeyMapper (const KeyMapperSettings& s)
  173. {
  174. std::vector<std::uint8_t> out;
  175. put<std::int32_t> (out, s.version);
  176. put<std::int32_t> (out, s.enabled ? 1 : 0);
  177. put<std::int32_t> (out, s.baseKey);
  178. put<std::int32_t> (out, s.offset);
  179. put<std::int32_t> (out, s.multimode);
  180. put<std::int32_t> (out, s.slide);
  181. for (const auto& row : s.rows)
  182. {
  183. put<std::int32_t> (out, (std::int32_t) row.size());
  184. for (const auto v : row)
  185. put<std::int16_t> (out, (std::int16_t) v);
  186. }
  187. out.insert (out.end(), s.extra.begin(), s.extra.end());
  188. return out;
  189. }
  190. // ---------------------------------------------------------------------------------------------------------------
  191. // VFX Color Mapper
  192. ColorMapperSettings defaultColorMapper()
  193. {
  194. ColorMapperSettings s;
  195. for (int i = 0; i < 16; ++i)
  196. s.port[(std::size_t) i] = s.colour[(std::size_t) i] = i;
  197. return s;
  198. }
  199. std::optional<ColorMapperSettings> parseColorMapper (const std::vector<std::uint8_t>& fl)
  200. {
  201. Reader r { fl.data(), fl.size() };
  202. ColorMapperSettings s;
  203. s.header = r.u32();
  204. for (auto& p : s.port)
  205. p = std::clamp (r.i32(), 0, 15);
  206. for (auto& c : s.colour)
  207. c = std::clamp (r.i32(), 0, 15);
  208. if (r.failed)
  209. return std::nullopt;
  210. return s;
  211. }
  212. std::vector<std::uint8_t> writeColorMapper (const ColorMapperSettings& s)
  213. {
  214. std::vector<std::uint8_t> out;
  215. put<std::uint32_t> (out, s.header);
  216. for (const auto p : s.port)
  217. put<std::int32_t> (out, p);
  218. for (const auto c : s.colour)
  219. put<std::int32_t> (out, c);
  220. return out;
  221. }
  222. // ---------------------------------------------------------------------------------------------------------------
  223. // VFX Level Scaler (REA_rodada164b §Level Scaler)
  224. bool LevelScalerSettings::identity (int tab) const noexcept
  225. {
  226. return at (tab, multiply) == 8192 && at (tab, offset) == 0 && at (tab, tension) == 0 && at (tab, humanize) == 0;
  227. }
  228. void resetLevelScalerTab (LevelScalerSettings& s, int tab)
  229. {
  230. // the editor's Reset: bipolar properties are centred
  231. s.at (tab, LevelScalerSettings::center) = tab >= LevelScalerSettings::finePitch ? 4096 : 0;
  232. s.at (tab, LevelScalerSettings::multiply) = 8192;
  233. s.at (tab, LevelScalerSettings::offset) = 0;
  234. s.at (tab, LevelScalerSettings::tension) = 0;
  235. s.at (tab, LevelScalerSettings::humanize) = 0;
  236. s.at (tab, LevelScalerSettings::humanizeMode) = 1;
  237. }
  238. LevelScalerSettings defaultLevelScaler()
  239. {
  240. LevelScalerSettings s;
  241. for (int t = 0; t < LevelScalerSettings::tabCount; ++t)
  242. resetLevelScalerTab (s, t);
  243. return s;
  244. }
  245. std::optional<LevelScalerSettings> parseLevelScaler (const std::vector<std::uint8_t>& fl)
  246. {
  247. Reader r { fl.data(), fl.size() };
  248. auto s = defaultLevelScaler();
  249. s.version = r.u32();
  250. if (r.failed)
  251. return std::nullopt;
  252. if (s.version >= 2)
  253. return defaultLevelScaler(); // (FL ignores a state it does not know)
  254. // chunks: id, 64-bit size, data (unknown ids skipped)
  255. while (r.left() >= 12)
  256. {
  257. const auto id = r.u32();
  258. const auto size = r.get<std::uint64_t>();
  259. if (size > r.left())
  260. return std::nullopt;
  261. const auto end = r.pos + (std::size_t) size;
  262. if (id == 0x3ea && size >= 1)
  263. s.selectedTab = std::clamp ((int) r.get<std::uint8_t>(), 0, 5);
  264. else if (id == 0x3e9 && size >= 144)
  265. {
  266. static constexpr std::array<std::pair<int, int>, 6> range { { { 0, 8192 }, { -16384, 16384 }, { -8192, 8192 }, { -8192, 8192 }, { 0, 16384 }, { 0, 2 } } };
  267. for (int i = 0; i < 36; ++i)
  268. s.p[(std::size_t) i] = std::clamp (r.i32(), range[(std::size_t) (i % 6)].first, range[(std::size_t) (i % 6)].second);
  269. }
  270. r.pos = end;
  271. }
  272. if (r.failed)
  273. return std::nullopt;
  274. return s;
  275. }
  276. std::vector<std::uint8_t> writeLevelScaler (const LevelScalerSettings& s)
  277. {
  278. std::vector<std::uint8_t> out;
  279. put<std::uint32_t> (out, 1);
  280. put<std::uint32_t> (out, 0x3ea);
  281. put<std::uint64_t> (out, 1);
  282. put<std::uint8_t> (out, (std::uint8_t) std::clamp (s.selectedTab, 0, 5));
  283. put<std::uint32_t> (out, 0x3e9);
  284. put<std::uint64_t> (out, 144);
  285. for (const auto v : s.p)
  286. put<std::int32_t> (out, v);
  287. return out;
  288. }
  289. double levelScale (const LevelScalerSettings& s, int tab, double x, double lo, double hi, double random) noexcept
  290. {
  291. using L = LevelScalerSettings;
  292. if (s.identity (tab) || ! (hi > lo))
  293. return x;
  294. const auto c = s.at (tab, L::center) / 8192.0;
  295. const auto scale = 1.0 / std::max (c, 1.0 - c);
  296. const auto tension = s.at (tab, L::tension);
  297. const auto g = std::pow (8193.0, std::abs (tension) / 8192.0) - 1.0;
  298. const auto mul = s.at (tab, L::multiply) / (8192.0 * scale);
  299. const auto off = s.at (tab, L::offset) / 8192.0 + c;
  300. const auto u = (x - lo) / (hi - lo);
  301. const auto d = u - c;
  302. const auto m = std::min (1.0, std::abs (d) * scale);
  303. auto shape = m;
  304. if (tension > 0 && g > 0.0)
  305. shape = 1.0 - (std::pow (g + 1.0, 1.0 - m) - 1.0) / g;
  306. else if (tension < 0 && g > 0.0)
  307. shape = (std::pow (g + 1.0, m) - 1.0) / g;
  308. const auto y = std::clamp ((d < 0.0 ? -shape : shape) * mul + off, 0.0, 1.0);
  309. auto out = std::clamp (lo + y * (hi - lo), lo, hi);
  310. if (const auto h = s.at (tab, L::humanize) / 16384.0; h > 0.0)
  311. {
  312. const auto mode = s.at (tab, L::humanizeMode);
  313. const auto a = mode == 2 ? out : out - (out - lo) * h;
  314. const auto b = mode == 0 ? out : out + (hi - out) * h;
  315. out = a + std::clamp (random, 0.0, 1.0) * (b - a);
  316. }
  317. return out;
  318. }
  319. // ---------------------------------------------------------------------------------------------------------------
  320. // FL's mapping curves and VFX Keyboard Splitter (REA_rodada164b §Keyboard Splitter)
  321. MapCurve MapCurve::flat (double level)
  322. {
  323. MapCurve m;
  324. m.points.push_back ({ 0.0, level });
  325. m.points.push_back ({ 1.0, level });
  326. return m;
  327. }
  328. double MapCurve::at (double x) const noexcept
  329. {
  330. if (points.empty())
  331. return 0.0;
  332. if (x <= points.front().x)
  333. return points.front().y;
  334. for (std::size_t i = 1; i < points.size(); ++i)
  335. if (x < points[i].x)
  336. {
  337. const auto& a = points[i - 1];
  338. const auto& b = points[i];
  339. if (b.curve == 2) // hold: the previous level up to this point
  340. return a.y;
  341. auto f = b.x > a.x ? (x - a.x) / (b.x - a.x) : 1.0;
  342. if (b.tension != 0.0f) // (the automation clips' bend, FL's sign)
  343. f = std::pow (f, std::pow (2.0, (double) -b.tension * 3.0));
  344. return a.y + (b.y - a.y) * f;
  345. }
  346. return points.back().y;
  347. }
  348. bool MapCurve::isFlat (double level) const noexcept
  349. {
  350. return std::all_of (points.begin(), points.end(), [level] (const Point& p) { return std::abs (p.y - level) < 1e-9; });
  351. }
  352. namespace
  353. {
  354. bool readMap (Reader& r, MapCurve& m)
  355. {
  356. r.i32(); // kind (3)
  357. const auto version = r.i32();
  358. const auto n = r.i32();
  359. if (r.failed || n < 0 || n > 4096 || version < 2 || version > 3)
  360. return false;
  361. m.points.clear();
  362. double x = 0.0;
  363. for (int k = 0; k < n; ++k)
  364. {
  365. MapCurve::Point p;
  366. const auto dx = r.get<double>();
  367. x += std::isfinite (dx) ? dx : 0.0;
  368. p.x = x;
  369. p.y = r.get<double>();
  370. if (! std::isfinite (p.y))
  371. p.y = 0.0;
  372. p.tension = r.get<float>();
  373. if (! std::isfinite (p.tension))
  374. p.tension = 0.0f;
  375. p.curve = r.get<std::uint8_t>();
  376. p.b13 = r.get<std::uint8_t>();
  377. p.b14 = r.get<std::uint8_t>();
  378. p.b15 = r.get<std::uint8_t>();
  379. m.points.push_back (p);
  380. }
  381. for (auto& f : m.footer)
  382. f = r.i32();
  383. return ! r.failed;
  384. }
  385. void writeMap (std::vector<std::uint8_t>& out, const MapCurve& m, int kind = 3)
  386. {
  387. put<std::int32_t> (out, kind);
  388. put<std::int32_t> (out, 3);
  389. put<std::int32_t> (out, (std::int32_t) m.points.size());
  390. double x = 0.0;
  391. for (const auto& p : m.points)
  392. {
  393. put<double> (out, p.x - x);
  394. x = p.x;
  395. put<double> (out, p.y);
  396. put<float> (out, p.tension);
  397. put<std::uint8_t> (out, p.curve);
  398. put<std::uint8_t> (out, p.b13);
  399. put<std::uint8_t> (out, p.b14);
  400. put<std::uint8_t> (out, p.b15); // (FL's shape flag: 2 straight, 1 / 0xff bent up / down)
  401. }
  402. for (const auto f : m.footer)
  403. put<std::int32_t> (out, f);
  404. }
  405. } // namespace
  406. KeyboardSplitterSettings defaultKeyboardSplitter()
  407. {
  408. KeyboardSplitterSettings s;
  409. s.zones[0].keyboard = MapCurve::flat (1.0); // zone 1: the whole keyboard
  410. return s;
  411. }
  412. std::optional<KeyboardSplitterSettings> parseKeyboardSplitter (const std::vector<std::uint8_t>& fl)
  413. {
  414. Reader r { fl.data(), fl.size() };
  415. KeyboardSplitterSettings s;
  416. s.header = r.u32();
  417. if (r.failed || s.header >= 0x100004 || (s.header & 0xfffff) == 0)
  418. return std::nullopt;
  419. if ((s.header >> 20) != 0)
  420. s.page = std::clamp ((int) r.get<std::uint8_t>(), 0, 1);
  421. for (auto& z : s.zones)
  422. {
  423. if (! readMap (r, z.keyboard) || ! readMap (r, z.velocity))
  424. return std::nullopt;
  425. z.transpose = std::clamp (r.i32(), -48, 48);
  426. z.absolute = r.get<std::uint8_t>() != 0;
  427. z.random = r.get<std::uint8_t>() != 0;
  428. // name: u8 length (255: a u32 follows), UTF-16 characters
  429. std::uint32_t length = r.get<std::uint8_t>();
  430. if (length == 255)
  431. length = r.u32();
  432. if (r.failed || length > 4096 || length * 2 > r.left())
  433. return std::nullopt;
  434. std::u16string name;
  435. for (std::uint32_t k = 0; k < length; ++k)
  436. name.push_back ((char16_t) r.get<std::uint16_t>());
  437. z.name.clear();
  438. for (std::size_t k = 0; k < name.size(); ++k)
  439. {
  440. std::uint32_t c = name[k];
  441. if (c >= 0xd800 && c < 0xdc00 && k + 1 < name.size())
  442. c = 0x10000 + ((c - 0xd800) << 10) + ((std::uint32_t) name[++k] - 0xdc00);
  443. if (c < 0x80)
  444. z.name.push_back ((char) c);
  445. else if (c < 0x800)
  446. z.name += { (char) (0xc0 | (c >> 6)), (char) (0x80 | (c & 0x3f)) };
  447. else if (c < 0x10000)
  448. z.name += { (char) (0xe0 | (c >> 12)), (char) (0x80 | ((c >> 6) & 0x3f)), (char) (0x80 | (c & 0x3f)) };
  449. else
  450. z.name += { (char) (0xf0 | (c >> 18)), (char) (0x80 | ((c >> 12) & 0x3f)), (char) (0x80 | ((c >> 6) & 0x3f)), (char) (0x80 | (c & 0x3f)) };
  451. }
  452. }
  453. if (r.failed)
  454. return std::nullopt;
  455. return s;
  456. }
  457. std::vector<std::uint8_t> writeKeyboardSplitter (const KeyboardSplitterSettings& s)
  458. {
  459. std::vector<std::uint8_t> out;
  460. put<std::uint32_t> (out, 0x100003);
  461. put<std::uint8_t> (out, (std::uint8_t) std::clamp (s.page, 0, 1));
  462. for (const auto& z : s.zones)
  463. {
  464. writeMap (out, z.keyboard);
  465. writeMap (out, z.velocity);
  466. put<std::int32_t> (out, z.transpose);
  467. put<std::uint8_t> (out, z.absolute ? 1 : 0);
  468. put<std::uint8_t> (out, z.random ? 1 : 0);
  469. std::u16string name;
  470. for (std::size_t k = 0; k < z.name.size();)
  471. {
  472. const auto b = (std::uint8_t) z.name[k];
  473. std::uint32_t c = b;
  474. int more = b >= 0xf0 ? 3 : b >= 0xe0 ? 2 : b >= 0xc0 ? 1 : 0;
  475. c = more == 3 ? b & 0x07 : more == 2 ? b & 0x0f : more == 1 ? b & 0x1f : b;
  476. ++k;
  477. for (; more > 0 && k < z.name.size(); --more, ++k)
  478. c = (c << 6) | ((std::uint8_t) z.name[k] & 0x3f);
  479. if (c >= 0x10000)
  480. {
  481. c -= 0x10000;
  482. name.push_back ((char16_t) (0xd800 + (c >> 10)));
  483. name.push_back ((char16_t) (0xdc00 + (c & 0x3ff)));
  484. }
  485. else
  486. name.push_back ((char16_t) c);
  487. }
  488. if (name.size() < 255)
  489. put<std::uint8_t> (out, (std::uint8_t) name.size());
  490. else
  491. {
  492. put<std::uint8_t> (out, 255);
  493. put<std::uint32_t> (out, (std::uint32_t) name.size());
  494. }
  495. for (const auto c : name)
  496. put<std::uint16_t> (out, (std::uint16_t) c);
  497. }
  498. return out;
  499. }
  500. double splitterGain (double m) noexcept
  501. {
  502. return m >= 1.0 ? 1.0 : (std::pow (11.0, m) - 1.0) / 10.0;
  503. }
  504. // ---------------------------------------------------------------------------------------------------------------
  505. // VFX Envelope (REA_rodada164b §Envelope)
  506. namespace
  507. {
  508. MapCurve curveOf (std::initializer_list<std::tuple<double, double, float>> points, std::array<std::int32_t, 5> footer)
  509. {
  510. MapCurve m;
  511. for (const auto& [x, y, t] : points)
  512. m.points.push_back ({ x, y, t });
  513. m.footer = footer;
  514. return m;
  515. }
  516. } // namespace
  517. EnvelopeSettings defaultEnvelope()
  518. {
  519. EnvelopeSettings s;
  520. for (int g = 0; g < 16; ++g)
  521. {
  522. auto& a = s.articulators[(std::size_t) g];
  523. for (int t = 0; t < EnvelopeSettings::targetCount; ++t)
  524. {
  525. auto& p = a.parts[(std::size_t) t];
  526. p.lfoAmp = curveOf ({ { 0.0, 0.5, 0.0f }, { 1.0, 0.5, 0.0f }, { 1.25, 1.0, 0.0f }, { 2.25, 0.5, 0.0f } }, { 0, 0, -1, -1, -1 });
  527. if (t == EnvelopeSettings::velocity)
  528. {
  529. p.base = 0.0f;
  530. // a volume envelope: attack, a peak, sustain at half (= the note's own level), release
  531. p.envelope = curveOf ({ { 0.0, 0.0, 0.0f }, { 0.75, 1.0, 0.2f }, { 2.25, 0.5, 0.2f }, { 2.5, 0.0, 0.2f } },
  532. { 0, g == 0 ? -1 : 0, 1, -1, 2 });
  533. }
  534. else
  535. {
  536. p.base = 0.5f;
  537. p.env = t == EnvelopeSettings::pitch ? 0.25f : 1.0f;
  538. p.envelope = curveOf ({ { 0.0, 0.5, 0.0f }, { 0.25, 0.5, 0.0f } }, { 1, -1, -1, -1, -1 }); // (on, neutral)
  539. }
  540. }
  541. }
  542. return s;
  543. }
  544. namespace
  545. {
  546. bool readPart (Reader& r, EnvelopeSettings::Part& p)
  547. {
  548. p.version = r.i32();
  549. p.base = r.get<float>();
  550. p.env = r.get<float>();
  551. p.lfo = r.get<float>();
  552. if (! readMap (r, p.envelope))
  553. return false;
  554. for (auto& k : p.adsr)
  555. k = r.i32();
  556. if (! readMap (r, p.lfoAmp))
  557. return false;
  558. p.speed = r.i32();
  559. p.tension = r.i32();
  560. p.skew = r.i32();
  561. p.pulseWidth = r.i32();
  562. p.phase = p.version >= 3 ? r.i32() : 0;
  563. for (auto* f : { &p.base, &p.env, &p.lfo })
  564. if (! std::isfinite (*f))
  565. *f = 0.0f;
  566. return ! r.failed;
  567. }
  568. void writePart (std::vector<std::uint8_t>& out, const EnvelopeSettings::Part& p)
  569. {
  570. put<std::int32_t> (out, 3);
  571. put<float> (out, p.base);
  572. put<float> (out, p.env);
  573. put<float> (out, p.lfo);
  574. writeMap (out, p.envelope, 1);
  575. for (const auto k : p.adsr)
  576. put<std::int32_t> (out, k);
  577. writeMap (out, p.lfoAmp, 2);
  578. for (const auto v : { p.speed, p.tension, p.skew, p.pulseWidth, p.phase })
  579. put<std::int32_t> (out, v);
  580. }
  581. void writeChunk (std::vector<std::uint8_t>& out, std::int32_t id, const std::vector<std::uint8_t>& data)
  582. {
  583. put<std::int32_t> (out, id);
  584. put<std::int64_t> (out, (std::int64_t) data.size());
  585. out.insert (out.end(), data.begin(), data.end());
  586. }
  587. } // namespace
  588. std::optional<EnvelopeSettings> parseEnvelope (const std::vector<std::uint8_t>& fl)
  589. {
  590. Reader r { fl.data(), fl.size() };
  591. auto s = defaultEnvelope();
  592. s.header = r.u32();
  593. if (r.failed || s.header >= 0x10004)
  594. return std::nullopt;
  595. std::vector<std::int32_t> params;
  596. int group = 0, target = 0;
  597. while (r.left() >= 12)
  598. {
  599. const auto id = r.i32();
  600. const auto size = r.get<std::int64_t>();
  601. if (size < 0 || (std::uint64_t) size > r.left())
  602. return std::nullopt;
  603. const auto end = r.pos + (std::size_t) size;
  604. Reader c { fl.data(), end, r.pos };
  605. switch (id)
  606. {
  607. case 1003:
  608. s.enabled = c.i32() != 0;
  609. s.shownArticulator = std::clamp (c.i32(), 0, 15);
  610. s.shownTarget = std::clamp (c.i32(), 0, 4);
  611. s.shownPart = std::clamp (c.i32(), 0, 1);
  612. break;
  613. case 1008:
  614. params.clear();
  615. while (c.left() >= 4)
  616. params.push_back (c.i32());
  617. break;
  618. case 1007:
  619. for (auto& t : s.toggles)
  620. t = c.left() >= 4 ? c.i32() : 0;
  621. break;
  622. case 1004:
  623. {
  624. group = std::clamp (c.i32(), 0, 15);
  625. auto& a = s.articulators[(std::size_t) group];
  626. a.colour = std::clamp (c.i32(), 0, 15);
  627. a.low = std::clamp (c.i32(), 0, 132);
  628. a.high = std::clamp (c.i32(), 0, 132);
  629. break;
  630. }
  631. case 1005:
  632. group = std::clamp (c.i32(), 0, 15);
  633. target = std::clamp (c.i32(), 0, 4);
  634. break;
  635. case 1006:
  636. if (! readPart (c, s.articulators[(std::size_t) group].parts[(std::size_t) target]))
  637. return std::nullopt;
  638. break;
  639. default: break;
  640. }
  641. r.pos = end;
  642. }
  643. if (r.failed)
  644. return std::nullopt;
  645. // the parameter values set the base / envelope / LFO levels (FL pushes them after loading)
  646. if (params.size() >= 880)
  647. for (int g = 0; g < 16; ++g)
  648. for (int t = 0; t < 5; ++t)
  649. {
  650. auto& p = s.articulators[(std::size_t) g].parts[(std::size_t) t];
  651. const auto at = (std::size_t) ((g * 5 + t) * 11);
  652. p.base = std::clamp (params[at + 8], 0, 256) / 256.0f;
  653. p.env = std::clamp (params[at + 9], -256, 256) / 256.0f;
  654. p.lfo = std::clamp (params[at + 10], -256, 256) / 256.0f;
  655. }
  656. return s;
  657. }
  658. std::vector<std::uint8_t> writeEnvelope (const EnvelopeSettings& s)
  659. {
  660. std::vector<std::uint8_t> out, chunk;
  661. put<std::uint32_t> (out, 0x10003);
  662. for (const auto v : { s.enabled ? 1 : 0, s.shownArticulator, s.shownTarget, s.shownPart })
  663. put<std::int32_t> (chunk, v);
  664. writeChunk (out, 1003, chunk);
  665. chunk.clear();
  666. for (const auto& a : s.articulators)
  667. for (const auto& p : a.parts)
  668. for (const auto v : { p.adsr[0], p.adsr[1], p.adsr[2], p.adsr[3], p.speed, p.tension, p.skew, p.pulseWidth,
  669. (std::int32_t) std::lround (p.base * 256.0f), (std::int32_t) std::lround (p.env * 256.0f),
  670. (std::int32_t) std::lround (p.lfo * 256.0f) })
  671. put<std::int32_t> (chunk, v);
  672. writeChunk (out, 1008, chunk);
  673. chunk.clear();
  674. for (const auto t : s.toggles)
  675. put<std::int32_t> (chunk, t);
  676. writeChunk (out, 1007, chunk);
  677. for (int g = 0; g < 16; ++g)
  678. {
  679. const auto& a = s.articulators[(std::size_t) g];
  680. chunk.clear();
  681. for (const auto v : { g, a.colour, a.low, a.high })
  682. put<std::int32_t> (chunk, v);
  683. writeChunk (out, 1004, chunk);
  684. for (int t = 0; t < 5; ++t)
  685. {
  686. chunk.clear();
  687. for (const auto v : { g, t, 0 })
  688. put<std::int32_t> (chunk, v);
  689. writeChunk (out, 1005, chunk);
  690. chunk.clear();
  691. writePart (chunk, a.parts[(std::size_t) t]);
  692. writeChunk (out, 1006, chunk);
  693. }
  694. }
  695. return out;
  696. }
  697. // ---------------------------------------------------------------------------------------------------------------
  698. // Presets
  699. std::vector<Preset> builtInPresets (Kind kind)
  700. {
  701. std::vector<Preset> out;
  702. if (kind == Kind::keyMapper)
  703. {
  704. // scales: each key plays the nearest scale note at or below it (as FL's scale presets do)
  705. struct Scale
  706. {
  707. const char* name;
  708. std::vector<int> notes;
  709. };
  710. const std::vector<Scale> scales {
  711. { "Major", { 0, 2, 4, 5, 7, 9, 11 } },
  712. { "Natural minor", { 0, 2, 3, 5, 7, 8, 10 } },
  713. { "Harmonic minor", { 0, 2, 3, 5, 7, 8, 11 } },
  714. { "Melodic minor", { 0, 2, 3, 5, 7, 9, 11 } },
  715. { "Dorian", { 0, 2, 3, 5, 7, 9, 10 } },
  716. { "Phrygian", { 0, 1, 3, 5, 7, 8, 10 } },
  717. { "Lydian", { 0, 2, 4, 6, 7, 9, 11 } },
  718. { "Mixolydian", { 0, 2, 4, 5, 7, 9, 10 } },
  719. { "Locrian", { 0, 1, 3, 5, 6, 8, 10 } },
  720. { "Major pentatonic", { 0, 2, 4, 7, 9 } },
  721. { "Minor pentatonic", { 0, 3, 5, 7, 10 } },
  722. { "Blues", { 0, 3, 5, 6, 7, 10 } },
  723. { "Whole tone", { 0, 2, 4, 6, 8, 10 } },
  724. { "Diminished", { 0, 2, 3, 5, 6, 8, 9, 11 } },
  725. };
  726. for (const auto& scale : scales)
  727. {
  728. auto s = defaultKeyMapper();
  729. for (int pc = 0; pc < 12; ++pc)
  730. {
  731. int below = 0;
  732. for (const auto n : scale.notes)
  733. if (n <= pc)
  734. below = n;
  735. s.rows[(std::size_t) pc] = { below };
  736. }
  737. out.push_back ({ "Scales", scale.name, writeKeyMapper (s) });
  738. }
  739. auto shifted = [&] (const char* name, std::vector<int> intervals) {
  740. auto s = defaultKeyMapper();
  741. for (int pc = 0; pc < 12; ++pc)
  742. {
  743. s.rows[(std::size_t) pc].clear();
  744. for (const auto i : intervals)
  745. s.rows[(std::size_t) pc].push_back (pc + i);
  746. }
  747. out.push_back ({ "Harmony", name, writeKeyMapper (s) });
  748. };
  749. shifted ("Octave up", { 0, 12 });
  750. shifted ("Octave down", { -12, 0 });
  751. shifted ("Fifth up", { 0, 7 });
  752. shifted ("Fifth down", { -5, 0 });
  753. shifted ("Power chord", { 0, 7, 12 });
  754. shifted ("Major triad", { 0, 4, 7 });
  755. shifted ("Minor triad", { 0, 3, 7 });
  756. auto inverted = defaultKeyMapper();
  757. for (int pc = 0; pc < 12; ++pc)
  758. inverted.rows[(std::size_t) pc] = { 11 - pc };
  759. out.push_back ({ "Special", "Inverted", writeKeyMapper (inverted) });
  760. }
  761. if (kind == Kind::levelScaler)
  762. {
  763. using L = LevelScalerSettings;
  764. auto make = [&] (const char* folder, const char* name, std::function<void (L&)> f) {
  765. auto s = defaultLevelScaler();
  766. f (s);
  767. out.push_back ({ folder, name, writeLevelScaler (s) });
  768. };
  769. make ("Velocity", "Humanize (subtle)", [] (L& s) { s.at (L::velocity, L::humanize) = 2400; });
  770. make ("Velocity", "Humanize (strong)", [] (L& s) { s.at (L::velocity, L::humanize) = 6000; });
  771. make ("Velocity", "Softer", [] (L& s) { s.at (L::velocity, L::multiply) = 6144; });
  772. make ("Velocity", "Compress", [] (L& s) {
  773. s.at (L::velocity, L::center) = 6400;
  774. s.at (L::velocity, L::multiply) = 4096;
  775. });
  776. make ("Velocity", "Expand", [] (L& s) {
  777. s.at (L::velocity, L::center) = 6400;
  778. s.at (L::velocity, L::multiply) = 12288;
  779. });
  780. make ("Velocity", "Fixed", [] (L& s) {
  781. s.at (L::velocity, L::multiply) = 0;
  782. s.at (L::velocity, L::offset) = 6400;
  783. });
  784. make ("Velocity", "Inverted", [] (L& s) {
  785. s.at (L::velocity, L::center) = 4096;
  786. s.at (L::velocity, L::multiply) = -8192;
  787. });
  788. make ("Other", "Random pan", [] (L& s) { s.at (L::pan, L::humanize) = 8192; });
  789. make ("Other", "Detune (random fine pitch)", [] (L& s) { s.at (L::finePitch, L::humanize) = 300; });
  790. make ("Other", "Short releases", [] (L& s) { s.at (L::release, L::offset) = -4096; });
  791. }
  792. return out;
  793. }
  794. std::optional<std::vector<std::uint8_t>> stateFromFlPreset (const std::vector<std::uint8_t>& bytes, Kind kind)
  795. {
  796. try
  797. {
  798. const auto project = flp::parseProject (bytes, true);
  799. if (project.channels.empty() || kindOfFlName (project.channels.front().pluginName) != kind)
  800. return std::nullopt;
  801. return project.channels.front().pluginState;
  802. }
  803. catch (const flp::Error&)
  804. {
  805. return std::nullopt;
  806. }
  807. }
  808. // ---------------------------------------------------------------------------------------------------------------
  809. std::vector<std::uint8_t> defaultState (Kind kind)
  810. {
  811. switch (kind)
  812. {
  813. case Kind::keyMapper: return writeKeyMapper (defaultKeyMapper());
  814. case Kind::colorMapper: return writeColorMapper (defaultColorMapper());
  815. case Kind::levelScaler: return writeLevelScaler (defaultLevelScaler());
  816. case Kind::keyboardSplitter: return writeKeyboardSplitter (defaultKeyboardSplitter());
  817. case Kind::envelope: return writeEnvelope (defaultEnvelope());
  818. default: break;
  819. }
  820. return {};
  821. }
  822. int outputCount (Kind kind) noexcept
  823. {
  824. return kind == Kind::colorMapper || kind == Kind::keyboardSplitter ? 16 : 1;
  825. }
  826. int outputsShown (Kind kind) noexcept
  827. {
  828. return kind == Kind::colorMapper || kind == Kind::keyboardSplitter ? 4 : 1;
  829. }
  830. std::string outputName (Kind kind, int output)
  831. {
  832. if (kind == Kind::colorMapper)
  833. return "Voice " + std::to_string (output + 1);
  834. if (kind == Kind::keyboardSplitter)
  835. return "Zone " + std::to_string (output + 1);
  836. return "Voice output";
  837. }
  838. std::optional<State> readState (const std::vector<std::uint8_t>& pluginState)
  839. {
  840. Reader r { pluginState.data(), pluginState.size() };
  841. if (r.u32() != lynxMagic)
  842. return std::nullopt;
  843. const auto kind = r.u32();
  844. const auto port = r.i32();
  845. r.u32(); // (reserved)
  846. if (r.failed || kind >= (std::uint32_t) kindCount)
  847. return std::nullopt;
  848. State s;
  849. s.kind = (Kind) kind;
  850. s.port = std::clamp (port, 0, 255);
  851. s.fl.assign (pluginState.begin() + (std::ptrdiff_t) r.pos, pluginState.end());
  852. return s;
  853. }
  854. std::vector<std::uint8_t> writeState (const State& state)
  855. {
  856. std::vector<std::uint8_t> out;
  857. put<std::uint32_t> (out, lynxMagic);
  858. put<std::uint32_t> (out, (std::uint32_t) state.kind);
  859. put<std::int32_t> (out, state.port);
  860. put<std::uint32_t> (out, 0);
  861. out.insert (out.end(), state.fl.begin(), state.fl.end());
  862. return out;
  863. }
  864. void makeChannel (ChannelDef& channel, Kind kind)
  865. {
  866. channel.instrument = InstrumentKind::vfx;
  867. channel.name = flName (kind);
  868. State s;
  869. s.kind = kind;
  870. s.fl = defaultState (kind);
  871. channel.pluginState = writeState (s);
  872. }
  873. std::optional<Kind> kindOf (const ChannelDef& channel)
  874. {
  875. if (channel.instrument != InstrumentKind::vfx)
  876. return std::nullopt;
  877. if (auto s = readState (channel.pluginState))
  878. return s->kind;
  879. return std::nullopt;
  880. }
  881. // ---------------------------------------------------------------------------------------------------------------
  882. // Processors
  883. namespace
  884. {
  885. // What every processor keeps: the voices it sent out for each input voice, so an input's "off" ends exactly them
  886. // (even after the settings changed) and releaseAll ends everything.
  887. struct VoiceTable
  888. {
  889. struct Entry
  890. {
  891. int input = -1; // input id
  892. int id = 0; // output voice id
  893. int output = 0;
  894. Voice voice;
  895. float slide = 0.0f; // Key Mapper's pitch slide: cents still to go (0 = none)
  896. };
  897. std::array<Entry, 512> entries {};
  898. int count = 0;
  899. int nextId = 1;
  900. int add (int input, int output, const Voice& v) noexcept
  901. {
  902. if (count >= (int) entries.size())
  903. return -1;
  904. auto& e = entries[(std::size_t) count++];
  905. e.input = input;
  906. e.output = output;
  907. e.voice = v;
  908. e.slide = 0.0f;
  909. e.id = nextId++;
  910. if (nextId > 1 << 30)
  911. nextId = 1;
  912. return e.id;
  913. }
  914. // sends the "off" of every voice of `input` (all with input < 0)
  915. void release (int input, int offset, float releaseVelocity, EventList& out) noexcept
  916. {
  917. int kept = 0;
  918. for (int i = 0; i < count; ++i)
  919. {
  920. auto& e = entries[(std::size_t) i];
  921. if (input >= 0 && e.input != input)
  922. {
  923. entries[(std::size_t) kept++] = e;
  924. continue;
  925. }
  926. Event off;
  927. off.type = Event::Type::off;
  928. off.offset = offset;
  929. off.output = e.output;
  930. off.id = e.id;
  931. off.voice = e.voice;
  932. off.voice.release = releaseVelocity;
  933. out.add (off);
  934. }
  935. count = kept;
  936. }
  937. };
  938. Event onEvent (int offset, int output, int id, const Voice& v) noexcept
  939. {
  940. Event e;
  941. e.type = Event::Type::on;
  942. e.offset = offset;
  943. e.output = output;
  944. e.id = id;
  945. e.voice = v;
  946. return e;
  947. }
  948. // A processor whose settings are FL's parsed state
  949. template <typename Settings>
  950. class Base : public Processor
  951. {
  952. public:
  953. explicit Base (Settings initial) : settings (std::move (initial)) {}
  954. void releaseAll (EventList& out) noexcept override { voices.release (-1, 0, 0.5f, out); }
  955. bool busy() const noexcept override { return voices.count > 0; }
  956. protected:
  957. const Settings& current() noexcept
  958. {
  959. settings.take();
  960. return settings.get();
  961. }
  962. void publish (Settings s) { settings.publish (std::move (s)); }
  963. VoiceTable voices;
  964. private:
  965. Handoff<Settings> settings;
  966. };
  967. // Notes pass unchanged (a plugin whose behaviour LYNX does not reproduce yet keeps the notes flowing)
  968. class ThroughProcessor final : public Processor
  969. {
  970. public:
  971. explicit ThroughProcessor (Kind k) : which (k) {}
  972. Kind kind() const noexcept override { return which; }
  973. void releaseAll (EventList& out) noexcept override { voices.release (-1, 0, 0.5f, out); }
  974. void process (const Event* in, int count, int, const Transport&, EventList& out) noexcept override
  975. {
  976. for (int i = 0; i < count; ++i)
  977. {
  978. const auto& e = in[i];
  979. if (e.type == Event::Type::on)
  980. {
  981. if (const auto id = voices.add (e.id, 0, e.voice); id >= 0)
  982. out.add (onEvent (e.offset, 0, id, e.voice));
  983. }
  984. else if (e.type == Event::Type::off)
  985. voices.release (e.id, e.offset, e.voice.release, out);
  986. }
  987. }
  988. bool configure (const std::vector<std::uint8_t>&) override { return true; }
  989. private:
  990. Kind which;
  991. VoiceTable voices;
  992. };
  993. class KeyMapper final : public Base<KeyMapperSettings>
  994. {
  995. public:
  996. explicit KeyMapper (KeyMapperSettings s) : Base (std::move (s)) {}
  997. Kind kind() const noexcept override { return Kind::keyMapper; }
  998. bool configure (const std::vector<std::uint8_t>& fl) override
  999. {
  1000. auto s = parseKeyMapper (fl);
  1001. if (! s)
  1002. return false;
  1003. publish (std::move (*s));
  1004. return true;
  1005. }
  1006. void process (const Event* in, int count, int n, const Transport& transport, EventList& out) noexcept override
  1007. {
  1008. const auto& s = current();
  1009. // the slides under way move on (FL: the voice's pitch covers 99 % of the way in `slide` / 192 beats)
  1010. if (s.slide > 0)
  1011. {
  1012. const auto beats = (double) n * transport.bpm / (60.0 * std::max (1.0, transport.sampleRate));
  1013. const auto keep = (float) std::pow (0.01, beats * 192.0 / (double) s.slide);
  1014. for (int i = 0; i < voices.count; ++i)
  1015. slideStep (voices.entries[(std::size_t) i], keep, out);
  1016. }
  1017. else
  1018. for (int i = 0; i < voices.count; ++i)
  1019. slideStep (voices.entries[(std::size_t) i], 0.0f, out);
  1020. for (int i = 0; i < count; ++i)
  1021. {
  1022. const auto& e = in[i];
  1023. if (e.type == Event::Type::off)
  1024. {
  1025. voices.release (e.id, e.offset, e.voice.release, out);
  1026. continue;
  1027. }
  1028. if (e.type != Event::Type::on)
  1029. continue;
  1030. if (! s.enabled)
  1031. {
  1032. send (e, e.voice, 0, out);
  1033. continue;
  1034. }
  1035. // FL: the row of the input's pitch class counted from the base key; its values are semitones from the start
  1036. // of that octave (on the base key); the offset transposes what comes out
  1037. const auto k = std::max (0, e.voice.key - s.baseKey + 12);
  1038. const auto rowIndex = k % 12;
  1039. const auto octaveStart = e.voice.key - rowIndex;
  1040. const auto& row = s.rows[(std::size_t) rowIndex];
  1041. const auto size = (int) row.size();
  1042. if (size == 0)
  1043. continue; // (the note is muted)
  1044. auto play = [&] (int value, float gain) {
  1045. auto v = e.voice;
  1046. v.key = octaveStart + value + s.offset;
  1047. if (v.key < 0 || v.key > 127)
  1048. return;
  1049. v.velocity *= gain;
  1050. // with a pitch slide the new note starts at the played pitch and glides to its own
  1051. const auto slide = s.slide > 0 ? (float) (e.voice.key - v.key) * 100.0f : 0.0f;
  1052. send (e, v, slide, out);
  1053. };
  1054. switch (s.multimode)
  1055. {
  1056. case 1: // all, gain-compensated (1 / sqrt n)
  1057. for (const auto value : row)
  1058. play (value, 1.0f / std::sqrt ((float) size));
  1059. break;
  1060. case 2: // one of them at random
  1061. play (row[(std::size_t) (nextRandom() % (std::uint32_t) size)], 1.0f);
  1062. break;
  1063. case 3: // the next one in the row's order (the first first)
  1064. {
  1065. auto& c = cycle[(std::size_t) rowIndex];
  1066. const auto at = ((c % size) + size) % size;
  1067. c = at + 1;
  1068. play (row[(std::size_t) at], 1.0f);
  1069. break;
  1070. }
  1071. case 4: // backwards (the last first)
  1072. {
  1073. auto& c = cycle[(std::size_t) rowIndex];
  1074. c = (((c + size - 1) % size) + size) % size;
  1075. play (row[(std::size_t) c], 1.0f);
  1076. break;
  1077. }
  1078. default:
  1079. for (const auto value : row)
  1080. play (value, 1.0f);
  1081. break;
  1082. }
  1083. }
  1084. }
  1085. void releaseAll (EventList& out) noexcept override
  1086. {
  1087. voices.release (-1, 0, 0.5f, out);
  1088. cycle.fill (0); // (FL: a flush starts the cycles again)
  1089. }
  1090. private:
  1091. void send (const Event& input, Voice v, float slide, EventList& out) noexcept
  1092. {
  1093. const auto cents = v.cents;
  1094. v.cents += slide;
  1095. if (const auto id = voices.add (input.id, 0, v); id >= 0)
  1096. {
  1097. out.add (onEvent (input.offset, 0, id, v));
  1098. auto& entry = voices.entries[(std::size_t) voices.count - 1];
  1099. entry.slide = slide;
  1100. entry.voice.cents = cents;
  1101. }
  1102. }
  1103. // one block of a voice's slide: `keep` of the way left stays (a prop event with its pitch)
  1104. static void slideStep (VoiceTable::Entry& e, float keep, EventList& out) noexcept
  1105. {
  1106. if (e.slide == 0.0f)
  1107. return;
  1108. e.slide *= keep;
  1109. if (std::abs (e.slide) < 0.5f)
  1110. e.slide = 0.0f;
  1111. Event p;
  1112. p.type = Event::Type::prop;
  1113. p.output = e.output;
  1114. p.id = e.id;
  1115. p.voice = e.voice;
  1116. p.prop = Prop::pitch;
  1117. p.value = e.voice.cents + e.slide;
  1118. out.add (p);
  1119. }
  1120. std::uint32_t nextRandom() noexcept
  1121. {
  1122. seed ^= seed << 13;
  1123. seed ^= seed >> 17;
  1124. seed ^= seed << 5;
  1125. return seed;
  1126. }
  1127. std::array<int, 12> cycle {};
  1128. std::uint32_t seed = 0x9e3779b9u;
  1129. };
  1130. class ColorMapper final : public Base<ColorMapperSettings>
  1131. {
  1132. public:
  1133. explicit ColorMapper (ColorMapperSettings s) : Base (std::move (s)) {}
  1134. Kind kind() const noexcept override { return Kind::colorMapper; }
  1135. bool configure (const std::vector<std::uint8_t>& fl) override
  1136. {
  1137. auto s = parseColorMapper (fl);
  1138. if (! s)
  1139. return false;
  1140. publish (*s);
  1141. return true;
  1142. }
  1143. void process (const Event* in, int count, int, const Transport&, EventList& out) noexcept override
  1144. {
  1145. const auto& s = current();
  1146. for (int i = 0; i < count; ++i)
  1147. {
  1148. const auto& e = in[i];
  1149. if (e.type == Event::Type::off)
  1150. {
  1151. voices.release (e.id, e.offset, e.voice.release, out);
  1152. continue;
  1153. }
  1154. if (e.type != Event::Type::on)
  1155. continue;
  1156. const auto c = e.voice.colour & 15;
  1157. auto v = e.voice;
  1158. v.colour = s.colour[(std::size_t) c];
  1159. const auto port = s.port[(std::size_t) c];
  1160. if (const auto id = voices.add (e.id, port, v); id >= 0)
  1161. out.add (onEvent (e.offset, port, id, v));
  1162. }
  1163. }
  1164. };
  1165. } // namespace
  1166. namespace
  1167. {
  1168. // One voice in, one voice out, its velocity, fine pitch, pan, Mod X / Y and release velocity through the curves.
  1169. // (FL re-evaluates the curves every tick from the parent's live levels; LYNX applies them when the note starts and
  1170. // to its release velocity when it ends: the voices' levels do not change on their way here.)
  1171. class LevelScaler final : public Base<LevelScalerSettings>
  1172. {
  1173. public:
  1174. explicit LevelScaler (LevelScalerSettings s) : Base (std::move (s)) {}
  1175. Kind kind() const noexcept override { return Kind::levelScaler; }
  1176. bool configure (const std::vector<std::uint8_t>& fl) override
  1177. {
  1178. auto s = parseLevelScaler (fl);
  1179. if (! s)
  1180. return false;
  1181. publish (std::move (*s));
  1182. return true;
  1183. }
  1184. void process (const Event* in, int count, int, const Transport&, EventList& out) noexcept override
  1185. {
  1186. using L = LevelScalerSettings;
  1187. const auto& s = current();
  1188. for (int i = 0; i < count; ++i)
  1189. {
  1190. const auto& e = in[i];
  1191. if (e.type == Event::Type::on)
  1192. {
  1193. auto v = e.voice;
  1194. // (FL's order: pan, Mod X, Mod Y, fine pitch, velocity; each with its own random, fixed for the note)
  1195. v.pan = (float) levelScale (s, L::pan, v.pan, -1.0, 1.0, random());
  1196. v.modX = (float) (levelScale (s, L::modX, v.modX * 2.0 - 1.0, -1.0, 1.0, random()) * 0.5 + 0.5);
  1197. v.modY = (float) (levelScale (s, L::modY, v.modY * 2.0 - 1.0, -1.0, 1.0, random()) * 0.5 + 0.5);
  1198. v.cents = (float) (levelScale (s, L::finePitch, v.cents / 1200.0, -1.0, 1.0, random()) * 1200.0);
  1199. v.velocity = (float) levelScale (s, L::velocity, v.velocity, 0.0, 1.0, random());
  1200. if (const auto id = voices.add (e.id, 0, v); id >= 0)
  1201. out.add (onEvent (e.offset, 0, id, v));
  1202. }
  1203. else if (e.type == Event::Type::off)
  1204. voices.release (e.id, e.offset, (float) levelScale (s, L::release, e.voice.release, 0.0, 1.0, random()), out);
  1205. }
  1206. }
  1207. private:
  1208. double random() noexcept
  1209. {
  1210. seed ^= seed << 13;
  1211. seed ^= seed >> 17;
  1212. seed ^= seed << 5;
  1213. return (double) (seed >> 8) / 16777216.0;
  1214. }
  1215. std::uint32_t seed = 0x2545f491u;
  1216. };
  1217. } // namespace
  1218. namespace
  1219. {
  1220. // Each note on every zone whose keyboard × velocity level is above zero, on that zone's output (FL: the level
  1221. // scales the note's volume, or replaces it with Absolute; Random zones play one of them, picked by their keyboard
  1222. // level). LYNX works in velocities: vol = (11^(1.28 v) − 1) / 10 both ways.
  1223. class KeyboardSplitter final : public Base<KeyboardSplitterSettings>
  1224. {
  1225. public:
  1226. explicit KeyboardSplitter (KeyboardSplitterSettings s) : Base (std::move (s)) {}
  1227. Kind kind() const noexcept override { return Kind::keyboardSplitter; }
  1228. bool configure (const std::vector<std::uint8_t>& fl) override
  1229. {
  1230. auto s = parseKeyboardSplitter (fl);
  1231. if (! s)
  1232. return false;
  1233. publish (std::move (*s));
  1234. return true;
  1235. }
  1236. void process (const Event* in, int count, int, const Transport&, EventList& out) noexcept override
  1237. {
  1238. const auto& s = current();
  1239. for (int i = 0; i < count; ++i)
  1240. {
  1241. const auto& e = in[i];
  1242. if (e.type == Event::Type::off)
  1243. {
  1244. voices.release (e.id, e.offset, e.voice.release, out);
  1245. continue;
  1246. }
  1247. if (e.type != Event::Type::on)
  1248. continue;
  1249. const auto x = ((double) e.voice.key + e.voice.cents / 100.0) / 132.0;
  1250. const auto velocity = std::min (1.0, (double) e.voice.velocity);
  1251. std::array<double, 16> w {};
  1252. bool anyRandom = false;
  1253. for (int z = 0; z < 16; ++z)
  1254. {
  1255. const auto& zone = s.zones[(std::size_t) z];
  1256. if (! zone.active())
  1257. continue;
  1258. w[(std::size_t) z] = splitterGain (zone.keyboard.at (x));
  1259. anyRandom = anyRandom || zone.random;
  1260. }
  1261. if (anyRandom) // one weighted pick among the random zones, which then plays at full level
  1262. {
  1263. double total = 0.0;
  1264. for (int z = 0; z < 16; ++z)
  1265. if (s.zones[(std::size_t) z].random && s.zones[(std::size_t) z].active())
  1266. total += w[(std::size_t) z];
  1267. const auto r = random() * total;
  1268. int chosen = -1;
  1269. double acc = 0.0;
  1270. for (int z = 0; z < 16; ++z)
  1271. if (s.zones[(std::size_t) z].random && s.zones[(std::size_t) z].active() && w[(std::size_t) z] > 0.0)
  1272. {
  1273. if (acc <= r)
  1274. chosen = z;
  1275. acc += w[(std::size_t) z];
  1276. w[(std::size_t) z] = 0.0;
  1277. }
  1278. if (chosen >= 0) // (FL then falls back on zone 1; LYNX plays no random zone)
  1279. w[(std::size_t) chosen] = 1.0;
  1280. }
  1281. const auto volumeIn = velocityToVolume (velocity);
  1282. for (int z = 0; z < 16; ++z)
  1283. {
  1284. const auto& zone = s.zones[(std::size_t) z];
  1285. if (w[(std::size_t) z] <= 0.0)
  1286. continue;
  1287. const auto level = w[(std::size_t) z] * splitterGain (zone.velocity.at (velocity));
  1288. if (level <= 1e-5)
  1289. continue;
  1290. auto v = e.voice;
  1291. v.velocity = (float) volumeToVelocity (zone.absolute ? level : volumeIn * level);
  1292. v.key = e.voice.key + zone.transpose;
  1293. if (v.key < 0 || v.key > 127)
  1294. continue;
  1295. if (const auto id = voices.add (e.id, z, v); id >= 0)
  1296. out.add (onEvent (e.offset, z, id, v));
  1297. }
  1298. }
  1299. }
  1300. private:
  1301. static double velocityToVolume (double v) noexcept { return (std::pow (11.0, 1.28 * v) - 1.0) / 10.0; }
  1302. static double volumeToVelocity (double vol) noexcept { return std::clamp (std::log (10.0 * vol + 1.0) / std::log (11.0) / 1.28, 0.0, 1.0); }
  1303. double random() noexcept
  1304. {
  1305. seed ^= seed << 13;
  1306. seed ^= seed >> 17;
  1307. seed ^= seed << 5;
  1308. return (double) (seed >> 8) / 16777216.0;
  1309. }
  1310. std::uint32_t seed = 0x12bd6aau;
  1311. };
  1312. } // namespace
  1313. namespace
  1314. {
  1315. // An FL curve as the Envelope Controller's (core/FlSynths.h): accumulated points, LYNX's tension sign on the segment
  1316. // starting at a point, a hold as a step
  1317. void toArticulator (const MapCurve& m, ControllerArticulator& a)
  1318. {
  1319. a.count = 0;
  1320. a.sustain = -1;
  1321. a.decayPoint = -1;
  1322. const auto sustain = m.footer[4], decay = m.footer[2];
  1323. for (std::size_t i = 0; i < m.points.size() && a.count < (int) a.time.size(); ++i)
  1324. {
  1325. const auto& p = m.points[i];
  1326. if (i > 0)
  1327. {
  1328. if (p.curve == 2 && p.x > m.points[i - 1].x && a.count + 1 < (int) a.time.size())
  1329. {
  1330. a.time[(std::size_t) a.count] = (float) p.x;
  1331. a.level[(std::size_t) a.count] = a.level[(std::size_t) a.count - 1];
  1332. a.tension[(std::size_t) a.count] = 0.0f;
  1333. ++a.count;
  1334. }
  1335. else if (p.curve <= 1)
  1336. a.tension[(std::size_t) a.count - 1] = std::clamp (-p.tension, -1.0f, 1.0f);
  1337. }
  1338. if ((int) i == sustain)
  1339. a.sustain = a.count;
  1340. if ((int) i == decay)
  1341. a.decayPoint = a.count;
  1342. a.time[(std::size_t) a.count] = (float) p.x;
  1343. a.level[(std::size_t) a.count] = (float) std::clamp (p.y, 0.0, 1.0);
  1344. a.tension[(std::size_t) a.count] = 0.0f;
  1345. ++a.count;
  1346. }
  1347. }
  1348. // What the audio thread evaluates: per articulator and target the envelope, the LFO amplitude and the LFO wave
  1349. struct EnvelopeRuntime
  1350. {
  1351. struct Part
  1352. {
  1353. bool envOn = false, lfoOn = false, envTempo = false, lfoTempo = false;
  1354. float base = 0.5f, env = 0.0f, lfo = 0.0f, offset = 0.5f;
  1355. ControllerArticulator envelope, amplitude, wave; // (levels 0…1 with base 0: their curves' values)
  1356. double rate = 1.0, startPhase = 0.0; // LFO: cycles per unit, phase at the trigger
  1357. };
  1358. struct Articulator
  1359. {
  1360. int colour = 0, low = 0, high = 132;
  1361. std::array<Part, 5> parts;
  1362. };
  1363. bool enabled = true;
  1364. std::array<Articulator, 16> articulators;
  1365. // (big: on the heap, never on a stack)
  1366. static std::unique_ptr<EnvelopeRuntime> from (const EnvelopeSettings& s)
  1367. {
  1368. auto made = std::make_unique<EnvelopeRuntime>();
  1369. auto& rt = *made;
  1370. rt.enabled = s.enabled;
  1371. for (int g = 0; g < 16; ++g)
  1372. {
  1373. const auto& a = s.articulators[(std::size_t) g];
  1374. auto& r = rt.articulators[(std::size_t) g];
  1375. r.colour = a.colour;
  1376. r.low = a.low;
  1377. r.high = a.high;
  1378. for (int t = 0; t < 5; ++t)
  1379. {
  1380. const auto& p = a.parts[(std::size_t) t];
  1381. auto& q = r.parts[(std::size_t) t];
  1382. q.envOn = p.envOn() && ! p.envelope.points.empty();
  1383. q.lfoOn = p.lfoOn();
  1384. q.envTempo = (p.envelope.footer[0] & 1) != 0;
  1385. q.lfoTempo = (p.lfoAmp.footer[0] & 1) != 0;
  1386. q.base = p.base;
  1387. q.env = p.env;
  1388. q.lfo = p.lfo;
  1389. q.offset = t == EnvelopeSettings::velocity ? 0.0f : 0.5f;
  1390. toArticulator (p.envelope, q.envelope);
  1391. q.envelope.adsr = p.adsr;
  1392. q.envelope = controllerWithKnobs (q.envelope);
  1393. for (auto* c : { &q.envelope, &q.amplitude })
  1394. {
  1395. c->base = 0.0f;
  1396. c->envLevel = 1.0f;
  1397. c->bipolar = false;
  1398. c->envOn = true;
  1399. }
  1400. toArticulator (p.lfoAmp, q.amplitude);
  1401. q.wave.lfoSpeed = p.speed;
  1402. q.wave.lfoTension = p.tension;
  1403. q.wave.lfoSkew = p.skew;
  1404. q.wave.lfoPulseWidth = p.pulseWidth;
  1405. q.wave.lfoPhase = p.phase;
  1406. q.rate = controllerLfoRate (q.wave);
  1407. q.startPhase = controllerLfoStartPhase (q.wave);
  1408. }
  1409. }
  1410. return made;
  1411. }
  1412. };
  1413. // One note in, the same note out, its volume, fine pitch, pan and Mod X / Y moved by the envelopes and LFOs of every
  1414. // articulator whose note colour and key range it matches (FL re-applies them each tick; LYNX each block).
  1415. class Envelope final : public Processor
  1416. {
  1417. public:
  1418. explicit Envelope (const EnvelopeSettings& s) : settings (EnvelopeRuntime::from (s)) {}
  1419. Kind kind() const noexcept override { return Kind::envelope; }
  1420. bool configure (const std::vector<std::uint8_t>& fl) override
  1421. {
  1422. auto s = parseEnvelope (fl);
  1423. if (! s)
  1424. return false;
  1425. settings.publish (EnvelopeRuntime::from (*s));
  1426. return true;
  1427. }
  1428. bool busy() const noexcept override { return count > 0; }
  1429. void releaseAll (EventList& out) noexcept override
  1430. {
  1431. for (int i = 0; i < count; ++i)
  1432. if (! voices[(std::size_t) i].released)
  1433. out.add (offEvent (voices[(std::size_t) i], 0));
  1434. count = 0;
  1435. }
  1436. void process (const Event* in, int n, int samples, const Transport& transport, EventList& out) noexcept override
  1437. {
  1438. settings.take();
  1439. const auto& rt = settings.get();
  1440. const auto seconds = samples / std::max (1.0, transport.sampleRate);
  1441. const auto beats = seconds * transport.bpm / 60.0;
  1442. // the voices sounding move on (and send what changed)
  1443. for (int i = 0; i < count; ++i)
  1444. {
  1445. auto& v = voices[(std::size_t) i];
  1446. v.seconds += seconds;
  1447. v.beats += beats;
  1448. if (v.released)
  1449. {
  1450. v.releaseSeconds += seconds;
  1451. v.releaseBeats += beats;
  1452. }
  1453. apply (rt, v, 0, &out);
  1454. }
  1455. // the finished ones go (their output was released and their envelopes have ended, or 30 s after the release)
  1456. int kept = 0;
  1457. for (int i = 0; i < count; ++i)
  1458. {
  1459. const auto& v = voices[(std::size_t) i];
  1460. if (v.released && (v.releaseSeconds > 30.0 || finished (rt, v)))
  1461. continue;
  1462. voices[(std::size_t) kept++] = v;
  1463. }
  1464. count = kept;
  1465. for (int i = 0; i < n; ++i)
  1466. {
  1467. const auto& e = in[i];
  1468. if (e.type == Event::Type::on)
  1469. {
  1470. Voice v;
  1471. v.input = e.id;
  1472. v.id = nextId++;
  1473. if (nextId > 1 << 30)
  1474. nextId = 1;
  1475. v.source = e.voice;
  1476. v.sent = e.voice;
  1477. for (int g = 0; g < 16; ++g)
  1478. {
  1479. const auto& a = rt.articulators[(std::size_t) g];
  1480. const auto key = e.voice.key + 1;
  1481. if (a.colour == e.voice.colour && key >= a.low && key <= a.high)
  1482. v.matched |= (std::uint16_t) (1u << g);
  1483. }
  1484. Voice playing = v;
  1485. apply (rt, playing, e.offset, nullptr);
  1486. out.add (onEvent (e.offset, 0, playing.id, playing.sent));
  1487. if (count < (int) voices.size())
  1488. voices[(std::size_t) count++] = playing;
  1489. }
  1490. else if (e.type == Event::Type::off)
  1491. for (int k = 0; k < count; ++k)
  1492. {
  1493. auto& v = voices[(std::size_t) k];
  1494. if (v.input == e.id && ! v.released)
  1495. {
  1496. v.released = true;
  1497. v.source.release = e.voice.release;
  1498. out.add (offEvent (v, e.offset));
  1499. }
  1500. }
  1501. }
  1502. }
  1503. private:
  1504. struct Voice
  1505. {
  1506. int input = -1, id = 0;
  1507. Voice() = default;
  1508. vfx::Voice source, sent;
  1509. std::uint16_t matched = 0;
  1510. bool released = false;
  1511. double seconds = 0.0, beats = 0.0, releaseSeconds = 0.0, releaseBeats = 0.0;
  1512. };
  1513. static Event offEvent (const Voice& v, int offset) noexcept
  1514. {
  1515. Event e;
  1516. e.type = Event::Type::off;
  1517. e.offset = offset;
  1518. e.id = v.id;
  1519. e.voice = v.sent;
  1520. e.voice.release = v.source.release;
  1521. return e;
  1522. }
  1523. // the voice's levels now (FL's per-voice apply); with `out`, prop events for what changed
  1524. static void apply (const EnvelopeRuntime& rt, Voice& v, int offset, EventList* out) noexcept
  1525. {
  1526. auto now = v.source;
  1527. if (rt.enabled && v.matched != 0)
  1528. {
  1529. const auto sourceVolume = (std::pow (11.0, 1.28 * (double) v.source.velocity) - 1.0) / 10.0;
  1530. auto volume = sourceVolume;
  1531. double cents = v.source.cents, pan = v.source.pan, modX = v.source.modX * 2.0 - 1.0, modY = v.source.modY * 2.0 - 1.0;
  1532. for (int g = 15; g >= 0; --g) // (FL: the last articulator first)
  1533. {
  1534. if ((v.matched & (1u << g)) == 0)
  1535. continue;
  1536. for (int t = 4; t >= 0; --t)
  1537. {
  1538. const auto& p = rt.articulators[(std::size_t) g].parts[(std::size_t) t];
  1539. if (! p.envOn && ! p.lfoOn)
  1540. continue;
  1541. const auto envTime = p.envTempo ? v.beats : v.seconds;
  1542. const auto envRelease = ! v.released ? -1.0 : p.envTempo ? v.releaseBeats : v.releaseSeconds;
  1543. const auto e = p.envOn ? controllerValue (p.envelope, envTime, envRelease) - p.offset : 0.0f;
  1544. double l = 0.0;
  1545. if (p.lfoOn)
  1546. {
  1547. const auto lfoTime = p.lfoTempo ? v.beats : v.seconds;
  1548. const auto lfoRelease = ! v.released ? -1.0 : p.lfoTempo ? v.releaseBeats : v.releaseSeconds;
  1549. const auto amp = controllerValue (p.amplitude, lfoTime, lfoRelease) - 0.5;
  1550. l = amp * controllerLfoWave (p.wave, p.startPhase + p.rate * lfoTime);
  1551. }
  1552. if (t == EnvelopeSettings::velocity)
  1553. {
  1554. double m = p.base;
  1555. if (p.envOn)
  1556. m = p.env >= 0.0f ? p.base + 2.0 * p.env * e : (1.0 - p.base) + 2.0 * std::abs (p.env) * (1.0 - e);
  1557. if (p.lfoOn)
  1558. m *= 2.0 * p.lfo * l;
  1559. volume = std::clamp (volume * m, 0.0, 4.0);
  1560. continue;
  1561. }
  1562. auto d = (double) p.base - 0.5;
  1563. if (p.envOn)
  1564. d += 2.0 * p.env * e;
  1565. if (p.lfoOn)
  1566. d += 2.0 * p.lfo * l;
  1567. if (t == EnvelopeSettings::pitch)
  1568. cents += d * 4800.0;
  1569. else if (t == EnvelopeSettings::pan)
  1570. pan = std::clamp (pan + d, -1.0, 1.0);
  1571. else if (t == EnvelopeSettings::modX)
  1572. modX = std::clamp (modX + d, -2.0, 2.0);
  1573. else
  1574. modY = std::clamp (modY + d, -2.0, 2.0);
  1575. }
  1576. }
  1577. if (volume != sourceVolume)
  1578. now.velocity = (float) std::clamp (std::log (10.0 * volume + 1.0) / std::log (11.0) / 1.28, 0.0, 1.0);
  1579. now.cents = (float) std::clamp (cents, -v.source.key * 100.0, 12000.0 - v.source.key * 100.0); // (FL: Init.Pitch 0…12000)
  1580. now.pan = (float) pan;
  1581. now.modX = (float) std::clamp (modX * 0.5 + 0.5, 0.0, 1.0);
  1582. now.modY = (float) std::clamp (modY * 0.5 + 0.5, 0.0, 1.0);
  1583. }
  1584. if (out != nullptr)
  1585. {
  1586. auto send = [&] (Prop prop, float before, float after) {
  1587. if (std::abs (after - before) < 1e-4f)
  1588. return;
  1589. Event p;
  1590. p.type = Event::Type::prop;
  1591. p.offset = offset;
  1592. p.id = v.id;
  1593. p.voice = v.sent;
  1594. p.prop = prop;
  1595. p.value = after;
  1596. out->add (p);
  1597. };
  1598. send (Prop::velocity, v.sent.velocity, now.velocity);
  1599. send (Prop::pitch, v.sent.cents, now.cents);
  1600. send (Prop::pan, v.sent.pan, now.pan);
  1601. send (Prop::modX, v.sent.modX, now.modX);
  1602. send (Prop::modY, v.sent.modY, now.modY);
  1603. }
  1604. now.key = v.source.key;
  1605. v.sent = now;
  1606. }
  1607. static bool finished (const EnvelopeRuntime& rt, const Voice& v) noexcept
  1608. {
  1609. if (! rt.enabled || v.matched == 0)
  1610. return true;
  1611. for (int g = 0; g < 16; ++g)
  1612. if ((v.matched & (1u << g)) != 0)
  1613. for (const auto& p : rt.articulators[(std::size_t) g].parts)
  1614. {
  1615. if (p.envOn && ! controllerVoiceFinished (p.envelope, p.envTempo ? v.beats : v.seconds, p.envTempo ? v.releaseBeats : v.releaseSeconds))
  1616. return false;
  1617. if (p.lfoOn && ! controllerVoiceFinished (p.amplitude, p.lfoTempo ? v.beats : v.seconds, p.lfoTempo ? v.releaseBeats : v.releaseSeconds))
  1618. return false;
  1619. }
  1620. return true;
  1621. }
  1622. Handoff<EnvelopeRuntime> settings;
  1623. std::array<Voice, 256> voices {};
  1624. int count = 0, nextId = 1;
  1625. };
  1626. } // namespace
  1627. std::unique_ptr<Processor> makeProcessor (Kind kind, const std::vector<std::uint8_t>& fl)
  1628. {
  1629. switch (kind)
  1630. {
  1631. case Kind::keyMapper:
  1632. return std::make_unique<KeyMapper> (parseKeyMapper (fl).value_or (defaultKeyMapper()));
  1633. case Kind::colorMapper:
  1634. return std::make_unique<ColorMapper> (parseColorMapper (fl).value_or (defaultColorMapper()));
  1635. case Kind::levelScaler:
  1636. return std::make_unique<LevelScaler> (parseLevelScaler (fl).value_or (defaultLevelScaler()));
  1637. case Kind::keyboardSplitter:
  1638. return std::make_unique<KeyboardSplitter> (parseKeyboardSplitter (fl).value_or (defaultKeyboardSplitter()));
  1639. case Kind::envelope:
  1640. return std::make_unique<Envelope> (parseEnvelope (fl).value_or (defaultEnvelope()));
  1641. default: break;
  1642. }
  1643. return std::make_unique<ThroughProcessor> (kind);
  1644. }
  1645. } // namespace lynx::vfx