VfxScript165Tests.inc 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. // Round 165d: VFX Script runs Python (core/Python.h, core/VfxScript.h)
  2. #include "core/Python.h"
  3. #include "core/VfxScript.h"
  4. #include <ctime>
  5. namespace vfxs165
  6. {
  7. using lynx::vfx::Event;
  8. std::vector<std::uint8_t> state (const std::string& source, const std::vector<std::pair<std::string, std::string>>& params = {})
  9. {
  10. auto s = lynx::vfx::defaultScript();
  11. s.setSource (source);
  12. if (! params.empty())
  13. s.setParameters (params);
  14. return lynx::vfx::writeScript (s);
  15. }
  16. struct Timed
  17. {
  18. long at = 0; // absolute sample
  19. Event e;
  20. };
  21. // Plays `total` samples in blocks of n (the song playing from tick 0 at `bpm`, 44.1 kHz); `in` at absolute samples
  22. std::vector<Timed> play (lynx::vfx::Processor& p, std::vector<Timed> in, long total, int n = 512, bool playing = true, double bpm = 120.0)
  23. {
  24. std::vector<Timed> out;
  25. lynx::vfx::Transport t;
  26. t.sampleRate = 44100.0;
  27. t.bpm = bpm;
  28. t.playing = playing;
  29. std::size_t next = 0;
  30. for (long start = 0; start < total; start += n)
  31. {
  32. std::vector<Event> block;
  33. while (next < in.size() && in[next].at < start + n)
  34. {
  35. auto e = in[next++].e;
  36. e.offset = (int) (in[next - 1].at - start);
  37. block.push_back (e);
  38. }
  39. t.ticks = (double) start * bpm * 960.0 / (60.0 * t.sampleRate);
  40. lynx::vfx::EventList list;
  41. p.process (block.data(), (int) block.size(), n, t, list);
  42. list.sortByOffset();
  43. for (int k = 0; k < list.size(); ++k)
  44. out.push_back ({ start + list[k].offset, list[k] });
  45. }
  46. return out;
  47. }
  48. Timed on (long at, int key, float velocity = 0.8f, int colour = 0)
  49. {
  50. return { at, vfx164::on (key, 0, colour, velocity) };
  51. }
  52. Timed off (long at, int key, int colour = 0)
  53. {
  54. return { at, vfx164::off (key, 0, colour) };
  55. }
  56. std::vector<int> keysOn (const std::vector<Timed>& out)
  57. {
  58. std::vector<int> keys;
  59. for (const auto& o : out)
  60. if (o.e.type == Event::Type::on)
  61. keys.push_back (o.e.voice.key);
  62. return keys;
  63. }
  64. const char* passThrough = R"(
  65. import flvfx as vfx
  66. class Child(vfx.Voice):
  67. parent = None
  68. def onTriggerVoice(v):
  69. for shift in (0, 4, 7):
  70. c = Child(v)
  71. c.parent = v
  72. c.note += shift
  73. c.trigger()
  74. def onReleaseVoice(v):
  75. for c in list(vfx.context.voices):
  76. if c.parent is v:
  77. c.release()
  78. )";
  79. } // namespace vfxs165
  80. TEST (vfx_script_runs_python_on_the_notes)
  81. {
  82. using namespace lynx::vfx;
  83. auto p = makeProcessor (Kind::script, vfxs165::state (vfxs165::passThrough));
  84. const auto out = vfxs165::play (*p, { vfxs165::on (100, 60, 0.5f), vfxs165::off (3000, 60) }, 4096);
  85. // three notes on at the note's sample, three offs at the release's
  86. CHECK (out.size() == 6);
  87. if (out.size() != 6)
  88. return;
  89. CHECK ((vfxs165::keysOn (out) == std::vector<int> { 60, 64, 67 }));
  90. for (int k = 0; k < 3; ++k)
  91. {
  92. CHECK (out[(std::size_t) k].at == 100 && std::abs (out[(std::size_t) k].e.voice.velocity - 0.5f) < 1e-6f);
  93. CHECK (out[(std::size_t) k + 3].at == 3000 && out[(std::size_t) k + 3].e.type == Event::Type::off);
  94. }
  95. CHECK (out[3].e.id == out[0].e.id);
  96. }
  97. TEST (vfx_script_ticks_play_notes_at_their_sample)
  98. {
  99. using namespace lynx::vfx;
  100. // an eighth-note pulse (48 of 96 ticks), each half as long, from the song's start
  101. const char* src = R"(
  102. import flvfx as vfx
  103. def onTick():
  104. if vfx.context.isPlaying and vfx.context.ticks % 48 == 0:
  105. v = vfx.Voice()
  106. v.note = 72
  107. v.length = 24
  108. v.trigger()
  109. )";
  110. auto p = makeProcessor (Kind::script, vfxs165::state (src));
  111. auto out = vfxs165::play (*p, {}, 44100);
  112. out.erase (std::remove_if (out.begin(), out.end(), [] (const vfxs165::Timed& o) { return o.at >= 44100; }), out.end());
  113. // 120 bpm: a tick is 44100 · 60 / (120 · 96) = 229.6875 samples; an eighth 11025
  114. std::vector<long> ons, offs;
  115. for (const auto& o : out)
  116. (o.e.type == Event::Type::on ? ons : offs).push_back (o.at);
  117. if (ons != std::vector<long> { 0, 11025, 22050, 33075 })
  118. {
  119. for (const auto& o : out)
  120. std::printf (" %s at %ld key %d\n", o.e.type == Event::Type::on ? "on" : "off", o.at, o.e.voice.key);
  121. }
  122. CHECK ((ons == std::vector<long> { 0, 11025, 22050, 33075 }));
  123. // (24 ticks = 5512.5 samples: the half sample rounds either way)
  124. const long expectedOffs[] = { 5513, 16538, 27563, 38588 };
  125. CHECK (offs.size() == 4);
  126. for (std::size_t k = 0; k < offs.size() && k < 4; ++k)
  127. CHECK (std::abs (offs[k] - expectedOffs[k]) <= 1);
  128. CHECK (p->busy());
  129. }
  130. TEST (vfx_script_controls_values_and_output_controllers)
  131. {
  132. using namespace lynx::vfx;
  133. const char* src = R"(
  134. import flvfx as vfx
  135. vfx.addOutputController('Level', 0.25)
  136. def onTick():
  137. f = vfx.context.form
  138. vfx.setOutputController('Level', f.getInputValue('Main: Amount'))
  139. vfx.setOutputController('Steps', f.getInputValue('Steps') / 10.0)
  140. vfx.setOutputController('Mode', 1.0 if f.GetInputValue('Mode') == 2 and f.getInputValue('Name') == 'abc' else 0.0)
  141. def createDialog():
  142. form = vfx.ScriptDialog('Title', 'What it does')
  143. form.addGroup('Main')
  144. form.addInputKnob('Amount', 0.5, -1, 1, hint='the amount')
  145. form.endGroup()
  146. form.addInputKnobInt('Steps', 3, 1, 8)
  147. form.AddInputCombo('Mode', 'One,Two,Three', 0)
  148. form.addInputCheckbox('On', 1)
  149. form.addInputText('Name', 'x')
  150. vfx.addOutputController('Steps', 0)
  151. vfx.addOutputController('Mode', 0)
  152. return form
  153. )";
  154. auto settings = defaultScript();
  155. settings.setSource (src);
  156. const auto info = script::describe (settings);
  157. CHECK (info->compiled);
  158. if (! info->compiled)
  159. {
  160. std::printf (" %s\n", info->error.c_str());
  161. return;
  162. }
  163. CHECK (info->title == "Title" && info->description == "What it does");
  164. CHECK (info->controls.size() == 5);
  165. CHECK (info->controls[0].name == "Main: Amount" && info->controls[0].type == script::Control::Type::knob && info->controls[0].hint == "the amount");
  166. CHECK (info->controls[2].options == (std::vector<std::string> { "One", "Two", "Three" }));
  167. CHECK ((info->outputs == std::vector<std::string> { "Level", "Steps", "Mode" }));
  168. // FL's encodings: a knob as 2^18-normalized, an int / combo as the number, a text as it is
  169. settings.setParameters ({ { "Main: Amount", "196608" }, { "Steps", "7" }, { "Mode", "2" }, { "On", "0" }, { "Name", "abc" } });
  170. auto v = script::valuesOf (*info, settings);
  171. CHECK (std::abs (v.numbers[0] - 0.5) < 1e-9 && v.numbers[1] == 7.0 && v.numbers[2] == 2.0 && v.numbers[3] == 0.0 && v.texts[4] == "abc");
  172. auto again = settings;
  173. script::writeValues (again, *info, v);
  174. CHECK (again.parameters() == settings.parameters());
  175. CHECK (script::encodeValue (info->controls[0], 0.0, {}) == "131072"); // (0 in −1..1: the middle)
  176. auto p = makeProcessor (Kind::script, writeScript (settings));
  177. CHECK (std::abs (p->controlOutput (0) - 0.25f) < 1e-6f); // (the default, set at the top level)
  178. vfxs165::play (*p, {}, 2048);
  179. CHECK (std::abs (p->controlOutput (0) - 0.5f) < 1e-6f);
  180. CHECK (std::abs (p->controlOutput (1) - 0.7f) < 1e-6f);
  181. CHECK (p->controlOutput (2) == 1.0f);
  182. // an automation input (Patcher cable) moves a control: 0..1 over its range
  183. p->setParameter (0, 0.0f);
  184. p->setParameter (1, 1.0f);
  185. vfxs165::play (*p, {}, 1024);
  186. CHECK (p->controlOutput (0) == 0.0f); // (−1, clamped to the output's 0..1)
  187. CHECK (std::abs (p->controlOutput (1) - 0.8f) < 1e-6f);
  188. }
  189. TEST (vfx_script_errors_are_reported_and_never_hang)
  190. {
  191. using namespace lynx::vfx;
  192. // a syntax error: the line and the message, as FL's editor shows them
  193. const auto bad = script::describe (std::string ("import flvfx as vfx\ndef onTick(:\n pass\n"));
  194. CHECK (! bad->compiled && bad->error.find ("SyntaxError") != std::string::npos && bad->error.find ("line 2") != std::string::npos);
  195. // a runtime error in a callback: logged once, then counted; the script keeps running
  196. State st;
  197. st.kind = Kind::script;
  198. st.tag = 0x165d0001;
  199. const char* src = R"(
  200. import flvfx as vfx
  201. print('hello from the script')
  202. n = 0
  203. def onTick():
  204. global n
  205. n += 1
  206. if n % 2 == 0:
  207. raise ValueError('even tick')
  208. vfx.setOutputController('n', min(1.0, n / 1000.0))
  209. vfx.addOutputController('n', 0)
  210. )";
  211. auto p = makeProcessor (Kind::script, vfxs165::state (src));
  212. p->setTag (st.tag);
  213. vfxs165::play (*p, {}, 8192);
  214. const auto monitor = script::monitorOf (st.tag);
  215. CHECK (monitor != nullptr);
  216. if (monitor == nullptr)
  217. return;
  218. const auto log = monitor->log();
  219. CHECK (log.find ("hello from the script") != std::string::npos);
  220. CHECK (log.find ("ValueError: even tick") != std::string::npos);
  221. CHECK (log.find ("the same error again") != std::string::npos);
  222. CHECK (monitor->status().empty());
  223. CHECK (p->controlOutput (0) > 0.01f);
  224. // an endless loop: interrupted, the instance stops and says why; the audio thread never waits long
  225. script::setRealtime (true);
  226. auto loop = makeProcessor (Kind::script, vfxs165::state ("import flvfx as vfx\ndef onTriggerVoice(v):\n while True:\n try:\n pass\n except:\n pass\n"));
  227. loop->setTag (0x165d0002);
  228. const auto begin = std::chrono::steady_clock::now();
  229. double worst = 0.0;
  230. std::vector<double> times;
  231. for (int b = 0; b < 400; ++b)
  232. {
  233. lynx::vfx::EventList out;
  234. lynx::vfx::Transport t;
  235. auto e = vfx164::on (60);
  236. const auto before = std::chrono::steady_clock::now();
  237. loop->process (&e, b == 0 ? 1 : 0, 512, t, out);
  238. const auto ms = std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now() - before).count();
  239. worst = std::max (worst, ms);
  240. times.push_back (ms);
  241. std::this_thread::sleep_for (std::chrono::milliseconds (2));
  242. }
  243. script::setRealtime (false);
  244. const auto m2 = script::monitorOf (0x165d0002);
  245. // (round 167e: the limit is 250 ms of the Python thread's CPU time, so on a busy machine it may come after the
  246. // 400 blocks: waited for, up to the 1 s wall-clock backstop and some)
  247. for (int w = 0; w < 300 && m2 != nullptr && m2->status().find ("took too long") == std::string::npos; ++w)
  248. std::this_thread::sleep_for (std::chrono::milliseconds (10));
  249. CHECK (m2 != nullptr && m2->status().find ("took too long") != std::string::npos);
  250. std::sort (times.begin(), times.end());
  251. const auto p95 = times[times.size() * 95 / 100];
  252. std::printf (" endless loop: stopped; block wait 95th percentile %.2f ms, worst %.2f ms, %.0f ms in all\n", p95, worst,
  253. std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now() - begin).count());
  254. // the wait is bounded by the budget (2 ms at most); the worst block also carries the OS scheduler's noise on a
  255. // loaded machine (a test thread has no real-time priority)
  256. CHECK (p95 < 2.5);
  257. CHECK (worst < 50.0);
  258. }
  259. extern "C" size_t py_lynx_heap_limit; // (third_party/pocketpy/pocketpy.c: LYNX's heap limit, 768 MB)
  260. TEST (vfx_script_memory_runaway_is_stopped)
  261. {
  262. using namespace lynx::vfx;
  263. // a script that keeps allocating is stopped at LYNX's heap limit, with a message; the memory comes back.
  264. // (round 190fg: the test runs with the limit lowered to 64 MB. Filling the real 768 MB costs the Python thread
  265. // ~0.5 s of page faults on an idle machine; under six parallel test shards plus builds it once took past the
  266. // call's time limit (3 s of CPU, 12 s wall), and the script was stopped as "took too long" before the memory
  267. // stop: the test failed though the product did what it should. The heap counter and the stop are the same at any
  268. // limit; the shipped limit is checked on its own.)
  269. CHECK (py_lynx_heap_limit == ((size_t) 768 << 20));
  270. const auto shipped = py_lynx_heap_limit;
  271. py_lynx_heap_limit = (size_t) 64 << 20;
  272. auto p = makeProcessor (Kind::script, vfxs165::state ("import flvfx as vfx\nkeep = []\ndef onTick():\n while True:\n try:\n keep.append([0] * 400000)\n except:\n pass\n"));
  273. p->setTag (0x165d0005);
  274. const auto cpuBefore = std::clock();
  275. const auto wallBefore = std::chrono::steady_clock::now();
  276. vfxs165::play (*p, {}, 1024);
  277. auto m = script::monitorOf (0x165d0005);
  278. CHECK (m != nullptr && m->status().find ("Stopped: the script used more than 64 MB of memory") != std::string::npos);
  279. if (m != nullptr)
  280. std::printf (" %s\n (process CPU %.0f ms, wall %.0f ms)\n", m->status().c_str(), 1000.0 * (double) (std::clock() - cpuBefore) / CLOCKS_PER_SEC,
  281. std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now() - wallBefore).count());
  282. m.reset();
  283. p.reset(); // (its VM is released: the next script starts with a small heap)
  284. // the memory came back: a list of 1.5 million items (its storage grows to 32 MB) fits under the same 64 MB limit
  285. auto q = makeProcessor (Kind::script, vfxs165::state ("import flvfx as vfx\nbig = [0] * 1500000\ndef onTick():\n vfx.setOutputController('ok', 1)\nvfx.addOutputController('ok', 0)\n"));
  286. vfxs165::play (*q, {}, 512);
  287. CHECK (q->controlOutput (0) == 1.0f);
  288. q.reset();
  289. py_lynx_heap_limit = shipped;
  290. }
  291. // Round 190fg: one operation that asks for more than the heap has room for, in a single allocation, stops the script
  292. // with the same memory message before anything is allocated (list() of a long iterator: as soon as it passes the limit). Before, an allocation past twice the limit failed and
  293. // pocketpy aborted the process ('[0] * 300_000_000': c11_vector__reserve "out of memory") or wrote through a null
  294. // pointer ('x' * 2_000_000_000): one line of a script took LYNX down.
  295. TEST (vfx_script_one_huge_allocation_is_stopped_not_fatal)
  296. {
  297. using namespace lynx::vfx;
  298. // (at a 64 MB limit, as the test above: list(range(...)) fills the heap up to the limit first)
  299. const auto shipped = py_lynx_heap_limit;
  300. py_lynx_heap_limit = (size_t) 64 << 20;
  301. const char* lines[] = { "big = [0] * 300000000", "big = 'x' * 2000000000", "big = 'xy' * 1500000000", "big = [1, 2] * 2000000000",
  302. "big = list(range(200000000))" };
  303. int tag = 0x165d0100;
  304. for (const auto* line : lines)
  305. {
  306. const auto src = std::string ("import flvfx as vfx\ndef onTick():\n try:\n ") + line + "\n except:\n pass\n";
  307. auto p = makeProcessor (Kind::script, vfxs165::state (src));
  308. p->setTag (++tag);
  309. vfxs165::play (*p, {}, 1024);
  310. auto m = script::monitorOf (tag);
  311. CHECK (m != nullptr && m->status().find ("more than 64 MB") != std::string::npos);
  312. if (m != nullptr && m->status().find ("more than 64 MB") == std::string::npos)
  313. std::printf (" %s: %s\n", line, m->status().c_str());
  314. }
  315. // a repeat that fits is untouched
  316. auto ok = makeProcessor (Kind::script, vfxs165::state ("import flvfx as vfx\ns = 'ab' * 1000\nl = [0, 1] * 1000\nr = list(range(5000))\n"
  317. "def onTick():\n vfx.setOutputController('ok', 1 if len(s) == 2000 and len(l) == 2000 and len(r) == 5000 else 0)\n"
  318. "vfx.addOutputController('ok', 0)\n"));
  319. vfxs165::play (*ok, {}, 512);
  320. CHECK (ok->controlOutput (0) == 1.0f);
  321. ok.reset();
  322. py_lynx_heap_limit = shipped;
  323. }
  324. TEST (vfx_script_voice_changes_reach_the_sounding_note)
  325. {
  326. using namespace lynx::vfx;
  327. const char* src = R"(
  328. import flvfx as vfx
  329. def onTriggerVoice(v):
  330. c = vfx.Voice(v)
  331. c.parent = v
  332. c.trigger()
  333. def onTick():
  334. for c in vfx.context.voices:
  335. c.copyFrom(c.parent)
  336. c.note += 0.5
  337. c.pan = -1
  338. )";
  339. auto p = makeProcessor (Kind::script, vfxs165::state (src));
  340. const auto out = vfxs165::play (*p, { vfxs165::on (0, 60) }, 1024);
  341. bool pitch = false, pan = false;
  342. for (const auto& o : out)
  343. if (o.e.type == Event::Type::prop)
  344. {
  345. pitch = pitch || (o.e.prop == Prop::pitch && std::abs (o.e.value - 50.0f) < 1e-3f);
  346. pan = pan || (o.e.prop == Prop::pan && o.e.value == -1.0f);
  347. }
  348. CHECK (pitch && pan);
  349. CHECK (! out.empty() && out[0].e.type == Event::Type::on && out[0].e.voice.key == 60);
  350. }
  351. TEST (vfx_script_python_has_what_fl_scripts_use)
  352. {
  353. using namespace lynx::vfx;
  354. // CPython features pocketpy lacks that FL's factory scripts use: LYNX adds or patches them
  355. const char* src = "import flvfx as vfx\nimport re, random, sys, math, time\n"
  356. "text = '''two lines \\\nas one'''\n"
  357. "class Mine(vfx.Voice):\n def __init__(self):\n super().__init__()\n self.extra: int = 3\n"
  358. "def check():\n"
  359. " assert re.sub(r'choices\\((.*?)\\)( |$)', r'choices(\\1)[0] ', 'choices([1,2],k=1)') == 'choices([1,2],k=1)[0] '\n"
  360. " assert re.findall(r'\\d+', 'a1b22c333') == ['1', '22', '333']\n"
  361. " m = re.match(r'(?P<w>[a-z]+)(\\d)', 'ab7x')\n"
  362. " assert m.group('w') == 'ab' and m.group(2) == '7' and m.span() == (0, 3)\n"
  363. " assert re.split(r',\\s*', 'a, b,c') == ['a', 'b', 'c']\n"
  364. " assert pow(2, 10, 1000) == 24 and pow(2, 3) == 8\n"
  365. " assert sys.float_info.epsilon < 1e-15\n"
  366. " random.seed(1.5)\n"
  367. " g = [random.gauss(0, 1) for i in range(2000)]\n"
  368. " assert abs(sum(g) / len(g)) < 0.15\n"
  369. " assert next((x for x in [1, 5, 9] if x > 4), None) == 5\n"
  370. " assert sum(x * x for x in range(4)) == 14\n"
  371. " assert text == 'two lines as one'\n"
  372. " assert Mine().extra == 3 and Mine().note == 60.0\n"
  373. " assert time.time_ns() > 0\n"
  374. " assert '42'.isdigit() and not '4a'.isdigit() and 'ab'.isalpha() and 'a1'.isalnum() and ' '.isspace()\n"
  375. " assert 'AB'.isupper() and 'ab'.islower() and 'hello world'.title() == 'Hello World'\n"
  376. " assert 'a,b,c'.rsplit(',', 1) == ['a,b', 'c'] and 'a.b.c'.rpartition('.') == ('a.b', '.', 'c')\n"
  377. " assert 'abcabc'.rfind('b') == 4 and 'ab'.center(6, '*') == '**ab**' and 'x'.capitalize() == 'X'\n"
  378. " vfx.setOutputController('ok', 1)\n"
  379. "vfx.addOutputController('ok', 0)\n"
  380. "def onTick():\n check()\n";
  381. auto p = makeProcessor (Kind::script, vfxs165::state (src));
  382. p->setTag (0x165d0003);
  383. vfxs165::play (*p, {}, 512);
  384. CHECK (p->controlOutput (0) == 1.0f);
  385. if (p->controlOutput (0) != 1.0f)
  386. if (const auto m = script::monitorOf (0x165d0003))
  387. std::printf (" %s\n", m->log().c_str());
  388. // the sandbox: no files, no processes
  389. auto q = makeProcessor (Kind::script, vfxs165::state ("import flvfx as vfx\nimport os\n"));
  390. q->setTag (0x165d0004);
  391. const auto m = script::monitorOf (0x165d0004);
  392. CHECK (m != nullptr && m->status().find ("ImportError") != std::string::npos);
  393. CHECK (! script::describe (std::string ("x = open('a.txt', 'w')\n"))->compiled);
  394. }
  395. TEST (vfx_script_late_answers_play_at_the_next_block)
  396. {
  397. using namespace lynx::vfx;
  398. // a script slower than the real-time budget: its note comes later, at the start of the first block after it
  399. // answered. (Round 167e made the margins larger; round 190at removed them: the macOS CI still failed now and then
  400. // because the audio thread, preempted for longer than the script's 40 ms between handing the block over and
  401. // looking at the answer, found it on time. The test now holds the Python thread while the first block runs, so the
  402. // answer cannot be on time whatever the scheduling, and releases it after that block returned.)
  403. const char* src = R"(
  404. import flvfx as vfx, time
  405. def onTriggerVoice(v):
  406. c = vfx.Voice(v)
  407. c.trigger()
  408. )";
  409. auto p = makeProcessor (Kind::script, vfxs165::state (src));
  410. script::setRealtime (true);
  411. script::holdScriptThread (true);
  412. lynx::vfx::Transport t;
  413. lynx::vfx::EventList first, later;
  414. auto e = vfx164::on (60, 100);
  415. p->process (&e, 1, 512, t, first);
  416. script::holdScriptThread (false);
  417. int blocks = 0;
  418. for (; blocks < 400 && later.size() == 0; ++blocks)
  419. {
  420. std::this_thread::sleep_for (std::chrono::milliseconds (5));
  421. p->process (nullptr, 0, 512, t, later);
  422. }
  423. script::setRealtime (false);
  424. CHECK (first.size() == 0);
  425. CHECK (later.size() == 1 && later[0].offset == 0 && later[0].voice.key == 60);
  426. // offline (export) it waits: the note is at its sample
  427. lynx::vfx::EventList exact;
  428. auto p2 = makeProcessor (Kind::script, vfxs165::state (src));
  429. p2->process (&e, 1, 512, t, exact);
  430. CHECK (exact.size() == 1 && exact[0].offset == 100);
  431. }
  432. TEST (vfx_script_runs_fl_factory_scripts)
  433. {
  434. using namespace lynx::vfx;
  435. if (realFlpDir.empty())
  436. return;
  437. namespace fs = std::filesystem;
  438. const auto dir = fs::path (realFlpDir) / "Patches" / "Plugin presets" / "Effects" / "VFX Script";
  439. if (! fs::is_directory (dir))
  440. return;
  441. auto load = [&] (const fs::path& file) -> std::optional<ScriptSettings> {
  442. std::ifstream in (file, std::ios::binary);
  443. const std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), {});
  444. const auto st = stateFromFlPreset (bytes, Kind::script);
  445. return st ? parseScript (*st) : std::nullopt;
  446. };
  447. int files = 0, compiled = 0;
  448. double slowest = 0.0;
  449. std::string slowestName;
  450. for (const auto& entry : fs::recursive_directory_iterator (dir))
  451. {
  452. if (entry.path().extension() != ".fst")
  453. continue;
  454. const auto s = load (entry.path());
  455. if (! s)
  456. continue;
  457. ++files;
  458. const auto info = script::describe (*s);
  459. if (info->compiled)
  460. ++compiled;
  461. else
  462. std::printf (" %s: %s\n", entry.path().filename().string().c_str(), info->error.c_str());
  463. // each one runs 2 s with a held chord and the song playing, without an error
  464. auto p = makeProcessor (Kind::script, writeScript (*s));
  465. p->setTag (0x165d1000 + (std::uint32_t) files);
  466. const auto begin = std::chrono::steady_clock::now();
  467. vfxs165::play (*p, { vfxs165::on (0, 60), vfxs165::on (0, 64), vfxs165::on (0, 67), vfxs165::off (44100, 60), vfxs165::off (44100, 64), vfxs165::off (44100, 67) },
  468. 88200);
  469. const auto ms = std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now() - begin).count();
  470. if (ms > slowest)
  471. slowest = ms, slowestName = entry.path().filename().string();
  472. if (const auto m = script::monitorOf (0x165d1000 + (std::uint32_t) files))
  473. if (m->log().find ("Error") != std::string::npos)
  474. std::printf (" %s ran with errors:\n%s\n", entry.path().filename().string().c_str(), m->log().c_str());
  475. }
  476. std::printf (" %d of %d FL scripts compile; slowest: %s, 2 s of audio in %.1f ms\n", compiled, files, slowestName.c_str(), slowest);
  477. CHECK (files >= 80 && compiled == files);
  478. // FL's Snap To Scale (spec S6): Enable, C major, Down: 61 → 60, 63 → 62; Up: 61 → 62
  479. if (auto s = load (dir / "Snap To Scale.fst"))
  480. {
  481. const auto info = script::describe (*s);
  482. auto v = script::valuesOf (*info, *s);
  483. auto set = [&] (const char* name, double value) {
  484. if (const auto i = info->index (name); i >= 0)
  485. v.numbers[(std::size_t) i] = value;
  486. };
  487. set ("Snap to Scale: Enable", 1);
  488. set ("Snap to Scale: Key", 0);
  489. set ("Snap to Scale: Scale", 0);
  490. set ("Snap to Scale: Snap Direction", 1);
  491. script::writeValues (*s, *info, v);
  492. auto p = makeProcessor (Kind::script, writeScript (*s));
  493. auto keys = vfxs165::keysOn (vfxs165::play (*p, { vfxs165::on (0, 61), vfxs165::on (10, 63), vfxs165::on (20, 60) }, 512));
  494. CHECK ((keys == std::vector<int> { 60, 62, 60 }));
  495. set ("Snap to Scale: Snap Direction", 0);
  496. script::writeValues (*s, *info, v);
  497. p->configure (writeScript (*s));
  498. keys = vfxs165::keysOn (vfxs165::play (*p, { vfxs165::on (0, 61) }, 512));
  499. CHECK ((keys == std::vector<int> { 62 }));
  500. }
  501. // FL's Arpeggiator (Up, 2 per beat, 0.75 long): C E G held → C E G C… every 48 ticks
  502. if (auto s = load (dir / "Arpeggiator.fst"))
  503. {
  504. auto p = makeProcessor (Kind::script, writeScript (*s));
  505. const auto out = vfxs165::play (*p, { vfxs165::on (0, 60), vfxs165::on (0, 64), vfxs165::on (0, 67) }, 44100);
  506. std::vector<int> keys;
  507. std::vector<long> at;
  508. for (const auto& o : out)
  509. if (o.e.type == Event::Type::on)
  510. keys.push_back (o.e.voice.key), at.push_back (o.at);
  511. CHECK (keys.size() >= 4 && keys[0] == 60 && keys[1] == 64 && keys[2] == 67 && keys[3] == 60);
  512. CHECK (at.size() >= 2 && at[1] - at[0] == 11025);
  513. }
  514. // ... synced, Speed 3 (as in FL's render, round 165d): the arpeggio stops when the held notes are released
  515. if (auto s = load (dir / "Arpeggiator.fst"))
  516. {
  517. const auto info = script::describe (*s);
  518. auto v = script::valuesOf (*info, *s);
  519. for (auto [name, value] : { std::pair { "Sync", 1.0 }, { "Speed", 3.0 } })
  520. if (const auto i = info->index (name); i >= 0)
  521. v.numbers[(std::size_t) i] = value;
  522. script::writeValues (*s, *info, v);
  523. auto p = makeProcessor (Kind::script, writeScript (*s));
  524. const auto out = vfxs165::play (*p, { vfxs165::on (5512, 60), vfxs165::on (5512, 64), vfxs165::on (6890, 67), vfxs165::off (97387, 60),
  525. vfxs165::off (97387, 64), vfxs165::off (98765, 67) },
  526. 176400);
  527. long last = 0;
  528. int ons = 0;
  529. for (const auto& o : out)
  530. if (o.e.type == Event::Type::on)
  531. last = o.at, ++ons;
  532. if (last > 99000)
  533. std::printf (" synced arpeggio: %d notes, the last at %ld\n", ons, last);
  534. CHECK (ons >= 10 && last <= 99000);
  535. }
  536. // FL's Note Formula (spec S7): "note + 12", also for a note at the render's first sample (FL has ticked before)
  537. if (auto s = load (dir / "Note Formula Examples" / "1 - Raise the pitch by one octave.fst"))
  538. {
  539. auto p = makeProcessor (Kind::script, writeScript (*s));
  540. auto keys = vfxs165::keysOn (vfxs165::play (*p, { vfxs165::on (300, 60) }, 2048));
  541. CHECK ((keys == std::vector<int> { 72 }));
  542. auto first = makeProcessor (Kind::script, writeScript (*s));
  543. keys = vfxs165::keysOn (vfxs165::play (*first, { vfxs165::on (0, 60) }, 2048));
  544. CHECK ((keys == std::vector<int> { 72 }));
  545. }
  546. }