CtlAudit.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. #pragma once
  2. // "Every control changes the render" (round 170i3): for one FL-native generator channel, each control the LYNX editor
  3. // shows is flipped to the far end of its range and a short note pattern is rendered through the same three paths the
  4. // app uses:
  5. // state — a new instrument built from the edited channel (a project saved and opened again)
  6. // live — the edited channel reaches the running instrument through RackState::build (previous) → configure, as an
  7. // editor knob's ChannelRef::edit does while notes play
  8. // auto — Instrument::setParameter (index, 0…1) on the running instrument, as an automation clip / MIDI link does
  9. // A control "moves" a path when that path's render differs from the unedited one by more than −100 dB (relative RMS).
  10. // Used by tools/ctlaudit (the survey) and by tests/CtlAudit170i3Tests.inc (the permanent checks).
  11. #include <algorithm>
  12. #include <cmath>
  13. #include <cstdint>
  14. #include <cctype>
  15. #include <cstring>
  16. #include <optional>
  17. #include <functional>
  18. #include <memory>
  19. #include <string>
  20. #include <vector>
  21. #include "core/EngineParams.h"
  22. #include "core/FlKeys.h"
  23. #include "core/Harmor.h"
  24. #include "core/SytrusEngine.h"
  25. #include "core/ThreeOsc.h"
  26. #include "core/ModelParams.h"
  27. #include "core/NativeEngines.h"
  28. #include "core/RackRenderer.h"
  29. #include "core/Song.h"
  30. namespace lynx::ctlaudit
  31. {
  32. // one editor control of a channel: how to read it and write it as the editor does (raw value, the control's range)
  33. // FL's installation for the controls that load files (natives::followControl), set by the caller; nullptr = none
  34. inline const natives::FlAccess* flAccess = nullptr;
  35. struct Control
  36. {
  37. int index = 0; // the engine's parameter number (automation target param), −1 = not automatable
  38. std::string name;
  39. float low = 0.0f, high = 1.0f;
  40. std::function<std::optional<float> (const ChannelDef&)> get;
  41. std::function<bool (ChannelDef&, float)> set;
  42. bool automatable = true; // (the engines without a parameter list take no channelParam automation)
  43. };
  44. // the listed parameters (core/ModelParams.h) of the channel's engine, as the designed editor builds its knobs
  45. inline std::vector<Control> modelControls (const ChannelDef& c)
  46. {
  47. std::vector<Control> out;
  48. const auto* table = modelparams::tableOf (c.instrument);
  49. if (table == nullptr || table->params == nullptr)
  50. return out;
  51. for (const auto& p : *table->params)
  52. {
  53. Control k;
  54. k.index = p.index, k.name = p.name, k.low = p.low, k.high = p.high;
  55. const auto index = p.index;
  56. k.get = [index] (const ChannelDef& d) { return modelparams::rawValue (d, index); };
  57. k.set = [index] (ChannelDef& d, float raw) {
  58. const auto ok = modelparams::setRawValue (d, index, raw);
  59. if (ok && flAccess != nullptr)
  60. natives::followControl (d, index, *flAccess); // (as the editor's knob does)
  61. return ok;
  62. };
  63. out.push_back (std::move (k));
  64. }
  65. return out;
  66. }
  67. // the knobs of the engines with their own (unlisted) controls, exactly as src/ui/ChannelSettings.cpp's ModelPanel
  68. // builds them: 3x Osc, FL Keys, Sytrus's main settings, Harmor's part A knobs, BooBass's three knobs
  69. inline std::vector<Control> ownControls (const ChannelDef& c)
  70. {
  71. std::vector<Control> out;
  72. auto add = [&out] (int index, std::string name, float low, float high, auto get, auto set) {
  73. Control k;
  74. k.index = index, k.name = std::move (name), k.low = low, k.high = high, k.get = get, k.set = set, k.automatable = false;
  75. out.push_back (std::move (k));
  76. };
  77. switch (c.instrument)
  78. {
  79. case InstrumentKind::threeosc:
  80. {
  81. static const char* const names[] = {
  82. "Osc 1 pan", "Osc 1 shape", "Osc 1 coarse", "Osc 1 fine", "Osc 1 phase", "Osc 1 detune", "Osc 2 mix", "Osc 2 pan",
  83. "Osc 2 shape", "Osc 2 coarse", "Osc 2 fine", "Osc 2 phase", "Osc 2 detune", "Osc 3 mix", "Osc 3 pan", "Osc 3 shape",
  84. "Osc 3 coarse", "Osc 3 fine", "Osc 3 phase", "Osc 3 detune", "Phase rand", "Invert 1", "Invert 2", "Invert 3",
  85. "Osc 3 AM", "HQ" };
  86. for (int i = 0; i < threeOscParamCount(); ++i)
  87. {
  88. const auto [low, high] = threeOscParamRange (i);
  89. add (i, i < 26 ? names[i] : "Param " + std::to_string (i), (float) low, (float) high,
  90. [i] (const ChannelDef& d) -> std::optional<float> {
  91. const auto v = threeOscParam (d.pluginState, i);
  92. return v ? std::optional<float> ((float) *v) : std::nullopt;
  93. },
  94. [i] (ChannelDef& d, float v) { return threeOscSetParam (d.pluginState, i, (int) std::lround (v)); });
  95. }
  96. break;
  97. }
  98. case InstrumentKind::flkeys:
  99. for (int i = 0; i < 15; ++i)
  100. add (i, flkeys::knobRange[i].name, (float) flkeys::knobRange[i].min, (float) flkeys::knobRange[i].max,
  101. [i] (const ChannelDef& d) -> std::optional<float> {
  102. const auto st = flkeys::parseState (d.pluginState);
  103. return st ? std::optional<float> ((float) st->knobs[(std::size_t) i]) : std::nullopt;
  104. },
  105. [i] (ChannelDef& d, float v) {
  106. auto st = flkeys::parseState (d.pluginState);
  107. if (! st)
  108. return false;
  109. st->knobs[(std::size_t) i] = (int) std::lround (v);
  110. d.pluginState = flkeys::writeState (*st);
  111. return true;
  112. });
  113. break;
  114. case InstrumentKind::sytrus:
  115. for (int i = 0; i < (int) sytrus::settings().size(); ++i)
  116. {
  117. const auto& st = sytrus::settings()[(std::size_t) i];
  118. add (i, st.name, (float) st.low, (float) st.high,
  119. [i] (const ChannelDef& d) -> std::optional<float> {
  120. const auto v = sytrus::settingValue (d.pluginState, i);
  121. return v ? std::optional<float> ((float) *v) : std::nullopt;
  122. },
  123. [i] (ChannelDef& d, float v) { return sytrus::setSetting (d.pluginState, i, (int) std::lround (v)); });
  124. }
  125. break;
  126. case InstrumentKind::harmor:
  127. {
  128. struct K { int part, index; const char* name; float low, high; };
  129. static const K knobs[] = {
  130. { -1, 12, "Master vol", 0, 2000 }, { -1, 10, "A/B mix", 0, 1000 }, { 0, 11, "A volume", -1000, 1000 },
  131. { 0, 4, "Timbre mix", 0, 1000 }, { 0, 52, "Cutoff", 0, 8192 }, { 0, 57, "Resonance", 0, 1000 },
  132. { 0, 75, "Pluck", 0, 1000 }, { 0, 34, "Unison", 1, 9 }, { 0, 38, "Uni detune", 0, 256 },
  133. { 0, 27, "Harmonizer", 0, 1000 }, { 0, 76, "Phaser mix", 0, 1000 }, { 0, 23, "Harm. blur", 0, 10000 },
  134. { 0, 45, "Vibrato", 0, 1000 }, { 0, 17, "Tremolo", 0, 1000 } };
  135. for (const auto& k : knobs)
  136. add (k.index, k.name, k.low, k.high,
  137. [k] (const ChannelDef& d) -> std::optional<float> {
  138. const auto at = harmorParamOffset (d.pluginState, k.part, k.index);
  139. if (at < 0)
  140. return std::nullopt;
  141. std::int32_t v = 0;
  142. std::memcpy (&v, d.pluginState.data() + at, 4);
  143. return (float) v;
  144. },
  145. [k] (ChannelDef& d, float v) {
  146. const auto at = harmorParamOffset (d.pluginState, k.part, k.index);
  147. if (at < 0)
  148. return false;
  149. const auto x = (std::int32_t) std::lround (v);
  150. std::memcpy (d.pluginState.data() + at, &x, 4);
  151. return true;
  152. });
  153. break;
  154. }
  155. case InstrumentKind::boobass:
  156. for (const auto& [i, name] : { std::pair<int, const char*> { 0, "Bass" }, { 1, "Mid" }, { 2, "Treble" } })
  157. add (i, name, 0.0f, 65535.0f,
  158. [i] (const ChannelDef& d) -> std::optional<float> {
  159. return (std::size_t) i < d.modelParams.size() ? std::optional<float> (d.modelParams[(std::size_t) i]) : std::nullopt;
  160. },
  161. [i] (ChannelDef& d, float v) {
  162. if ((std::size_t) i >= d.modelParams.size())
  163. return false;
  164. d.modelParams[(std::size_t) i] = v;
  165. return true;
  166. });
  167. break;
  168. default:
  169. break;
  170. }
  171. return out;
  172. }
  173. // what the editor shows for this channel: the parameter list when the engine has one (and can read the state), its
  174. // own knobs otherwise
  175. inline std::vector<Control> editorControls (const ChannelDef& c)
  176. {
  177. const auto* table = modelparams::tableOf (c.instrument);
  178. if (table != nullptr && table->params != nullptr && ! table->params->empty() && modelparams::rawValue (c, table->params->front().index))
  179. return modelControls (c);
  180. return ownControls (c);
  181. }
  182. struct Pattern
  183. {
  184. std::vector<int> keys { 48, 60, 64, 67 };
  185. std::vector<int> keys2 { 50, 62, 65, 69 }; // a second chord after the edit (most engines read a control at note on)
  186. int secondBlock = 16;
  187. float velocity = 0.8f;
  188. double rate = 44100.0;
  189. int heldBlocks = 40; // 512-sample blocks with the keys down (0.46 s)
  190. int releaseBlocks = 30; // then released (0.35 s)
  191. int editBlock = 8; // the live / automation edit lands here (0.09 s in)
  192. double bpm = 120.0;
  193. // round 173d2: the performance a control may need (defaults: none of it)
  194. float bend = 0.0f; // the pitch wheel (semitones) from bendBlock on
  195. float channelPitch = 0.0f; // the channel's PITCH knob (cents) from bendBlock on (FL's pitch bend of a generator)
  196. int bendBlock = 12;
  197. float modWheel = -1.0f; // CC 1 (0…1) before the first note, ≥ 0 = sent
  198. float releaseVelocity = -1.0f; // the note-off velocity (0…1), ≥ 0 = sent
  199. bool offline = false; // rendered as an export (setOfflineRendering: the render-quality settings)
  200. int firstOffBlock = -1; // ≥ 0: the first keys are released here, before the second ones (a gap between notes)
  201. };
  202. // the pattern for an engine: drum engines play their pads
  203. inline Pattern patternFor (InstrumentKind kind)
  204. {
  205. Pattern p;
  206. if (kind == InstrumentKind::drumaxx)
  207. p.keys = p.keys2 = { 36, 37, 38, 42, 43, 44, 45, 49 }; // (FL's Default Kit's pads, hit again after the edit)
  208. else if (kind == InstrumentKind::drumpad || kind == InstrumentKind::bassdrum || kind == InstrumentKind::fruitkick)
  209. p.keys = { 60 }, p.keys2 = { 60 };
  210. return p;
  211. }
  212. using Samples = std::function<std::shared_ptr<const SampleData> (const std::string&)>;
  213. struct Player
  214. {
  215. Song song;
  216. std::unique_ptr<const RackState> state;
  217. Samples samples;
  218. double rate;
  219. Player (const ChannelDef& c, const Pattern& p, const Samples& s) : samples (s), rate (p.rate)
  220. {
  221. song.mixer = Song::defaultMixer (2);
  222. song.bpm = p.bpm;
  223. auto ch = c;
  224. ch.mixerTrack = 1;
  225. song.channels.push_back (ch);
  226. song.patterns.emplace_back();
  227. setOfflineRendering (p.offline); // (read when the engines are prepared)
  228. state = RackState::build (song, nullptr, rate, samples);
  229. }
  230. Instrument* inst() const { return state != nullptr && ! state->instruments.empty() ? state->instruments[0].get() : nullptr; }
  231. void rebuild (const ChannelDef& c)
  232. {
  233. auto next = song;
  234. auto ch = c;
  235. ch.mixerTrack = 1;
  236. next.channels[0] = ch;
  237. auto s = RackState::build (next, state.get(), rate, samples);
  238. song = std::move (next);
  239. state = std::move (s);
  240. }
  241. void block (std::vector<float>& out)
  242. {
  243. std::vector<float> l (512, 0.0f), r (512, 0.0f);
  244. if (auto* i = inst())
  245. i->render (l.data(), r.data(), 512, 1.0f, 1.0f);
  246. for (int k = 0; k < 512; ++k)
  247. out.push_back (l[(std::size_t) k]), out.push_back (r[(std::size_t) k]);
  248. }
  249. };
  250. enum class Path { state, live, automation };
  251. // the pattern's render; `edit` (when set) runs at the edit block on the playing player
  252. inline std::vector<float> render (const ChannelDef& c, const Pattern& p, const Samples& s, const std::function<void (Player&)>& edit = {})
  253. {
  254. Player pl (c, p, s);
  255. std::vector<float> out;
  256. auto* i = pl.inst();
  257. if (i == nullptr)
  258. return out;
  259. if (p.modWheel >= 0.0f)
  260. i->controlChange (1, p.modWheel);
  261. for (const auto k : p.keys)
  262. i->noteOn (k, p.velocity);
  263. for (int b = 0; b < p.heldBlocks + p.releaseBlocks; ++b)
  264. {
  265. if (b == p.editBlock && edit)
  266. edit (pl);
  267. if (b == p.bendBlock && (p.bend != 0.0f || p.channelPitch != 0.0f))
  268. if (auto* now = pl.inst())
  269. {
  270. if (p.bend != 0.0f)
  271. now->pitchBend (p.bend);
  272. if (p.channelPitch != 0.0f)
  273. now->setChannelPitchNow (p.channelPitch, 0.0f);
  274. }
  275. if (b == p.firstOffBlock)
  276. if (auto* now = pl.inst())
  277. for (const auto k : p.keys)
  278. now->noteOff (k);
  279. if (b == p.secondBlock)
  280. if (auto* now = pl.inst())
  281. for (const auto k : p.keys2)
  282. now->noteOn (k, p.velocity);
  283. if (b == p.heldBlocks)
  284. if (auto* now = pl.inst())
  285. {
  286. for (const auto k : p.keys)
  287. {
  288. if (p.firstOffBlock >= 0 && p.firstOffBlock < p.heldBlocks)
  289. break; // (released already)
  290. if (p.releaseVelocity >= 0.0f)
  291. now->setNextNoteRelease (p.releaseVelocity);
  292. now->noteOff (k);
  293. }
  294. for (const auto k : p.keys2)
  295. if (std::find (p.keys.begin(), p.keys.end(), k) == p.keys.end())
  296. {
  297. if (p.releaseVelocity >= 0.0f)
  298. now->setNextNoteRelease (p.releaseVelocity);
  299. now->noteOff (k);
  300. }
  301. }
  302. pl.block (out);
  303. }
  304. return out;
  305. }
  306. // relative RMS difference in dB (−300 = identical, 0 = as loud as the reference)
  307. inline double diffDb (const std::vector<float>& a, const std::vector<float>& b)
  308. {
  309. double e = 0.0, n = 0.0;
  310. const auto len = std::min (a.size(), b.size());
  311. for (std::size_t i = 0; i < len; ++i)
  312. {
  313. const double d = (double) a[i] - (double) b[i];
  314. e += d * d;
  315. n += (double) b[i] * (double) b[i];
  316. }
  317. if (a.size() != b.size())
  318. return 0.0;
  319. if (e == 0.0)
  320. return -300.0;
  321. return 10.0 * std::log10 (e / std::max (n, 1e-30));
  322. }
  323. inline double peak (const std::vector<float>& a)
  324. {
  325. double p = 0.0;
  326. for (const auto v : a)
  327. p = std::max (p, (double) std::abs (v));
  328. return p;
  329. }
  330. // the far end of the control's range from its current value
  331. inline float flipped (const Control& k, float v)
  332. {
  333. return v - k.low > 0.5f * (k.high - k.low) ? k.low : k.high;
  334. }
  335. struct Result
  336. {
  337. std::string name;
  338. int index = 0;
  339. float from = 0.0f, to = 0.0f;
  340. double state = -300.0, live = -300.0, automation = -300.0; // dB vs the unedited render (−300: no change)
  341. bool rebuilt = false; // the live edit replaced the instrument (its sounding notes end) instead of configuring it
  342. bool automatable = true;
  343. };
  344. struct Report
  345. {
  346. double basePeak = 0.0;
  347. double noise = -300.0; // the unedited pattern rendered twice (random-phase engines are not deterministic)
  348. std::vector<Result> results;
  349. };
  350. constexpr double movedDb = -100.0;
  351. // every control of `controls` on channel `c` (prepare `c` first: sections on, a send, …)
  352. inline Report audit (const ChannelDef& c, const std::vector<Control>& controls, const Pattern& p, const Samples& s, bool live = true,
  353. bool automation = true)
  354. {
  355. Report rep;
  356. const auto base = render (c, p, s);
  357. rep.basePeak = peak (base);
  358. rep.noise = diffDb (render (c, p, s), base);
  359. const auto liveBase = render (c, p, s, [&c] (Player& pl) { pl.rebuild (c); });
  360. for (const auto& k : controls)
  361. {
  362. Result r;
  363. r.name = k.name, r.index = k.index;
  364. const auto v = k.get (c);
  365. if (! v)
  366. continue;
  367. r.from = *v;
  368. r.to = flipped (k, *v);
  369. auto changed = c;
  370. if (! k.set (changed, r.to))
  371. continue;
  372. r.state = diffDb (render (changed, p, s), base);
  373. if (live)
  374. r.live = diffDb (render (c, p, s, [&changed, &r] (Player& pl) {
  375. const auto* before = pl.inst();
  376. pl.rebuild (changed);
  377. r.rebuilt = pl.inst() != before;
  378. }),
  379. liveBase);
  380. r.automatable = automation && k.automatable && k.index >= 0;
  381. if (r.automatable)
  382. {
  383. const auto* param = modelparams::find (c.instrument, k.index);
  384. const auto x = param != nullptr ? param->normalised (r.to) : (k.high > k.low ? (r.to - k.low) / (k.high - k.low) : 0.0f);
  385. r.automation = diffDb (render (c, p, s, [&] (Player& pl) {
  386. if (auto* i = pl.inst())
  387. i->setParameter (k.index, x);
  388. }),
  389. base);
  390. }
  391. rep.results.push_back (r);
  392. }
  393. return rep;
  394. }
  395. inline bool moved (double db, double noise) { return db > std::max (movedDb, noise + 20.0); }
  396. // A control can be silent only because another one switches its section off (an LFO amount of 0, an effect bypassed,
  397. // unison 1…). For the controls whose flip moved nothing, `contexts` random settings of all the other controls are tried
  398. // (a fixed seed): a control that moves in none of them is reported (its index in `controls`). Uniform values inside
  399. // each control's range; the master levels keep their values so the context is not silent.
  400. inline std::vector<int> stillDead (const ChannelDef& c, const std::vector<Control>& controls, const std::vector<int>& dead, const Pattern& p,
  401. const Samples& s, int contexts = 6, std::uint32_t seed = 170)
  402. {
  403. std::vector<int> left = dead;
  404. auto rnd = [&seed] {
  405. seed = seed * 1664525u + 1013904223u;
  406. return (float) ((seed >> 8) & 0xffffff) / 16777216.0f;
  407. };
  408. for (int k = 0; k < contexts && ! left.empty(); ++k)
  409. {
  410. auto ctx = c;
  411. for (const auto& ctl : controls)
  412. {
  413. std::string lower = ctl.name;
  414. std::transform (lower.begin(), lower.end(), lower.begin(), [] (unsigned char ch) { return (char) std::tolower (ch); });
  415. if (lower.find ("master") != std::string::npos || lower == "volume" || lower == "output" || lower.find ("mute") != std::string::npos)
  416. continue;
  417. ctl.set (ctx, ctl.low + rnd() * (ctl.high - ctl.low));
  418. }
  419. const auto base = render (ctx, p, s);
  420. if (peak (base) < 1e-4)
  421. continue;
  422. std::vector<int> next;
  423. for (const auto i : left)
  424. {
  425. const auto& ctl = controls[(std::size_t) i];
  426. const auto v = ctl.get (ctx);
  427. auto changed = ctx;
  428. if (! v || ! ctl.set (changed, flipped (ctl, *v)) || ! moved (diffDb (render (changed, p, s), base), -300.0))
  429. next.push_back (i);
  430. }
  431. left = std::move (next);
  432. }
  433. return left;
  434. }
  435. } // namespace lynx::ctlaudit