FlPatcher.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. #include "core/FlPatcher.h"
  2. #include <algorithm>
  3. #include <cctype>
  4. #include <cmath>
  5. #include <cstring>
  6. #include <functional>
  7. #include <map>
  8. #include <set>
  9. namespace lynx
  10. {
  11. namespace
  12. {
  13. template <typename T>
  14. T at (const std::uint8_t* p, std::size_t offset)
  15. {
  16. T v {};
  17. std::memcpy (&v, p + offset, sizeof (T));
  18. return v;
  19. }
  20. // chunks "u32 id + u64 size + data"; id 0 = group (the content is more chunks)
  21. bool forEachChunk (const std::uint8_t* p, std::size_t size, const std::function<void (std::uint32_t, const std::uint8_t*, std::size_t)>& fn)
  22. {
  23. std::size_t pos = 0;
  24. while (pos + 12 <= size)
  25. {
  26. const auto id = at<std::uint32_t> (p, pos);
  27. const auto length = at<std::uint64_t> (p, pos + 4);
  28. if (length > size - pos - 12)
  29. return false;
  30. fn (id, p + pos + 12, (std::size_t) length);
  31. pos += 12 + (std::size_t) length;
  32. }
  33. return pos == size;
  34. }
  35. std::string text (const std::uint8_t* p, std::size_t size, bool wide)
  36. {
  37. std::string out;
  38. if (wide)
  39. for (std::size_t i = 0; i + 1 < size; i += 2)
  40. out += (char) (p[i] | (p[i + 1] != 0 ? 0x80 : 0)); // plugin names are ASCII
  41. else
  42. out.assign (reinterpret_cast<const char*> (p), size);
  43. while (! out.empty() && out.back() == '\0')
  44. out.pop_back();
  45. return out;
  46. }
  47. struct Port
  48. {
  49. int node = -1; // -1 = Patcher pin
  50. bool input = false; // node input, or pin that takes the sound out
  51. int bus = 0;
  52. int kind = 0; // 0 audio, 1 MIDI, 2 control
  53. };
  54. struct Connection
  55. {
  56. std::uint64_t destination = 0, source = 0;
  57. float gain = 1.0f;
  58. int kind = -1; // −1 = port class (flags bit 1 cleared)
  59. bool disabled = false; // flags bit 0
  60. };
  61. bool isSplitterName (std::string name)
  62. {
  63. for (auto& ch : name)
  64. ch = (char) std::tolower ((unsigned char) ch);
  65. return name == "frequency splitter" || name == "fruity stereo shaper"; // nodes that split by bus
  66. }
  67. // Series-parallel reduction (REA_rodada20 §3.3). Vertices: IN, OUT and, for each node (or splitter node per
  68. // bus), its input and output; edges carry the expression. Repeat: edges with the same endpoints
  69. // become parallel; a vertex with one input and one output becomes series.
  70. struct SpEdge
  71. {
  72. int from, to;
  73. PatcherExpr expr;
  74. };
  75. PatcherExpr flattenSeries (PatcherExpr a, PatcherExpr b)
  76. {
  77. PatcherExpr s;
  78. s.kind = PatcherExpr::Kind::series;
  79. s.gain = a.gain * b.gain;
  80. for (auto* e : { &a, &b })
  81. {
  82. if (e->kind == PatcherExpr::Kind::identity)
  83. continue;
  84. if (e->kind == PatcherExpr::Kind::series)
  85. for (auto& c : e->children)
  86. s.children.push_back (std::move (c));
  87. else
  88. {
  89. e->gain = 1.0f;
  90. s.children.push_back (std::move (*e));
  91. }
  92. }
  93. if (s.children.empty())
  94. return { PatcherExpr::Kind::identity, -1, -1, s.gain, {} };
  95. if (s.children.size() == 1)
  96. {
  97. auto only = std::move (s.children.front());
  98. only.gain = s.gain;
  99. return only;
  100. }
  101. return s;
  102. }
  103. std::optional<PatcherExpr> reduce (std::vector<SpEdge> edges, int source, int sink)
  104. {
  105. for (int guard = 0; guard < 100000; ++guard)
  106. {
  107. if (edges.size() == 1 && edges[0].from == source && edges[0].to == sink)
  108. return edges[0].expr;
  109. bool changed = false;
  110. // parallel
  111. for (std::size_t i = 0; i < edges.size() && ! changed; ++i)
  112. for (std::size_t j = i + 1; j < edges.size(); ++j)
  113. if (edges[i].from == edges[j].from && edges[i].to == edges[j].to)
  114. {
  115. PatcherExpr p;
  116. p.kind = PatcherExpr::Kind::parallel;
  117. for (auto* e : { &edges[i].expr, &edges[j].expr })
  118. if (e->kind == PatcherExpr::Kind::parallel && e->gain == 1.0f)
  119. for (auto& c : e->children)
  120. p.children.push_back (std::move (c));
  121. else
  122. p.children.push_back (std::move (*e));
  123. edges[i].expr = std::move (p);
  124. edges.erase (edges.begin() + (std::ptrdiff_t) j);
  125. changed = true;
  126. break;
  127. }
  128. if (changed)
  129. continue;
  130. // series
  131. std::map<int, int> inCount, outCount;
  132. for (const auto& e : edges)
  133. {
  134. ++outCount[e.from];
  135. ++inCount[e.to];
  136. }
  137. for (const auto& [v, n] : inCount)
  138. {
  139. if (v == source || v == sink || n != 1 || outCount[v] != 1)
  140. continue;
  141. const auto a = std::find_if (edges.begin(), edges.end(), [v = v] (const SpEdge& e) { return e.to == v; }) - edges.begin();
  142. const auto b = std::find_if (edges.begin(), edges.end(), [v = v] (const SpEdge& e) { return e.from == v; }) - edges.begin();
  143. SpEdge merged { edges[(std::size_t) a].from, edges[(std::size_t) b].to,
  144. flattenSeries (std::move (edges[(std::size_t) a].expr), std::move (edges[(std::size_t) b].expr)) };
  145. edges.erase (edges.begin() + std::max (a, b));
  146. edges.erase (edges.begin() + std::min (a, b));
  147. edges.push_back (std::move (merged));
  148. changed = true;
  149. break;
  150. }
  151. if (! changed)
  152. return std::nullopt;
  153. }
  154. return std::nullopt;
  155. }
  156. } // namespace
  157. std::optional<PatcherGraph> parsePatcher (const std::vector<std::uint8_t>& state)
  158. {
  159. if (state.size() < 16)
  160. return std::nullopt;
  161. const auto version = at<std::uint32_t> (state.data(), 0);
  162. if (version < 3 || version > 4)
  163. return std::nullopt;
  164. const auto wide = version >= 4;
  165. PatcherGraph graph;
  166. std::map<std::uint64_t, Port> ports;
  167. std::vector<Connection> connections;
  168. std::uint64_t inputPin = 0, outputPin = 0;
  169. bool hasInput = false, hasOutput = false;
  170. const auto ok = forEachChunk (state.data() + 4, state.size() - 4, [&] (std::uint32_t id, const std::uint8_t* d, std::size_t n) {
  171. if (id != 0)
  172. return;
  173. std::vector<std::pair<std::uint32_t, std::pair<const std::uint8_t*, std::size_t>>> sub;
  174. forEachChunk (d, n, [&] (std::uint32_t k, const std::uint8_t* x, std::size_t m) { sub.push_back ({ k, { x, m } }); });
  175. if (sub.empty())
  176. return;
  177. const auto first = sub.front().first;
  178. if (first == 5000 && sub.front().second.second >= 4) // node
  179. {
  180. PatcherNode node;
  181. node.generator = at<std::uint32_t> (sub.front().second.first, 0) == 3;
  182. const auto index = (int) graph.nodes.size();
  183. for (const auto& [k, x] : sub)
  184. if (k == 5008)
  185. node.plugin = text (x.first, x.second, wide);
  186. else if (k == 5005)
  187. node.state.assign (x.first, x.first + x.second);
  188. else if (k == 5009 && x.second >= 20)
  189. ports[at<std::uint64_t> (x.first, 8)] = { index, (at<std::uint32_t> (x.first, 16) & 1) != 0, (int) at<std::uint32_t> (x.first, 4),
  190. (int) at<std::uint32_t> (x.first, 0) };
  191. graph.nodes.push_back (std::move (node));
  192. }
  193. else if (first == 1400 && sub.front().second.second >= 21) // I/O pin
  194. {
  195. const auto* x = sub.front().second.first;
  196. const auto portId = at<std::uint64_t> (x, 0);
  197. const auto kind = (int) at<std::uint32_t> (x, 8);
  198. const auto fromOutside = (at<std::uint32_t> (x, 12) & 1) != 0;
  199. const auto bus = at<std::int32_t> (x, 17);
  200. ports[portId] = { -1, ! fromOutside, bus, kind };
  201. if (kind == 0 && bus == 0 && fromOutside)
  202. inputPin = portId, hasInput = true;
  203. if (kind == 0 && bus == 0 && ! fromOutside)
  204. outputPin = portId, hasOutput = true;
  205. }
  206. else if (first == 1300 && sub.front().second.second >= 25) // connection
  207. {
  208. const auto* x = sub.front().second.first;
  209. // flags (offset 20): bit 0 = cable disabled; bit 1 = the class byte (24) is valid (REA_rodada20 §3.1)
  210. const auto flags = at<std::uint32_t> (x, 20);
  211. connections.push_back ({ at<std::uint64_t> (x, 0), at<std::uint64_t> (x, 8), at<float> (x, 16), (flags & 2) != 0 ? (int) x[24] : -1,
  212. (flags & 1) != 0 });
  213. }
  214. });
  215. if (! ok)
  216. return std::nullopt;
  217. // cable class: byte 24's if valid; otherwise, the destination port's. Disabled cables are dropped.
  218. std::erase_if (connections, [] (const Connection& c) { return c.disabled; });
  219. for (auto& c : connections)
  220. if (c.kind < 0)
  221. {
  222. const auto dst = ports.find (c.destination);
  223. c.kind = dst != ports.end() ? dst->second.kind : 2;
  224. }
  225. // main generator: the one reaching the output with the most gain
  226. float best = -1.0f;
  227. for (const auto& c : connections)
  228. if (c.kind == 0 && hasOutput && c.destination == outputPin)
  229. if (const auto src = ports.find (c.source); src != ports.end() && src->second.node >= 0
  230. && graph.nodes[(std::size_t) src->second.node].generator && c.gain > best)
  231. {
  232. best = c.gain;
  233. graph.mainGenerator = src->second.node;
  234. }
  235. // serial chain: only audio edges on bus 0, each node with one input and one output
  236. if (hasInput && hasOutput)
  237. {
  238. std::map<int, std::vector<int>> next; // -1 = IN, -2 = OUT
  239. int audioEdges = 0;
  240. bool simple = true;
  241. for (const auto& c : connections)
  242. {
  243. if (c.kind != 0)
  244. continue;
  245. const auto src = ports.find (c.source), dst = ports.find (c.destination);
  246. if (src == ports.end() || dst == ports.end())
  247. continue;
  248. ++audioEdges;
  249. if (src->second.bus != 0 || dst->second.bus != 0 || std::abs (c.gain - 1.0f) > 1e-3f)
  250. simple = false;
  251. const auto from = src->second.node >= 0 ? src->second.node : (c.source == inputPin ? -1 : -3);
  252. const auto to = dst->second.node >= 0 ? dst->second.node : (c.destination == outputPin ? -2 : -3);
  253. if (from == -3 || to == -3)
  254. simple = false;
  255. next[from].push_back (to);
  256. }
  257. std::vector<int> chain;
  258. auto cursor = -1;
  259. while (simple && next[cursor].size() == 1)
  260. {
  261. cursor = next[cursor].front();
  262. if (cursor == -2)
  263. break;
  264. if (cursor < 0 || graph.nodes[(std::size_t) cursor].generator || chain.size() > graph.nodes.size())
  265. {
  266. simple = false;
  267. break;
  268. }
  269. chain.push_back (cursor);
  270. }
  271. if (simple && cursor == -2 && audioEdges == (int) chain.size() + 1)
  272. graph.serialChain = std::move (chain);
  273. }
  274. // parallel branches: common serial section from IN, then branches (from IN, from a node with several
  275. // outputs, or from the bands of a Frequency Splitter), each a simple chain to OUT. Sidechain
  276. // inputs (bus > 0 at the destination) are left out.
  277. if (hasInput && hasOutput)
  278. {
  279. struct Edge
  280. {
  281. int from, to, fromBus;
  282. float gain;
  283. };
  284. std::vector<Edge> edges;
  285. bool ok = true;
  286. for (const auto& c : connections)
  287. {
  288. if (c.kind != 0)
  289. continue;
  290. const auto src = ports.find (c.source), dst = ports.find (c.destination);
  291. if (src == ports.end() || dst == ports.end())
  292. continue;
  293. if (dst->second.bus != 0)
  294. continue; // sidechain
  295. const auto from = src->second.node >= 0 ? src->second.node : (c.source == inputPin ? -1 : -3);
  296. const auto to = dst->second.node >= 0 ? dst->second.node : (c.destination == outputPin ? -2 : -3);
  297. if (from == -3 || to == -3)
  298. {
  299. ok = false;
  300. continue;
  301. }
  302. edges.push_back ({ from, to, src->second.bus, std::isfinite (c.gain) ? c.gain : 1.0f });
  303. }
  304. auto isSplitter = [&] (int n) {
  305. auto name = graph.nodes[(std::size_t) n].plugin;
  306. for (auto& ch : name)
  307. ch = (char) std::tolower ((unsigned char) ch);
  308. return name == "frequency splitter" || name == "fruity stereo shaper"; // nodes that split by bus
  309. };
  310. auto outs = [&] (int n) {
  311. std::vector<std::size_t> r;
  312. for (std::size_t i = 0; i < edges.size(); ++i)
  313. if (edges[i].from == n)
  314. r.push_back (i);
  315. return r;
  316. };
  317. auto countTo = [&] (int n) { return (int) std::count_if (edges.begin(), edges.end(), [n] (const Edge& e) { return e.to == n; }); };
  318. // only bus 0 outside the splitter (other outputs, like the Stereo Shaper's, are not reproducible)
  319. for (const auto& e : edges)
  320. if (e.fromBus != 0 && (e.from < 0 || ! isSplitter (e.from)))
  321. ok = false;
  322. std::vector<bool> consumed (edges.size(), false);
  323. auto cursor = -1;
  324. float preGain = 1.0f;
  325. std::vector<int> pre;
  326. while (ok)
  327. {
  328. const auto o = outs (cursor);
  329. if (o.size() != 1 || edges[o[0]].to < 0 || countTo (edges[o[0]].to) != 1)
  330. break;
  331. consumed[o[0]] = true;
  332. preGain *= edges[o[0]].gain;
  333. cursor = edges[o[0]].to;
  334. if (graph.nodes[(std::size_t) cursor].generator)
  335. ok = false;
  336. pre.push_back (cursor);
  337. if (isSplitter (cursor))
  338. break;
  339. }
  340. std::vector<PatcherGraph::Branch> branches;
  341. const auto splitterHere = cursor >= 0 && isSplitter (cursor);
  342. for (const auto i : outs (cursor))
  343. {
  344. if (! ok)
  345. break;
  346. consumed[i] = true;
  347. PatcherGraph::Branch branch;
  348. branch.gain = preGain * edges[i].gain;
  349. branch.band = splitterHere ? edges[i].fromBus : 0;
  350. auto at = edges[i].to;
  351. while (ok && at >= 0)
  352. {
  353. const auto o = outs (at);
  354. if (graph.nodes[(std::size_t) at].generator || isSplitter (at) || countTo (at) != 1 || o.size() != 1
  355. || branch.nodes.size() > graph.nodes.size())
  356. {
  357. ok = false;
  358. break;
  359. }
  360. branch.nodes.push_back (at);
  361. consumed[o[0]] = true;
  362. branch.gain *= edges[o[0]].gain;
  363. at = edges[o[0]].to;
  364. }
  365. if (at != -2)
  366. ok = false;
  367. branches.push_back (std::move (branch));
  368. }
  369. if (ok && std::all_of (consumed.begin(), consumed.end(), [] (bool c) { return c; })
  370. && (branches.size() >= 2 || (splitterHere && ! branches.empty())))
  371. {
  372. if (splitterHere)
  373. {
  374. graph.splitter = cursor;
  375. pre.pop_back();
  376. }
  377. graph.preChain = std::move (pre);
  378. graph.branches = std::move (branches);
  379. }
  380. }
  381. // audio graph reduced to series/parallel (REA_rodada20 §3.3)
  382. if (hasInput && hasOutput)
  383. {
  384. struct Edge
  385. {
  386. int from, to, fromBus;
  387. float gain;
  388. };
  389. std::vector<Edge> edges;
  390. bool valid = true;
  391. for (const auto& c : connections)
  392. {
  393. if (c.kind != 0)
  394. continue;
  395. const auto src = ports.find (c.source), dst = ports.find (c.destination);
  396. if (src == ports.end() || dst == ports.end() || dst->second.bus != 0)
  397. continue; // sidechain is left out
  398. const auto from = src->second.node >= 0 ? src->second.node : (c.source == inputPin ? -1 : -3);
  399. const auto to = dst->second.node >= 0 ? dst->second.node : (c.destination == outputPin ? -2 : -3);
  400. if (from == -3 || to == -3)
  401. continue;
  402. edges.push_back ({ from, to, src->second.bus, std::isfinite (c.gain) ? c.gain : 1.0f });
  403. }
  404. // prune: only nodes reachable from IN that also reach OUT
  405. auto reach = [&] (int start, bool forward) {
  406. std::set<int> seen { start };
  407. std::vector<int> stack { start };
  408. while (! stack.empty())
  409. {
  410. const auto v = stack.back();
  411. stack.pop_back();
  412. for (const auto& e : edges)
  413. if ((forward ? e.from : e.to) == v && seen.insert (forward ? e.to : e.from).second)
  414. stack.push_back (forward ? e.to : e.from);
  415. }
  416. return seen;
  417. };
  418. const auto fromIn = reach (-1, true), toOut = reach (-2, false);
  419. std::erase_if (edges, [&] (const Edge& e) { return ! fromIn.count (e.from) || ! toOut.count (e.from) || ! fromIn.count (e.to) || ! toOut.count (e.to); });
  420. // splitters with outputs on bus ≠ 0 become one vertex per used bus
  421. std::map<int, std::set<int>> splitBuses;
  422. for (const auto& e : edges)
  423. if (e.from >= 0 && e.fromBus != 0)
  424. {
  425. if (! isSplitterName (graph.nodes[(std::size_t) e.from].plugin))
  426. valid = false; // side output of an ordinary node: not reproducible
  427. splitBuses[e.from].insert (e.fromBus);
  428. }
  429. for (const auto& e : edges)
  430. if (e.from >= 0 && splitBuses.count (e.from))
  431. splitBuses[e.from].insert (e.fromBus);
  432. // vertices: IN = 0, OUT = 1; node n (or n per bus): input/output
  433. std::map<std::pair<int, int>, int> vin, vout;
  434. int next = 2;
  435. std::vector<SpEdge> sp;
  436. auto vertexPair = [&] (int n, int bus) {
  437. const auto key = std::make_pair (n, bus);
  438. if (! vin.count (key))
  439. {
  440. vin[key] = next++;
  441. vout[key] = next++;
  442. PatcherExpr e;
  443. e.kind = PatcherExpr::Kind::node;
  444. e.node = n;
  445. e.bus = bus;
  446. sp.push_back ({ vin[key], vout[key], std::move (e) });
  447. }
  448. };
  449. auto busesOf = [&] (int n) { return splitBuses.count (n) ? std::vector<int> (splitBuses[n].begin(), splitBuses[n].end()) : std::vector<int> { -1 }; };
  450. for (const auto& e : edges)
  451. {
  452. if ((e.from >= 0 && graph.nodes[(std::size_t) e.from].generator) || (e.to >= 0 && graph.nodes[(std::size_t) e.to].generator))
  453. valid = false;
  454. const auto fromBus = e.from >= 0 && splitBuses.count (e.from) ? e.fromBus : -1;
  455. int from = 0;
  456. if (e.from >= 0)
  457. {
  458. vertexPair (e.from, fromBus);
  459. from = vout[{ e.from, fromBus }];
  460. }
  461. // the cable entering a splitter feeds all of its buses
  462. for (const auto bus : e.to >= 0 ? busesOf (e.to) : std::vector<int> { -1 })
  463. {
  464. int to = 1;
  465. if (e.to >= 0)
  466. {
  467. vertexPair (e.to, bus);
  468. to = vin[{ e.to, bus }];
  469. }
  470. sp.push_back ({ from, to, { PatcherExpr::Kind::identity, -1, -1, e.gain, {} } });
  471. }
  472. }
  473. if (valid && ! sp.empty())
  474. graph.audio = reduce (std::move (sp), 0, 1);
  475. }
  476. return graph;
  477. }
  478. } // namespace lynx