ysfx.cpp 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095
  1. // Copyright 2021 Jean Pierre Cimalando
  2. // Copyright 2024 Joep Vanlier
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. //
  16. // Modifications by Joep Vanlier, 2024
  17. //
  18. // SPDX-License-Identifier: Apache-2.0
  19. //
  20. #include "ysfx.hpp"
  21. #include "ysfx_config.hpp"
  22. #include "ysfx_eel_utils.hpp"
  23. #include "ysfx_api_eel.hpp"
  24. #include "ysfx_preprocess.hpp"
  25. #include "ysfx_api_host_interaction_dummy.hpp"
  26. #include "ysfx_api_gfx.hpp"
  27. #include "ysfx_gmem.hpp"
  28. #include <type_traits>
  29. #include <algorithm>
  30. #include <functional>
  31. #include <deque>
  32. #include <set>
  33. #include <new>
  34. #include <map>
  35. #include <string>
  36. #include <stdexcept>
  37. #include <cstring>
  38. #include <cassert>
  39. #include <cmath>
  40. #include <cfenv> // LYNX (ysfx_lynx_fp_guard)
  41. // LYNX: a script's code leaves the calling thread's floating-point control register changed on aarch64 (FPCR 0 -> 0x2800000,
  42. // i.e. rounding toward minus infinity and default NaN; LYNX's Linux arm64 self-test, rollup 0.1.31 step 7), and the host's
  43. // own float work on that thread (parsing, rendering, drawing) then rounds differently. Every entry that compiles or runs
  44. // EEL code puts the caller's environment back when it returns.
  45. struct ysfx_lynx_fp_guard {
  46. std::fenv_t env;
  47. ysfx_lynx_fp_guard() { std::fegetenv(&env); }
  48. ~ysfx_lynx_fp_guard() { std::fesetenv(&env); }
  49. ysfx_lynx_fp_guard(const ysfx_lynx_fp_guard &) = delete;
  50. ysfx_lynx_fp_guard &operator=(const ysfx_lynx_fp_guard &) = delete;
  51. };
  52. static_assert(std::is_same<EEL_F, ysfx_real>::value,
  53. "ysfx_real is incorrectly defined");
  54. enum {
  55. ysfx_max_file_handles = 64, // change if it needs more
  56. };
  57. //------------------------------------------------------------------------------
  58. static thread_local ysfx_thread_id_t ysfx_thread_id;
  59. ysfx_thread_id_t ysfx_get_thread_id()
  60. {
  61. return ysfx_thread_id;
  62. }
  63. void ysfx_set_thread_id(ysfx_thread_id_t id)
  64. {
  65. ysfx_thread_id = id;
  66. }
  67. //------------------------------------------------------------------------------
  68. struct ysfx_api_initializer {
  69. private:
  70. ysfx_api_initializer();
  71. ~ysfx_api_initializer();
  72. public:
  73. static void init_once();
  74. };
  75. ysfx_api_initializer::ysfx_api_initializer()
  76. {
  77. if (NSEEL_init() != 0)
  78. throw std::runtime_error("NSEEL_init");
  79. ysfx_api_init_eel();
  80. ysfx_api_init_reaper();
  81. ysfx_api_init_file();
  82. ysfx_api_init_gfx();
  83. ysfx_api_init_host_interaction();
  84. }
  85. ysfx_api_initializer::~ysfx_api_initializer()
  86. {
  87. NSEEL_quit();
  88. }
  89. void ysfx_api_initializer::init_once()
  90. {
  91. static ysfx_api_initializer init;
  92. }
  93. // Only non-built ins should be reset on @init, so we need to log the ones that are built in
  94. // so we can ignore them when the plugin runs and we hit @init.
  95. EEL_F *registerVariable(ysfx_u *fx, NSEEL_VMCTX ctx, const char* name) {
  96. EEL_F* var = NSEEL_VM_regvar(ctx, name);
  97. (*fx)->built_ins.vars[(*fx)->built_ins.count] = var;
  98. (*fx)->built_ins.count += 1;
  99. return var;
  100. };
  101. //------------------------------------------------------------------------------
  102. ysfx_t *ysfx_new(ysfx_config_t *config)
  103. {
  104. ysfx_u fx{new ysfx_t};
  105. fx->built_ins.count = 0;
  106. ysfx_config_add_ref(config);
  107. fx->config.reset(config);
  108. fx->string_ctx.reset(ysfx_eel_string_context_new());
  109. ysfx_api_initializer::init_once();
  110. NSEEL_VMCTX vm = NSEEL_VM_alloc();
  111. if (!vm)
  112. throw std::bad_alloc();
  113. fx->vm.reset(vm);
  114. NSEEL_VM_SetCustomFuncThis(vm, fx.get());
  115. ysfx_eel_string_initvm(vm);
  116. #if !defined(YSFX_NO_GFX)
  117. fx->gfx.state.reset(ysfx_gfx_state_new(fx.get()));
  118. #endif
  119. auto var_resolver = [](void *userdata, const char *name) -> EEL_F * {
  120. ysfx_t *fx = (ysfx_t *)userdata;
  121. /* Not very efficient */
  122. std::string lower_name{name};
  123. std::transform(lower_name.begin(), lower_name.end(), lower_name.begin(), ysfx::ascii_tolower);
  124. auto it = fx->source.slider_alias.find(lower_name);
  125. if (it != fx->source.slider_alias.end())
  126. return fx->var.slider[it->second];
  127. return nullptr;
  128. };
  129. NSEEL_VM_set_var_resolver(vm, var_resolver, fx.get());
  130. for (uint32_t i = 0; i < ysfx_max_channels; ++i) {
  131. std::string name = "spl" + std::to_string(i);
  132. EEL_F *var = registerVariable(&fx, vm, name.c_str());
  133. *(fx->var.spl[i] = var) = 0;
  134. }
  135. for (uint32_t i = 0; i < ysfx_max_sliders; ++i) {
  136. std::string name = "slider" + std::to_string(i + 1);
  137. EEL_F *var = registerVariable(&fx, vm, name.c_str());
  138. *(fx->var.slider[i] = var) = 0;
  139. fx->slider_of_var[var] = i;
  140. }
  141. #define AUTOVAR(name, value) *(fx->var.name = registerVariable(&fx, vm, #name)) = (value)
  142. AUTOVAR(srate, fx->sample_rate);
  143. AUTOVAR(num_ch, fx->valid_input_channels);
  144. AUTOVAR(samplesblock, fx->block_size);
  145. AUTOVAR(trigger, 0);
  146. AUTOVAR(tempo, 120);
  147. AUTOVAR(play_state, 1);
  148. AUTOVAR(play_position, 0);
  149. AUTOVAR(beat_position, 0);
  150. AUTOVAR(ts_num, 0);
  151. AUTOVAR(ts_denom, 4);
  152. AUTOVAR(ext_noinit, 0);
  153. AUTOVAR(ext_nodenorm, 0);
  154. AUTOVAR(ext_midi_bus, 0);
  155. AUTOVAR(midi_bus, 0);
  156. AUTOVAR(pdc_delay, 0);
  157. AUTOVAR(pdc_bot_ch, 0);
  158. AUTOVAR(pdc_top_ch, 0);
  159. AUTOVAR(pdc_midi, 0);
  160. // gfx variables
  161. AUTOVAR(gfx_r, 0);
  162. AUTOVAR(gfx_g, 0);
  163. AUTOVAR(gfx_b, 0);
  164. AUTOVAR(gfx_a, 0);
  165. AUTOVAR(gfx_a2, 0);
  166. AUTOVAR(gfx_w, 0);
  167. AUTOVAR(gfx_h, 0);
  168. AUTOVAR(gfx_x, 0);
  169. AUTOVAR(gfx_y, 0);
  170. AUTOVAR(gfx_mode, 0);
  171. AUTOVAR(gfx_clear, 0);
  172. AUTOVAR(gfx_texth, 0);
  173. AUTOVAR(gfx_dest, 0);
  174. AUTOVAR(gfx_ext_retina, 0);
  175. AUTOVAR(mouse_x, 0);
  176. AUTOVAR(mouse_y, 0);
  177. AUTOVAR(mouse_cap, 0);
  178. AUTOVAR(mouse_wheel, 0);
  179. AUTOVAR(mouse_hwheel, 0);
  180. #undef AUTOVAR
  181. fx->midi.in.reset(new ysfx_midi_buffer_t);
  182. fx->midi.out.reset(new ysfx_midi_buffer_t);
  183. ysfx_set_midi_capacity(fx.get(), 1024, true);
  184. fx->file.list.reserve(16);
  185. fx->file.list.emplace_back(new ysfx_serializer_t(fx->vm.get()));
  186. return fx.release();
  187. }
  188. void ysfx_free(ysfx_t *fx)
  189. {
  190. if (!fx)
  191. return;
  192. if (fx->ref_count.fetch_sub(1, std::memory_order_acq_rel) == 1)
  193. {
  194. ysfx_gmem_detach(fx);
  195. delete fx;
  196. }
  197. }
  198. void ysfx_add_ref(ysfx_t *fx)
  199. {
  200. fx->ref_count.fetch_add(1, std::memory_order_relaxed);
  201. }
  202. ysfx_config_t *ysfx_get_config(ysfx_t *fx)
  203. {
  204. return fx->config.get();
  205. }
  206. bool ysfx_load_file(ysfx_t *fx, const char *filepath, uint32_t loadopts)
  207. {
  208. ysfx_unload(fx);
  209. //--------------------------------------------------------------------------
  210. // failure guard
  211. auto fail_guard = ysfx::defer([fx]() { ysfx_unload_source(fx); });
  212. //--------------------------------------------------------------------------
  213. // load the main file
  214. ysfx::file_uid main_uid;
  215. std::map<std::string, ysfx_real> preprocessor_values;
  216. {
  217. ysfx_source_unit_u main{new ysfx_source_unit_t};
  218. ysfx::FILE_u stream{ysfx::fopen_utf8(filepath, "rb")};
  219. if (!stream || !ysfx::get_stream_file_uid(stream.get(), main_uid)) {
  220. ysfx_logf(*fx->config, ysfx_log_error, "%s: cannot open file for reading", ysfx::path_file_name(filepath).c_str());
  221. return false;
  222. }
  223. ysfx_parse_error error;
  224. ysfx::stdio_text_reader raw_reader(stream.get());
  225. //--------------------------------------------------------------------------
  226. // Read the preprocessor configuration (which involves reading only the header) as we need the information to compile the rest
  227. {
  228. if (!ysfx_parse_toplevel(raw_reader, main->toplevel, &error, true)) {
  229. ysfx_logf(*fx->config, ysfx_log_error, "%s:%u: %s", ysfx::path_file_name(filepath).c_str(), error.line + 1, error.message.c_str());
  230. return false;
  231. }
  232. if (!ysfx_parse_header(main->toplevel.header.get(), main->header, &error)) {
  233. ysfx_logf(*fx->config, ysfx_log_error, "%s:%u: %s", ysfx::path_file_name(filepath).c_str(), error.line + 1, error.message.c_str());
  234. return false;
  235. };
  236. for (auto config_item : main->header.config_items) {
  237. preprocessor_values[config_item.identifier] = config_item.default_value; // Load preprocessor defaults
  238. }
  239. raw_reader.rewind();
  240. }
  241. std::string preprocessed;
  242. if (!ysfx_preprocess(raw_reader, &error, preprocessed, preprocessor_values)) {
  243. ysfx_logf(*fx->config, ysfx_log_error, "%s:%u: %s", ysfx::path_file_name(filepath).c_str(), error.line + 1, error.message.c_str());
  244. return false;
  245. }
  246. ysfx::string_text_reader reader = ysfx::string_text_reader(preprocessed.c_str());
  247. if (!ysfx_parse_toplevel(reader, main->toplevel, &error, false)) {
  248. ysfx_logf(*fx->config, ysfx_log_error, "%s:%u: %s", ysfx::path_file_name(filepath).c_str(), error.line + 1, error.message.c_str());
  249. return false;
  250. }
  251. ysfx_parse_header(main->toplevel.header.get(), main->header, &error);
  252. // validity check
  253. if (main->header.desc.empty()) {
  254. ysfx_logf(*fx->config, ysfx_log_warning, "%s: the required `desc` field is missing", ysfx::path_file_name(filepath).c_str());
  255. main->header.desc = ysfx::path_file_name(filepath);
  256. }
  257. if (loadopts & ysfx_load_ignoring_imports)
  258. main->header.imports.clear();
  259. // if no pins are specified and we have @sample, the default is stereo
  260. if (main->toplevel.sample && !main->header.explicit_pins &&
  261. main->header.in_pins.empty() && main->header.out_pins.empty())
  262. {
  263. main->header.in_pins = {"JS input 1", "JS input 2"};
  264. main->header.out_pins = {"JS output 1", "JS output 2"};
  265. }
  266. // register variables aliased to sliders
  267. for (uint32_t i = 0; i < ysfx_max_sliders; ++i) {
  268. if (main->header.sliders[i].exists) {
  269. if (!main->header.sliders[i].var.empty())
  270. {
  271. std::string data = main->header.sliders[i].var;
  272. std::transform(data.begin(), data.end(), data.begin(), ysfx::ascii_tolower);
  273. fx->source.slider_alias.insert({data, i});
  274. }
  275. }
  276. }
  277. fx->source.main = std::move(main);
  278. fx->source.main_file_path.assign(filepath);
  279. // find the bank file, if present
  280. const auto directory = ysfx::path_directory(filepath);
  281. auto filename = ysfx::path_file_name(filepath);
  282. int found_bank = ysfx::case_resolve(directory.c_str(),
  283. (filename + ".rpl").c_str(),
  284. fx->source.bank_path);
  285. if (found_bank == 0) {
  286. if (filename.length() > 5) {
  287. std::string ext = filename.substr(filename.length() - 5, 5);
  288. std::transform(ext.begin(), ext.end(), ext.begin(), ysfx::ascii_tolower);
  289. if (ext == ".jsfx") {
  290. filename = filename.substr(0, filename.length() - 5);
  291. ysfx::case_resolve(directory.c_str(),
  292. (filename + ".rpl").c_str(),
  293. fx->source.bank_path);
  294. }
  295. }
  296. }
  297. // fill the file enums with the contents of directories
  298. ysfx_fill_file_enums(fx);
  299. // find incorrect enums and fix them
  300. ysfx_fix_invalid_enums(fx);
  301. // set the initial mask of visible sliders
  302. ysfx_update_slider_visibility_mask(fx);
  303. }
  304. //--------------------------------------------------------------------------
  305. // load the imports
  306. // we load the imports recursively using post-order
  307. static constexpr uint32_t max_import_level = 32;
  308. std::set<ysfx::file_uid> seen;
  309. std::function<bool(const std::string &, const std::string &, uint32_t)> do_next_import =
  310. [fx, &seen, &do_next_import, &preprocessor_values]
  311. (const std::string &name, const std::string &origin, uint32_t level) -> bool
  312. {
  313. if (level >= max_import_level) {
  314. ysfx_logf(*fx->config, ysfx_log_error, "%s: %s", ysfx::path_file_name(origin.c_str()).c_str(), "too many import levels");
  315. return false;
  316. }
  317. std::string imported_path = ysfx_resolve_import_path(fx, name, origin);
  318. if (imported_path.empty()) {
  319. ysfx_logf(*fx->config, ysfx_log_error, "%s: cannot find import: %s", ysfx::path_file_name(origin.c_str()).c_str(), name.c_str());
  320. return false;
  321. }
  322. ysfx::file_uid imported_uid;
  323. ysfx::FILE_u stream{ysfx::fopen_utf8(imported_path.c_str(), "rb")};
  324. if (!stream || !ysfx::get_stream_file_uid(stream.get(), imported_uid)) {
  325. ysfx_logf(*fx->config, ysfx_log_error, "%s: cannot open file for reading", ysfx::path_file_name(imported_path.c_str()).c_str());
  326. return false;
  327. }
  328. // this file was already visited, skip
  329. if (!seen.insert(imported_uid).second)
  330. return true;
  331. ysfx_source_unit_u unit{new ysfx_source_unit_t};
  332. ysfx::stdio_text_reader raw_reader(stream.get());
  333. // run the preprocessor first
  334. ysfx_parse_error error;
  335. std::string preprocessed;
  336. if (!ysfx_preprocess(raw_reader, &error, preprocessed, preprocessor_values)) {
  337. ysfx_logf(*fx->config, ysfx_log_error, "%s:%u: %s", ysfx::path_file_name(imported_path.c_str()).c_str(), error.line + 1, error.message.c_str());
  338. return false;
  339. }
  340. ysfx::string_text_reader reader = ysfx::string_text_reader(preprocessed.c_str());
  341. // then parse it
  342. if (!ysfx_parse_toplevel(reader, unit->toplevel, &error, false)) {
  343. ysfx_logf(*fx->config, ysfx_log_error, "%s:%u: %s", ysfx::path_file_name(imported_path.c_str()).c_str(), error.line + 1, error.message.c_str());
  344. return false;
  345. }
  346. if (!ysfx_parse_header(unit->toplevel.header.get(), unit->header, &error)) {
  347. ysfx_logf(*fx->config, ysfx_log_error, "%s:%u: %s", ysfx::path_file_name(imported_path.c_str()).c_str(), error.line + 1, error.message.c_str());
  348. return false;
  349. }
  350. // process the imported dependencies, *first*
  351. for (const std::string &name : unit->header.imports) {
  352. if (!do_next_import(name, imported_path.c_str(), level + 1))
  353. return false;
  354. }
  355. // add it to the import sources, *second*
  356. fx->source.imports.push_back(std::move(unit));
  357. return true;
  358. };
  359. for (const std::string &name : fx->source.main->header.imports) {
  360. if (!do_next_import(name, filepath, 0))
  361. return false;
  362. }
  363. //--------------------------------------------------------------------------
  364. // initialize the sliders to defaults
  365. for (uint32_t i = 0; i < ysfx_max_sliders; ++i)
  366. *fx->var.slider[i] = fx->source.main->header.sliders[i].def;
  367. //--------------------------------------------------------------------------
  368. fail_guard.disarm();
  369. return true;
  370. }
  371. bool ysfx_compile(ysfx_t *fx, uint32_t compileopts)
  372. {
  373. ysfx_lynx_fp_guard lynx_fp_guard; // LYNX
  374. ysfx_unload_code(fx);
  375. if (!fx->source.main) {
  376. ysfx_logf(*fx->config, ysfx_log_error, "???: no source is loaded, cannot compile");
  377. return false;
  378. }
  379. //--------------------------------------------------------------------------
  380. // failure guard
  381. auto fail_guard = ysfx::defer([fx]() { ysfx_unload_code(fx); });
  382. //--------------------------------------------------------------------------
  383. // configure VM
  384. NSEEL_VMCTX vm = fx->vm.get();
  385. {
  386. uint32_t maxmem = fx->source.main->header.options.maxmem;
  387. if (maxmem == 0)
  388. maxmem = 8 * 1024 * 1024;
  389. if (maxmem > 128 * 1024 * 1024)
  390. maxmem = 128 * 1024 * 1024;
  391. NSEEL_VM_setramsize(vm, (int)maxmem);
  392. if (fx->source.main->header.options.prealloc != 0) {
  393. NSEEL_VM_preallocram(vm, (int) fx->source.main->header.options.prealloc);
  394. };
  395. ysfx_gmem_attach(fx, fx->source.main->header.options.gmem);
  396. }
  397. //--------------------------------------------------------------------------
  398. // compile
  399. auto compile_section =
  400. [fx](ysfx_section_t *section, const char *name, NSEEL_CODEHANDLE_u &dest) -> bool
  401. {
  402. NSEEL_VMCTX vm = fx->vm.get();
  403. if (section->text.empty()) {
  404. // NOTE: check for empty source, which would return null code
  405. dest.reset();
  406. return true;
  407. }
  408. NSEEL_CODEHANDLE_u code{NSEEL_code_compile_ex(vm, section->text.c_str(), section->line_offset, NSEEL_CODE_COMPILE_FLAG_COMMONFUNCS)};
  409. if (!code) {
  410. ysfx_logf(*fx->config, ysfx_log_error, "%s: %s", name, NSEEL_code_getcodeerror(vm));
  411. return false;
  412. }
  413. dest = std::move(code);
  414. return true;
  415. };
  416. // compile the multiple @init sections, imports first
  417. {
  418. std::vector<ysfx_section_t *> secs;
  419. secs.reserve(fx->source.imports.size() + 1);
  420. // collect init sections: imports first, main second
  421. for (size_t i = 0; i < fx->source.imports.size(); ++i)
  422. secs.push_back(fx->source.imports[i]->toplevel.init.get());
  423. secs.push_back(fx->source.main->toplevel.init.get());
  424. for (ysfx_section_t *sec : secs) {
  425. NSEEL_CODEHANDLE_u code;
  426. if (sec && !compile_section(sec, "@init", code))
  427. return false;
  428. fx->code.init.push_back(std::move(code));
  429. }
  430. }
  431. // compile the other sections, single
  432. // a non-@init section is searched in the main file first;
  433. // if not found, it's inherited from the first import which has it.
  434. ysfx_section_t *slider = ysfx_search_section(fx, ysfx_section_slider);
  435. ysfx_section_t *block = ysfx_search_section(fx, ysfx_section_block);
  436. ysfx_section_t *sample = ysfx_search_section(fx, ysfx_section_sample);
  437. ysfx_section_t *gfx = nullptr;
  438. ysfx_section_t *serialize = nullptr;
  439. if ((compileopts & ysfx_compile_no_gfx) == 0)
  440. gfx = ysfx_search_section(fx, ysfx_section_gfx);
  441. if ((compileopts & ysfx_compile_no_serialize) == 0)
  442. serialize = ysfx_search_section(fx, ysfx_section_serialize);
  443. if (slider && !compile_section(slider, "@slider", fx->code.slider))
  444. return false;
  445. if (block && !compile_section(block, "@block", fx->code.block))
  446. return false;
  447. if (sample && !compile_section(sample, "@sample", fx->code.sample))
  448. return false;
  449. if (gfx && !compile_section(gfx, "@gfx", fx->code.gfx))
  450. return false;
  451. if (serialize && !compile_section(serialize, "@serialize", fx->code.serialize))
  452. return false;
  453. fx->has_serialize = serialize ? true : false;
  454. fx->code.compiled = true;
  455. fx->is_freshly_compiled = true;
  456. fx->must_compute_init = true;
  457. ///
  458. ysfx_eel_string_context_update_named_vars(fx->string_ctx.get(), vm);
  459. fail_guard.disarm();
  460. return true;
  461. }
  462. void ysfx_reinitialize_vars(ysfx_t *fx)
  463. {
  464. auto callback = [](const char *name, EEL_F *var, void *userdata) -> int {
  465. ysfx_s::fixed_variables* built_ins = (ysfx_s::fixed_variables*) userdata;
  466. bool found = false;
  467. for (int i=0; i < built_ins->count; i++) {
  468. // If this is a plugin built-in, we shouldn't reset it.
  469. if (var == built_ins->vars[i]) {
  470. found = true;
  471. }
  472. }
  473. if (
  474. !(true
  475. && strcmp(name, "gfx_r")
  476. && strcmp(name, "gfx_g")
  477. && strcmp(name, "gfx_b")
  478. && strcmp(name, "gfx_a")
  479. && strcmp(name, "gfx_a2")
  480. && strcmp(name, "gfx_w")
  481. && strcmp(name, "gfx_h")
  482. && strcmp(name, "gfx_x")
  483. && strcmp(name, "gfx_y")
  484. && strcmp(name, "gfx_mode")
  485. && strcmp(name, "gfx_dest")
  486. && strcmp(name, "gfx_clear")
  487. && strcmp(name, "gfx_texth")
  488. && strcmp(name, "mouse_x")
  489. && strcmp(name, "mouse_y")
  490. && strcmp(name, "mouse_y")
  491. && strcmp(name, "mouse_cap")
  492. && strcmp(name, "mouse_wheel")
  493. && strcmp(name, "mouse_hwheel")
  494. && strcmp(name, "gfx_ext_retina")
  495. )
  496. ) {
  497. found = true;
  498. }
  499. if (!found) {
  500. *var = 0;
  501. }
  502. return 1;
  503. };
  504. NSEEL_VM_enumallvars(fx->vm.get(), +callback, &fx->built_ins);
  505. }
  506. bool ysfx_is_compiled(ysfx_t *fx)
  507. {
  508. return fx->code.compiled;
  509. }
  510. void ysfx_unload_source(ysfx_t *fx)
  511. {
  512. fx->source = {};
  513. }
  514. void ysfx_unload_code(ysfx_t *fx)
  515. {
  516. ysfx_lynx_fp_guard lynx_fp_guard; // LYNX
  517. #if !defined(YSFX_NO_GFX)
  518. // get rid of gfx first, to prevent a UI thread from trying
  519. // to access VM and invoke code
  520. {
  521. std::lock_guard<ysfx::mutex> lock{fx->gfx.mutex};
  522. fx->gfx.ready = false;
  523. fx->gfx.wants_retina = false;
  524. fx->gfx.must_init.store(false);
  525. }
  526. #endif
  527. fx->code = {};
  528. fx->is_freshly_compiled = false;
  529. fx->must_compute_init = false;
  530. fx->must_compute_slider = false;
  531. NSEEL_VMCTX vm = fx->vm.get();
  532. NSEEL_code_compile_ex(vm, nullptr, 0, NSEEL_CODE_COMPILE_FLAG_COMMONFUNCS_RESET);
  533. NSEEL_VM_remove_unused_vars(vm);
  534. NSEEL_VM_remove_all_nonreg_vars(vm);
  535. NSEEL_VM_freeRAM(vm);
  536. }
  537. void ysfx_unload(ysfx_t *fx)
  538. {
  539. ysfx_unload_code(fx);
  540. ysfx_unload_source(fx);
  541. }
  542. bool ysfx_is_loaded(ysfx_t *fx)
  543. {
  544. return fx->source.main != nullptr;
  545. }
  546. void ysfx_fill_file_enums(ysfx_t *fx)
  547. {
  548. if (fx->config->data_root.empty())
  549. return;
  550. for (uint32_t i = 0; i < ysfx_max_sliders; ++i) {
  551. ysfx_slider_t &slider = fx->source.main->header.sliders[i];
  552. if (slider.path.empty())
  553. continue;
  554. std::string dirpath = ysfx::path_ensure_final_separator((fx->config->data_root + slider.path).c_str());
  555. ysfx::string_list entries = ysfx::list_directory(dirpath.c_str());
  556. for (const std::string &filename : entries) {
  557. if (!filename.empty() && ysfx::is_path_separator(filename.back()))
  558. continue;
  559. std::string filepath = dirpath + filename;
  560. ysfx_file_type_t ftype = ysfx_detect_file_type(fx, filepath.c_str(), nullptr);
  561. if (ftype == ysfx_file_type_none)
  562. continue;
  563. slider.enum_names.push_back(std::move(filename));
  564. }
  565. if (!slider.enum_names.empty())
  566. slider.max = (EEL_F)(slider.enum_names.size() - 1);
  567. }
  568. }
  569. void ysfx_fix_invalid_enums(ysfx_t *fx)
  570. {
  571. //NOTE: regardless of the range of enum sliders in source, it is <0,N-1,1>
  572. // if there is a mismatch, correct and output a warning
  573. for (uint32_t i = 0; i < ysfx_max_sliders; ++i) {
  574. ysfx_slider_t &slider = fx->source.main->header.sliders[i];
  575. if (!slider.is_enum)
  576. continue;
  577. uint32_t count = (uint32_t)slider.enum_names.size();
  578. if (count == 0) {
  579. bool is_file = !slider.path.empty();
  580. ysfx_logf(*fx->config, ysfx_log_warning, "slider%u: the enumeration does not contain any %s", i + 1, is_file ? "files" : "items");
  581. slider.enum_names.emplace_back();
  582. slider.min = 0;
  583. slider.max = 0;
  584. slider.inc = 1;
  585. }
  586. else if (slider.min != 0 || slider.inc != 1 || slider.max != (EEL_F)(count - 1)) {
  587. ysfx_logf(*fx->config, ysfx_log_warning, "slider%u: the enumeration has an invalid range", i + 1);
  588. slider.min = 0;
  589. slider.max = (EEL_F)(count - 1);
  590. slider.inc = 1;
  591. }
  592. }
  593. }
  594. const char *ysfx_get_name(ysfx_t *fx)
  595. {
  596. ysfx_source_unit_t *main = fx->source.main.get();
  597. if (!main)
  598. return "";
  599. return main->header.desc.c_str();
  600. }
  601. const char *ysfx_get_file_path(ysfx_t *fx)
  602. {
  603. return fx->source.main_file_path.c_str();
  604. }
  605. char *ysfx_resolve_path_and_allocate(ysfx_t* fx, const char* name, const char* origin)
  606. {
  607. if (!fx) return nullptr;
  608. std::string result = ysfx_resolve_import_path(fx, std::string(name), std::string{origin});
  609. if (result.empty()) return nullptr;
  610. char* cPath = static_cast<char*>(malloc(result.size() + 1));
  611. if (cPath) {
  612. strcpy(cPath, result.c_str());
  613. } else {
  614. return nullptr;
  615. }
  616. return cPath;
  617. }
  618. void ysfx_free_resolved_path(char *path)
  619. {
  620. free(path);
  621. path = nullptr;
  622. }
  623. const char *ysfx_get_author(ysfx_t *fx)
  624. {
  625. ysfx_source_unit_t *main = fx->source.main.get();
  626. if (!main)
  627. return "";
  628. return main->header.author.c_str();
  629. }
  630. uint32_t ysfx_get_tags(ysfx_t *fx, const char **dest, uint32_t destsize)
  631. {
  632. ysfx_source_unit_t *main = fx->source.main.get();
  633. if (!main)
  634. return 0;
  635. uint32_t count = (uint32_t)main->header.tags.size();
  636. uint32_t copysize = (destsize < count) ? destsize : count;
  637. for (uint32_t i = 0; i < copysize; ++i)
  638. dest[i] = main->header.tags[i].c_str();
  639. return count;
  640. }
  641. const char *ysfx_get_tag(ysfx_t *fx, uint32_t index)
  642. {
  643. ysfx_source_unit_t *main = fx->source.main.get();
  644. if (!main || index >= main->header.tags.size())
  645. return "";
  646. return main->header.tags[index].c_str();
  647. }
  648. uint32_t ysfx_get_num_inputs(ysfx_t *fx)
  649. {
  650. ysfx_source_unit_t *main = fx->source.main.get();
  651. if (!main)
  652. return 0;
  653. return (uint32_t)main->header.in_pins.size();
  654. }
  655. uint32_t ysfx_get_num_outputs(ysfx_t *fx)
  656. {
  657. ysfx_source_unit_t *main = fx->source.main.get();
  658. if (!main)
  659. return 0;
  660. return (uint32_t)main->header.out_pins.size();
  661. }
  662. const char *ysfx_get_input_name(ysfx_t *fx, uint32_t index)
  663. {
  664. ysfx_source_unit_t *main = fx->source.main.get();
  665. if (!main || index >= main->header.in_pins.size())
  666. return "";
  667. return main->header.in_pins[index].c_str();
  668. }
  669. const char *ysfx_get_output_name(ysfx_t *fx, uint32_t index)
  670. {
  671. ysfx_source_unit_t *main = fx->source.main.get();
  672. if (!main || index >= main->header.out_pins.size())
  673. return "";
  674. return main->header.out_pins[index].c_str();
  675. }
  676. bool ysfx_wants_meters(ysfx_t *fx)
  677. {
  678. ysfx_source_unit_t *main = fx->source.main.get();
  679. if (!main)
  680. return false;
  681. return !main->header.options.no_meter;
  682. }
  683. bool ysfx_get_gfx_dim(ysfx_t *fx, uint32_t dim[2])
  684. {
  685. ysfx_toplevel_t *origin = nullptr;
  686. ysfx_section_t *sec = ysfx_search_section(fx, ysfx_section_gfx, &origin);
  687. if (!sec) {
  688. if (dim) {
  689. dim[0] = 0;
  690. dim[1] = 0;
  691. }
  692. return false;
  693. }
  694. if (dim) {
  695. dim[0] = origin->gfx_w;
  696. dim[1] = origin->gfx_h;
  697. }
  698. return true;
  699. }
  700. ysfx_section_t *ysfx_search_section(ysfx_t *fx, uint32_t type, ysfx_toplevel_t **origin)
  701. {
  702. if (!fx->source.main)
  703. return nullptr;
  704. auto search =
  705. [fx](ysfx_section_t *(*test)(ysfx_toplevel_t &tl), ysfx_toplevel_t **origin) -> ysfx_section_t *
  706. {
  707. ysfx_toplevel_t *tl = &fx->source.main->toplevel;
  708. ysfx_section_t *sec = test(*tl);
  709. for (size_t i = 0; !sec && i < fx->source.imports.size(); ++i) {
  710. tl = &fx->source.imports[i]->toplevel;
  711. sec = test(*tl);
  712. }
  713. if (origin)
  714. *origin = sec ? tl : nullptr;
  715. return sec;
  716. };
  717. switch (type) {
  718. case ysfx_section_init:
  719. return search([](ysfx_toplevel_t &tl) { return tl.init.get(); }, origin);
  720. case ysfx_section_slider:
  721. return search([](ysfx_toplevel_t &tl) { return tl.slider.get(); }, origin);
  722. case ysfx_section_block:
  723. return search([](ysfx_toplevel_t &tl) { return tl.block.get(); }, origin);
  724. case ysfx_section_sample:
  725. return search([](ysfx_toplevel_t &tl) { return tl.sample.get(); }, origin);
  726. case ysfx_section_gfx:
  727. return search([](ysfx_toplevel_t &tl) { return tl.gfx.get(); }, origin);
  728. case ysfx_section_serialize:
  729. return search([](ysfx_toplevel_t &tl) { return tl.serialize.get(); }, origin);
  730. default:
  731. return nullptr;
  732. }
  733. }
  734. bool ysfx_has_section(ysfx_t *fx, uint32_t type)
  735. {
  736. return ysfx_search_section(fx, type) != nullptr;
  737. }
  738. bool ysfx_slider_exists(ysfx_t *fx, uint32_t index)
  739. {
  740. ysfx_source_unit_t *main = fx->source.main.get();
  741. if (index >= ysfx_max_sliders || !main)
  742. return false;
  743. ysfx_slider_t &slider = main->header.sliders[index];
  744. return slider.exists;
  745. }
  746. const char *ysfx_slider_get_name(ysfx_t *fx, uint32_t index)
  747. {
  748. ysfx_source_unit_t *main = fx->source.main.get();
  749. if (index >= ysfx_max_sliders || !main)
  750. return "";
  751. ysfx_slider_t &slider = main->header.sliders[index];
  752. return slider.desc.c_str();
  753. }
  754. bool ysfx_slider_get_range(ysfx_t *fx, uint32_t index, ysfx_slider_range_t *range)
  755. {
  756. ysfx_source_unit_t *main = fx->source.main.get();
  757. if (index >= ysfx_max_sliders || !main)
  758. return false;
  759. ysfx_slider_t &slider = main->header.sliders[index];
  760. range->def = slider.def;
  761. range->min = slider.min;
  762. range->max = slider.max;
  763. range->inc = slider.inc;
  764. return true;
  765. }
  766. bool ysfx_slider_get_curve(ysfx_t *fx, uint32_t index, ysfx_slider_curve_t *curve)
  767. {
  768. ysfx_source_unit_t *main = fx->source.main.get();
  769. if (index >= ysfx_max_sliders || !main)
  770. return false;
  771. ysfx_slider_t &slider = main->header.sliders[index];
  772. curve->def = slider.def;
  773. curve->min = slider.min;
  774. curve->max = slider.max;
  775. curve->inc = slider.inc;
  776. curve->shape = slider.shape;
  777. curve->modifier = slider.shape_modifier;
  778. return true;
  779. }
  780. // Scaling function for log-based sliders
  781. ysfx_real ysfx_slider_scale_from_normalized_log(ysfx_real value, const ysfx_slider_curve_t *curve)
  782. {
  783. if (curve->modifier == 0) {
  784. if ((curve->min <= 0.0001) || (curve->max <= 0.0001)) {
  785. // Revert to linear if doing stuff is gonna be problematic
  786. return ysfx_slider_scale_from_normalized_linear(value, curve);
  787. } else {
  788. return std::exp((std::log(curve->max) - std::log(curve->min)) * value + std::log(curve->min));
  789. }
  790. } else {
  791. if (std::abs(curve->max - curve->min) < 0.0000001) {
  792. // Revert to linear if doing stuff is gonna be problematic
  793. return ysfx_slider_scale_from_normalized_linear(value, curve);
  794. }
  795. if (std::abs(curve->modifier - curve->min) < 0.0000001) {
  796. // Revert to linear if doing stuff is gonna be problematic
  797. return ysfx_slider_scale_from_normalized_linear(value, curve);
  798. }
  799. // This could all be precomputed.
  800. ysfx_real m = (curve->modifier - curve->min) / (curve->max - curve->min);
  801. ysfx_real mm1 = (m - 1) / m;
  802. mm1 *= mm1;
  803. ysfx_real prefactor = (curve->max - curve->min) / (mm1 - 1);
  804. return prefactor * (std::pow(std::abs(mm1), value) - 1) + curve->min;
  805. }
  806. }
  807. // Scaling function for log-based sliders
  808. ysfx_real ysfx_slider_scale_to_normalized_log(ysfx_real value, const ysfx_slider_curve_t *curve)
  809. {
  810. if (curve->modifier == 0) {
  811. if ((curve->min <= 0.0001) || (curve->max <= 0.0001)) {
  812. // Revert to linear if doing stuff is gonna be problematic
  813. return ysfx_slider_scale_to_normalized_linear(value, curve);
  814. } else {
  815. return (std::log(value) - std::log(curve->min)) / (std::log(curve->max) - std::log(curve->min));
  816. }
  817. } else {
  818. if (std::abs(curve->max - curve->min) < 0.0000001) {
  819. // Revert to linear if doing stuff is gonna be problematic
  820. return ysfx_slider_scale_to_normalized_linear(value, curve);
  821. }
  822. if (std::abs(curve->modifier - curve->min) < 0.0000001) {
  823. // Revert to linear if doing stuff is gonna be problematic
  824. return ysfx_slider_scale_to_normalized_linear(value, curve);
  825. }
  826. // This could all be precomputed
  827. ysfx_real m = (curve->modifier - curve->min) / (curve->max - curve->min);
  828. ysfx_real mm1 = (m - 1) / m;
  829. mm1 *= mm1;
  830. ysfx_real inv_prefactor = (mm1 - 1) / (curve->max - curve->min);
  831. return std::log(std::abs((value - curve->min) * inv_prefactor + 1)) / std::log(std::abs(mm1));
  832. }
  833. }
  834. ysfx_real _sgn(ysfx_real value)
  835. {
  836. return value >= 0 ? 1 : -1;
  837. }
  838. ysfx_real ysfx_slider_scale_from_normalized_sqr_raw(ysfx_real value, const ysfx_slider_curve_t *curve)
  839. {
  840. if ((curve->min < 0) && (curve->max > 0)) {
  841. return std::pow(std::abs(2 * value - 1), curve->modifier) * (value > 0.5 ? curve->max : curve->min);
  842. } else {
  843. ysfx_real offset = std::pow(std::abs(curve->min / curve->max), (1.0 / curve->modifier));
  844. return std::pow(std::abs(value * (1 - offset) + offset), curve->modifier) * curve->max;
  845. }
  846. }
  847. ysfx_real ysfx_slider_scale_from_normalized_sqr(ysfx_real value, const ysfx_slider_curve_t *curve)
  848. {
  849. ysfx_real imaxi = _sgn(curve->max) * std::pow(std::abs(curve->max), 1.0 / curve->modifier);
  850. ysfx_real imini = _sgn(curve->min) * std::pow(std::abs(curve->min), 1.0 / curve->modifier);
  851. ysfx_real interp = value * (imaxi - imini) + imini;
  852. return _sgn(interp) * std::pow(std::abs(interp), curve->modifier);
  853. }
  854. ysfx_real ysfx_slider_scale_to_normalized_sqr_raw(ysfx_real value, const ysfx_slider_curve_t *curve)
  855. {
  856. if ((curve->min < 0) && (curve->max > 0)) {
  857. ysfx_real sgn = (value >= 0) ? 1 : -1;
  858. return 0.5 * (sgn * std::pow(std::abs(value / ((value >= 0.0) ? curve->max : curve->min)), 1.0 / curve->modifier) + 1);
  859. } else {
  860. ysfx_real inv_mod = 1.0 / curve->modifier;
  861. ysfx_real offset = std::pow(std::abs(curve->min / curve->max), inv_mod);
  862. ysfx_real result = (std::pow(std::abs(value / curve->max), inv_mod) - offset) / (1.0 - offset);
  863. return result;
  864. }
  865. }
  866. ysfx_real ysfx_slider_scale_to_normalized_sqr(ysfx_real value, const ysfx_slider_curve_t *curve)
  867. {
  868. ysfx_real inv_mod = 1.0 / curve->modifier;
  869. ysfx_real imaxi = _sgn(curve->max) * std::pow(std::abs(curve->max), inv_mod);
  870. ysfx_real imini = _sgn(curve->min) * std::pow(std::abs(curve->min), inv_mod);
  871. ysfx_real interp = _sgn(value) * std::pow(std::abs(value), inv_mod);
  872. return (interp - imini) / (imaxi - imini);
  873. }
  874. ysfx_real ysfx_slider_scale_to_normalized_linear_raw(ysfx_real value, const ysfx_slider_curve_t *curve)
  875. {
  876. if ((std::signbit(curve->min) != std::signbit(curve->max)) && (curve->min != 0) && (curve->max != 0)) {
  877. if (std::signbit(value) == std::signbit(curve->min)) {
  878. return 0.5 * (1 - value / curve->min);
  879. } else {
  880. return 0.5 * (1 + value / curve->max);
  881. }
  882. } else {
  883. ysfx_real diff = curve->max - curve->min;
  884. if (std::abs(diff) < 1e-12) return curve->min;
  885. return (value - curve->min) / diff;
  886. }
  887. }
  888. ysfx_real ysfx_slider_scale_to_normalized_linear(ysfx_real value, const ysfx_slider_curve_t *curve)
  889. {
  890. ysfx_real diff = curve->max - curve->min;
  891. if (std::abs(diff) < 1e-12) return curve->min;
  892. return (value - curve->min) / diff;
  893. }
  894. ysfx_real ysfx_slider_scale_from_normalized_linear_raw(ysfx_real value, const ysfx_slider_curve_t *curve)
  895. {
  896. if ((std::signbit(curve->min) != std::signbit(curve->max)) && (curve->min != 0) && (curve->max != 0)) {
  897. return (value > 0.5) ? curve->max * (value + value - 1) : curve->min * (1.0 - value - value);
  898. } else {
  899. return value * (curve->max - curve->min) + curve->min;
  900. }
  901. }
  902. ysfx_real ysfx_slider_scale_from_normalized_linear(ysfx_real value, const ysfx_slider_curve_t *curve)
  903. {
  904. return value * (curve->max - curve->min) + curve->min;
  905. }
  906. // convert normalized slider value to ysfx value
  907. ysfx_real ysfx_normalized_to_ysfx_value(ysfx_real normalizedValue, const ysfx_slider_curve_t *curve) {
  908. switch(curve->shape) {
  909. case 2:
  910. return ysfx_slider_scale_from_normalized_sqr(normalizedValue, curve);
  911. case 1:
  912. return ysfx_slider_scale_from_normalized_log(normalizedValue, curve);
  913. default:
  914. return ysfx_slider_scale_from_normalized_linear(normalizedValue, curve);
  915. }
  916. };
  917. // convert ysfx value to normalized slider value
  918. ysfx_real ysfx_ysfx_value_to_normalized(ysfx_real value, const ysfx_slider_curve_t *curve) {
  919. switch(curve->shape) {
  920. case 2:
  921. return ysfx_slider_scale_to_normalized_sqr(value, curve);
  922. case 1:
  923. return ysfx_slider_scale_to_normalized_log(value, curve);
  924. default:
  925. return ysfx_slider_scale_to_normalized_linear(value, curve);
  926. }
  927. };
  928. bool ysfx_slider_is_enum(ysfx_t *fx, uint32_t index)
  929. {
  930. ysfx_source_unit_t *main = fx->source.main.get();
  931. if (index >= ysfx_max_sliders || !main)
  932. return false;
  933. ysfx_slider_t &slider = main->header.sliders[index];
  934. return slider.is_enum;
  935. }
  936. uint32_t ysfx_slider_get_enum_names(ysfx_t *fx, uint32_t index, const char **dest, uint32_t destsize)
  937. {
  938. ysfx_source_unit_t *main = fx->source.main.get();
  939. if (index >= ysfx_max_sliders || !main)
  940. return 0;
  941. ysfx_slider_t &slider = main->header.sliders[index];
  942. uint32_t count = (uint32_t)slider.enum_names.size();
  943. uint32_t copysize = (destsize < count) ? destsize : count;
  944. for (uint32_t i = 0; i < copysize; ++i)
  945. dest[i] = slider.enum_names[i].c_str();
  946. return count;
  947. }
  948. const char *ysfx_slider_get_enum_name(ysfx_t *fx, uint32_t slider_index, uint32_t enum_index)
  949. {
  950. ysfx_source_unit_t *main = fx->source.main.get();
  951. if (slider_index >= ysfx_max_sliders || !main)
  952. return 0;
  953. ysfx_slider_t &slider = main->header.sliders[slider_index];
  954. if (enum_index >= slider.enum_names.size())
  955. return "";
  956. return slider.enum_names[enum_index].c_str();
  957. }
  958. const char *ysfx_slider_path(ysfx_t *fx, uint32_t slider_index) {
  959. ysfx_source_unit_t *main = fx->source.main.get();
  960. if (slider_index >= ysfx_max_sliders || !main)
  961. return 0;
  962. ysfx_slider_t &slider = main->header.sliders[slider_index];
  963. if (slider.path.empty()) {
  964. return 0;
  965. } else {
  966. return slider.path.c_str();
  967. }
  968. }
  969. bool ysfx_slider_is_path(ysfx_t *fx, uint32_t index)
  970. {
  971. ysfx_source_unit_t *main = fx->source.main.get();
  972. if (index >= ysfx_max_sliders || !main)
  973. return false;
  974. ysfx_slider_t &slider = main->header.sliders[index];
  975. return !slider.path.empty();
  976. }
  977. bool ysfx_slider_is_initially_visible(ysfx_t *fx, uint32_t index)
  978. {
  979. ysfx_source_unit_t *main = fx->source.main.get();
  980. if (index >= ysfx_max_sliders || !main)
  981. return false;
  982. ysfx_slider_t &slider = main->header.sliders[index];
  983. return slider.initially_visible;
  984. }
  985. ysfx_real ysfx_slider_get_value(ysfx_t *fx, uint32_t index)
  986. {
  987. if (index >= ysfx_max_sliders)
  988. return 0;
  989. return *fx->var.slider[index];
  990. }
  991. void ysfx_slider_set_value(ysfx_t *fx, uint32_t index, ysfx_real value, bool notify)
  992. {
  993. if (index >= ysfx_max_sliders)
  994. return;
  995. if (*fx->var.slider[index] != value) {
  996. *fx->var.slider[index] = value;
  997. fx->must_compute_slider = notify;
  998. }
  999. }
  1000. std::string ysfx_resolve_import_path(ysfx_t *fx, const std::string &name, const std::string &origin)
  1001. {
  1002. std::vector<std::string> dirs;
  1003. // create the list of search directories
  1004. {
  1005. dirs.reserve(2);
  1006. if (!origin.empty())
  1007. dirs.push_back(ysfx::path_directory(origin.c_str()));
  1008. const std::string &import_root = fx->config->import_root;
  1009. if (!import_root.empty() && dirs[0] != import_root)
  1010. dirs.push_back(import_root);
  1011. }
  1012. // the search should be case-insensitive
  1013. static constexpr bool nocase = true;
  1014. static auto *check_existence = +[](const std::string &dir, const std::string &file, std::string &result_path) -> int {
  1015. if (nocase)
  1016. return ysfx::case_resolve(dir.c_str(), file.c_str(), result_path);
  1017. else {
  1018. result_path = dir + file;
  1019. return ysfx::exists(result_path.c_str());
  1020. }
  1021. };
  1022. // search for the file in these directories directly
  1023. for (const std::string &dir : dirs) {
  1024. std::string resolved;
  1025. if (check_existence(dir, name, resolved))
  1026. return resolved;
  1027. }
  1028. // search for the file recursively
  1029. for (const std::string &dir : dirs) {
  1030. struct visit_data {
  1031. const std::string *name = nullptr;
  1032. std::string resolved;
  1033. };
  1034. visit_data vd;
  1035. vd.name = &name;
  1036. auto visit = [](const std::string &dir, void *data) -> bool {
  1037. visit_data &vd = *(visit_data *)data;
  1038. std::string resolved;
  1039. if (check_existence(dir, *vd.name, resolved)) {
  1040. vd.resolved = std::move(resolved);
  1041. return false;
  1042. }
  1043. return true;
  1044. };
  1045. ysfx::visit_directories(dir.c_str(), +visit, &vd);
  1046. if (!vd.resolved.empty())
  1047. return vd.resolved;
  1048. }
  1049. return std::string{};
  1050. }
  1051. uint32_t ysfx_get_block_size(ysfx_t *fx)
  1052. {
  1053. return fx->block_size;
  1054. }
  1055. ysfx_real ysfx_get_sample_rate(ysfx_t *fx)
  1056. {
  1057. return fx->sample_rate;
  1058. }
  1059. void ysfx_set_block_size(ysfx_t *fx, uint32_t blocksize)
  1060. {
  1061. if (fx->block_size != blocksize) {
  1062. fx->block_size = blocksize;
  1063. fx->must_compute_init = true;
  1064. }
  1065. }
  1066. void ysfx_set_sample_rate(ysfx_t *fx, ysfx_real samplerate)
  1067. {
  1068. if (fx->sample_rate != samplerate) {
  1069. fx->sample_rate = samplerate;
  1070. fx->must_compute_init = true;
  1071. }
  1072. }
  1073. void ysfx_set_midi_capacity(ysfx_t *fx, uint32_t capacity, bool extensible)
  1074. {
  1075. ysfx_midi_reserve(fx->midi.in.get(), capacity, extensible);
  1076. ysfx_midi_reserve(fx->midi.out.get(), capacity, extensible);
  1077. }
  1078. void ysfx_delayed_init(ysfx_t *fx)
  1079. {
  1080. if (!fx->code.compiled)
  1081. return;
  1082. if (*fx->var.ext_noinit)
  1083. return;
  1084. fx->must_compute_init = true;
  1085. }
  1086. void ysfx_init(ysfx_t *fx)
  1087. {
  1088. ysfx_lynx_fp_guard lynx_fp_guard; // LYNX
  1089. if (!fx->code.compiled)
  1090. return;
  1091. bool no_init = *fx->var.ext_noinit;
  1092. *fx->var.samplesblock = (EEL_F)fx->block_size;
  1093. *fx->var.srate = fx->sample_rate;
  1094. if (fx->is_freshly_compiled) {
  1095. *fx->var.pdc_delay = 0;
  1096. *fx->var.pdc_bot_ch = 0;
  1097. *fx->var.pdc_top_ch = 0;
  1098. *fx->var.pdc_midi = 0;
  1099. ysfx_first_init(fx);
  1100. fx->is_freshly_compiled = false;
  1101. } else {
  1102. // This matches the reaper behavior
  1103. if (!fx->has_serialize && !no_init) {
  1104. ysfx_reinitialize_vars(fx);
  1105. }
  1106. }
  1107. ysfx_clear_files(fx);
  1108. for (size_t i = 0; i < fx->code.init.size(); ++i)
  1109. {
  1110. // TODO: @init should never run concurrently with any other thread
  1111. if (!no_init) {
  1112. NSEEL_code_execute(fx->code.init[i].get());
  1113. }
  1114. };
  1115. fx->must_compute_init = false;
  1116. fx->must_compute_slider = true;
  1117. #if !defined(YSFX_NO_GFX)
  1118. // do initializations on next @gfx, on the gfx thread
  1119. // release-acquire order is for VM `gfx_*` variables and `wants_retina`
  1120. fx->gfx.wants_retina = *fx->var.gfx_ext_retina > 0;
  1121. fx->gfx.must_init.store(true, std::memory_order_release);
  1122. #endif
  1123. }
  1124. void ysfx_first_init(ysfx_t *fx)
  1125. {
  1126. assert(fx->code.compiled);
  1127. assert(fx->is_freshly_compiled);
  1128. for (uint32_t i = 0; i < ysfx_max_slider_groups; ++i) {
  1129. fx->slider.automate_mask[i].store(0);
  1130. fx->slider.change_mask[i].store(0);
  1131. fx->slider.touch_mask[i].store(0);
  1132. }
  1133. ysfx_update_slider_visibility_mask(fx);
  1134. }
  1135. ysfx_real ysfx_get_pdc_delay(ysfx_t *fx)
  1136. {
  1137. ysfx_real value = *fx->var.pdc_delay;
  1138. return (value > 0) ? value : 0;
  1139. }
  1140. void ysfx_get_pdc_channels(ysfx_t *fx, uint32_t channels[2])
  1141. {
  1142. if (!channels)
  1143. return;
  1144. int64_t bot = (int64_t)*fx->var.pdc_bot_ch;
  1145. bot = (bot > 0) ? bot : 0;
  1146. bot = (bot < ysfx_max_channels) ? bot : ysfx_max_channels;
  1147. channels[0] = (uint32_t)bot;
  1148. int64_t top = (int64_t)*fx->var.pdc_top_ch;
  1149. top = (top > bot) ? top : bot;
  1150. top = (top < ysfx_max_channels) ? top : ysfx_max_channels;
  1151. channels[1] = (uint32_t)top;
  1152. }
  1153. bool ysfx_get_pdc_midi(ysfx_t *fx)
  1154. {
  1155. return (bool)*fx->var.pdc_midi;
  1156. }
  1157. void ysfx_update_slider_visibility_mask(ysfx_t *fx)
  1158. {
  1159. uint32_t slider_idx = 0;
  1160. for (uint32_t group = 0; group < ysfx_max_slider_groups; ++group) {
  1161. uint64_t visible = 0;
  1162. for (uint32_t i = 0; i < 64; ++i) {
  1163. ysfx_slider_t &slider = fx->source.main->header.sliders[slider_idx++];
  1164. visible |= (uint64_t)slider.initially_visible << i;
  1165. }
  1166. fx->slider.visible_mask[group].store(visible);
  1167. }
  1168. }
  1169. void ysfx_set_time_info(ysfx_t *fx, const ysfx_time_info_t *info)
  1170. {
  1171. uint32_t prev_state = (uint32_t)*fx->var.play_state;
  1172. uint32_t new_state = info->playback_state;
  1173. // unless `ext_noinit`, we should call @init every transport restart
  1174. if (!*fx->var.ext_noinit) {
  1175. auto is_running = [](uint32_t state) {
  1176. return state == ysfx_playback_playing ||
  1177. state == ysfx_playback_recording;
  1178. };
  1179. if (!is_running(prev_state) && is_running(new_state))
  1180. fx->must_compute_init = true;
  1181. }
  1182. *fx->var.tempo = info->tempo;
  1183. *fx->var.play_state = (EEL_F)new_state;
  1184. *fx->var.play_position = info->time_position;
  1185. *fx->var.beat_position = info->beat_position;
  1186. *fx->var.ts_num = (EEL_F)info->time_signature[0];
  1187. *fx->var.ts_denom = (EEL_F)info->time_signature[1];
  1188. }
  1189. void ysfx_gfx_set_window_state(ysfx_t *fx, bool hasFocus, bool windowVisible, bool mouseOver)
  1190. {
  1191. #if !defined(YSFX_NO_GFX)
  1192. ysfx_scoped_gfx_t scope{fx, false};
  1193. auto state = ysfx_gfx_get_context(fx);
  1194. if (state) ysfx_gfx_state_set_window_state(state, hasFocus, windowVisible, mouseOver);
  1195. #endif
  1196. }
  1197. bool ysfx_send_midi(ysfx_t *fx, const ysfx_midi_event_t *event)
  1198. {
  1199. return ysfx_midi_push(fx->midi.in.get(), event);
  1200. }
  1201. bool ysfx_receive_midi(ysfx_t *fx, ysfx_midi_event_t *event)
  1202. {
  1203. return ysfx_midi_get_next(fx->midi.out.get(), event);
  1204. }
  1205. bool ysfx_receive_midi_from_bus(ysfx_t *fx, uint32_t bus, ysfx_midi_event_t *event)
  1206. {
  1207. return ysfx_midi_get_next_from_bus(fx->midi.out.get(), 0, event);
  1208. }
  1209. uint32_t ysfx_current_midi_bus(ysfx_t *fx)
  1210. {
  1211. uint32_t bus = 0;
  1212. if (*fx->var.ext_midi_bus)
  1213. bus = (int32_t)*fx->var.midi_bus;
  1214. return bus;
  1215. }
  1216. bool ysfx_send_trigger(ysfx_t *fx, uint32_t index)
  1217. {
  1218. if (index >= ysfx_max_triggers)
  1219. return false;
  1220. fx->triggers |= 1u << index;
  1221. return true;
  1222. }
  1223. // A little helper function to find which of the bitsets we have to use
  1224. uint8_t ysfx_fetch_slider_group_index(uint32_t slider_number) {
  1225. return slider_number >> 6;
  1226. }
  1227. uint64_t ysfx_slider_mask(uint32_t slider_number, uint8_t group_index) {
  1228. return (uint64_t)1 << (slider_number - (group_index << 6));
  1229. }
  1230. uint64_t ysfx_fetch_slider_changes(ysfx_t *fx, uint8_t slider_group_index)
  1231. {
  1232. return fx->slider.change_mask[slider_group_index].exchange(0);
  1233. }
  1234. uint64_t ysfx_fetch_slider_automations(ysfx_t *fx, uint8_t slider_group_index)
  1235. {
  1236. return fx->slider.automate_mask[slider_group_index].exchange(0);
  1237. }
  1238. bool ysfx_fetch_want_undopoint(ysfx_t *fx)
  1239. {
  1240. if (!fx) return false;
  1241. bool undo_point = fx->want_undo;
  1242. fx->want_undo = false;
  1243. return undo_point;
  1244. }
  1245. uint32_t ysfx_get_requested_framerate(ysfx_t *fx)
  1246. {
  1247. if (!fx || !ysfx_is_compiled(fx)) return 30;
  1248. return fx->source.main->header.options.gfx_hz;
  1249. }
  1250. uint64_t ysfx_fetch_slider_touches(ysfx_t *fx, uint8_t slider_group_index)
  1251. {
  1252. return fx->slider.touch_mask[slider_group_index].load();
  1253. }
  1254. uint64_t ysfx_get_slider_visibility(ysfx_t *fx, uint8_t slider_group_index)
  1255. {
  1256. return fx->slider.visible_mask[slider_group_index].load();
  1257. }
  1258. template <class Real>
  1259. void ysfx_process_generic(ysfx_t *fx, const Real *const *ins, Real *const *outs, uint32_t num_ins, uint32_t num_outs, uint32_t num_frames)
  1260. {
  1261. ysfx_lynx_fp_guard lynx_fp_guard; // LYNX
  1262. ysfx_set_thread_id(ysfx_thread_id_dsp);
  1263. // prepare MIDI input for reading, output for writing
  1264. assert(fx->midi.in->read_pos == 0);
  1265. ysfx_midi_clear(fx->midi.out.get());
  1266. // prepare triggers
  1267. *fx->var.trigger = (EEL_F)fx->triggers;
  1268. fx->triggers = 0;
  1269. if (!fx->code.compiled) {
  1270. // Forward audio if it exists
  1271. for (uint32_t ch = 0; ch < std::min(num_ins, num_outs); ++ch)
  1272. memcpy(outs[ch], ins[ch], num_frames * sizeof(Real));
  1273. // Otherwise silence, since not all DAWs initialize their outs
  1274. for (uint32_t ch = std::min(num_ins, num_outs); ch < num_outs; ++ch)
  1275. memset(outs[ch], 0, num_frames * sizeof(Real));
  1276. } else {
  1277. // compute @init if needed
  1278. if (fx->must_compute_init)
  1279. ysfx_init(fx);
  1280. double denorm_value = 0.0000000000000001;
  1281. if ((fx->var.ext_nodenorm) && (*(fx->var.ext_nodenorm) > 0.5)) {
  1282. denorm_value = 0.0;
  1283. }
  1284. const uint32_t orig_num_ins = num_ins;
  1285. const uint32_t orig_num_outs = num_outs;
  1286. const uint32_t num_code_ins = (uint32_t)fx->source.main->header.in_pins.size();
  1287. const uint32_t num_code_outs = (uint32_t)fx->source.main->header.out_pins.size();
  1288. if (num_ins > num_code_ins)
  1289. num_ins = num_code_ins;
  1290. if (num_outs > num_code_outs)
  1291. num_outs = num_code_outs;
  1292. fx->valid_input_channels = num_ins;
  1293. *fx->var.samplesblock = (EEL_F)num_frames;
  1294. *fx->var.num_ch = (EEL_F)num_ins;
  1295. // compute @slider if needed
  1296. if (fx->must_compute_slider) {
  1297. // TODO: slider must never run concurrently with @sample or @block
  1298. NSEEL_code_execute(fx->code.slider.get());
  1299. fx->must_compute_slider = false;
  1300. }
  1301. // compute @block
  1302. NSEEL_code_execute(fx->code.block.get());
  1303. // compute @sample, once per frame
  1304. if (fx->code.sample) {
  1305. EEL_F **spl = fx->var.spl;
  1306. for (uint32_t i = 0; i < num_frames; ++i) {
  1307. for (uint32_t ch = 0; ch < num_ins; ++ch)
  1308. *spl[ch] = (EEL_F)ins[ch][i] + denorm_value;
  1309. for (uint32_t ch = num_ins; ch < num_code_ins; ++ch)
  1310. *spl[ch] = denorm_value;
  1311. NSEEL_code_execute(fx->code.sample.get());
  1312. for (uint32_t ch = 0; ch < num_outs; ++ch)
  1313. outs[ch][i] = (Real)*spl[ch];
  1314. }
  1315. }
  1316. // either forward or clear any output above the maximum count
  1317. for (uint32_t ch = num_outs; ch < std::min(orig_num_ins, orig_num_outs); ++ch)
  1318. memcpy(outs[ch], ins[ch], num_frames * sizeof(Real));
  1319. for (uint32_t ch = std::max(num_outs, std::min(orig_num_ins, orig_num_outs)); ch < orig_num_outs; ++ch)
  1320. memset(outs[ch], 0, num_frames * sizeof(Real));
  1321. }
  1322. // prepare MIDI input for writing, output for reading
  1323. assert(fx->midi.out->read_pos == 0);
  1324. ysfx_midi_clear(fx->midi.in.get());
  1325. ysfx_set_thread_id(ysfx_thread_id_none);
  1326. }
  1327. void ysfx_process_float(ysfx_t *fx, const float *const *ins, float *const *outs, uint32_t num_ins, uint32_t num_outs, uint32_t num_frames)
  1328. {
  1329. ysfx_process_generic<float>(fx, ins, outs, num_ins, num_outs, num_frames);
  1330. }
  1331. void ysfx_process_double(ysfx_t *fx, const double *const *ins, double *const *outs, uint32_t num_ins, uint32_t num_outs, uint32_t num_frames)
  1332. {
  1333. ysfx_process_generic<double>(fx, ins, outs, num_ins, num_outs, num_frames);
  1334. }
  1335. void ysfx_clear_files(ysfx_t *fx)
  1336. {
  1337. std::lock_guard<ysfx::mutex> list_lock(fx->file.list_mutex);
  1338. // delete all except the serializer
  1339. while (fx->file.list.size() > 1) {
  1340. ysfx_file_t *file = fx->file.list.back().get();
  1341. std::unique_ptr<ysfx::mutex> file_mutex;
  1342. std::unique_lock<ysfx::mutex> file_lock;
  1343. if (file) {
  1344. file_lock = std::unique_lock<ysfx::mutex>{*fx->file.list.back()->m_mutex};
  1345. file_mutex = std::move(fx->file.list.back()->m_mutex);
  1346. }
  1347. fx->file.list.pop_back();
  1348. }
  1349. }
  1350. ysfx_file_t *ysfx_get_file(ysfx_t *fx, uint32_t handle, std::unique_lock<ysfx::mutex> &lock, std::unique_lock<ysfx::mutex> *list_lock)
  1351. {
  1352. std::unique_lock<ysfx::mutex> local_list_lock;
  1353. if (list_lock)
  1354. *list_lock = std::unique_lock<ysfx::mutex>(fx->file.list_mutex);
  1355. else
  1356. local_list_lock = std::unique_lock<ysfx::mutex>(fx->file.list_mutex);
  1357. if (handle >= fx->file.list.size())
  1358. return nullptr;
  1359. ysfx_file_t *file = fx->file.list[handle].get();
  1360. if (!file)
  1361. return nullptr;
  1362. lock = std::unique_lock<ysfx::mutex>{*file->m_mutex};
  1363. return file;
  1364. }
  1365. int32_t ysfx_insert_file(ysfx_t *fx, ysfx_file_t *file)
  1366. {
  1367. std::lock_guard<ysfx::mutex> lock(fx->file.list_mutex);
  1368. //
  1369. size_t noneidx = ~(size_t)0;
  1370. size_t freeidx = noneidx;
  1371. for (size_t i = 0, n = fx->file.list.size(); i < n && freeidx == noneidx; ++i) {
  1372. if (!fx->file.list[i])
  1373. freeidx = i;
  1374. }
  1375. if (freeidx != noneidx) {
  1376. fx->file.list[freeidx].reset(file);
  1377. return (uint32_t)freeidx;
  1378. }
  1379. enum { max_file_handles = 64 };
  1380. size_t pos = fx->file.list.size();
  1381. if (pos >= max_file_handles)
  1382. return -1;
  1383. fx->file.list.emplace_back(file);
  1384. return (uint32_t)pos;
  1385. }
  1386. bool ysfx_load_state(ysfx_t *fx, ysfx_state_t *state)
  1387. {
  1388. if (!fx->code.compiled)
  1389. return false;
  1390. // restore the serialization
  1391. std::string buffer((char *)state->data, state->data_size);
  1392. // restore the sliders
  1393. for (uint32_t i = 0; i < ysfx_max_sliders; ++i)
  1394. *fx->var.slider[i] = fx->source.main->header.sliders[i].def;
  1395. for (uint32_t i = 0, n = state->slider_count; i < n; ++i) {
  1396. uint32_t j = state->sliders[i].index;
  1397. if (j < ysfx_max_sliders && fx->source.main->header.sliders[j].exists)
  1398. *fx->var.slider[j] = state->sliders[i].value;
  1399. }
  1400. fx->must_compute_slider = true;
  1401. // invoke @serialize
  1402. {
  1403. std::unique_lock<ysfx::mutex> lock;
  1404. ysfx_serializer_t *serializer = static_cast<ysfx_serializer_t *>(ysfx_get_file(fx, 0, lock));
  1405. assert(serializer);
  1406. serializer->begin(false, buffer);
  1407. lock.unlock();
  1408. ysfx_serialize(fx);
  1409. lock.lock();
  1410. serializer->end();
  1411. }
  1412. return true;
  1413. }
  1414. bool ysfx_load_serialized_state(ysfx_t *fx, ysfx_state_t *state)
  1415. {
  1416. if (!fx->code.compiled) return false;
  1417. // restore the serialization
  1418. std::string buffer((char *)state->data, state->data_size);
  1419. // invoke @serialize
  1420. {
  1421. std::unique_lock<ysfx::mutex> lock;
  1422. ysfx_serializer_t *serializer = static_cast<ysfx_serializer_t *>(ysfx_get_file(fx, 0, lock));
  1423. assert(serializer);
  1424. serializer->begin(false, buffer);
  1425. lock.unlock();
  1426. ysfx_serialize(fx);
  1427. lock.lock();
  1428. serializer->end();
  1429. }
  1430. return true;
  1431. }
  1432. ysfx_state_t *ysfx_save_state(ysfx_t *fx)
  1433. {
  1434. if (!fx->code.compiled)
  1435. return nullptr;
  1436. std::string buffer;
  1437. // invoke @serialize
  1438. {
  1439. std::unique_lock<ysfx::mutex> lock;
  1440. ysfx_serializer_t *serializer = static_cast<ysfx_serializer_t *>(ysfx_get_file(fx, 0, lock));
  1441. assert(serializer);
  1442. serializer->begin(true, buffer);
  1443. lock.unlock();
  1444. ysfx_serialize(fx);
  1445. lock.lock();
  1446. serializer->end();
  1447. }
  1448. // save the sliders
  1449. ysfx_state_u state{new ysfx_state_t};
  1450. uint32_t slider_count = 0;
  1451. for (uint32_t i = 0; i < ysfx_max_sliders; ++i)
  1452. slider_count += fx->source.main->header.sliders[i].exists;
  1453. state->sliders = new ysfx_state_slider_t[slider_count]{};
  1454. state->slider_count = slider_count;
  1455. for (uint32_t i = 0, j = 0; i < ysfx_max_sliders; ++i) {
  1456. if (fx->source.main->header.sliders[i].exists) {
  1457. state->sliders[j].index = i;
  1458. state->sliders[j].value = *fx->var.slider[i];
  1459. ++j;
  1460. }
  1461. }
  1462. // save the serialization
  1463. state->data_size = buffer.size();
  1464. state->data = new uint8_t[state->data_size];
  1465. memcpy(state->data, buffer.data(), state->data_size);
  1466. //
  1467. return state.release();
  1468. }
  1469. void ysfx_state_free(ysfx_state_t *state)
  1470. {
  1471. if (!state)
  1472. return;
  1473. delete[] state->sliders;
  1474. delete[] state->data;
  1475. delete state;
  1476. }
  1477. ysfx_state_t *ysfx_state_dup(ysfx_state_t *state_in)
  1478. {
  1479. if (!state_in)
  1480. return nullptr;
  1481. ysfx_state_u state_out{new ysfx_state_t};
  1482. uint32_t slider_count = state_out->slider_count = state_in->slider_count;
  1483. size_t data_size = state_out->data_size = state_in->data_size;
  1484. state_out->sliders = new ysfx_state_slider_t[slider_count];
  1485. memcpy(state_out->sliders, state_in->sliders, slider_count * sizeof(ysfx_state_slider_t));
  1486. state_out->data = new uint8_t[data_size];
  1487. memcpy(state_out->data, state_in->data, data_size);
  1488. return state_out.release();
  1489. }
  1490. bool ysfx_is_state_equal(ysfx_state_t *state1, ysfx_state_t *state2)
  1491. {
  1492. if (!state1 || !state2)
  1493. return false;
  1494. if (state1->slider_count != state2->slider_count) return false;
  1495. if (state1->data_size != state2->data_size) return false;
  1496. if (memcmp(state1->data, state2->data, state1->data_size) != 0) return false;
  1497. if (memcmp(state1->sliders, state2->sliders, state1->slider_count * sizeof(ysfx_state_slider_t)) != 0) return false;
  1498. return true;
  1499. }
  1500. void ysfx_serialize(ysfx_t *fx)
  1501. {
  1502. ysfx_lynx_fp_guard lynx_fp_guard; // LYNX
  1503. if (fx->code.serialize) {
  1504. if (fx->must_compute_init)
  1505. ysfx_init(fx);
  1506. NSEEL_code_execute(fx->code.serialize.get());
  1507. }
  1508. }
  1509. uint32_t ysfx_get_slider_of_var(ysfx_t *fx, EEL_F *var)
  1510. {
  1511. auto it = fx->slider_of_var.find(var);
  1512. if (it == fx->slider_of_var.end())
  1513. return ~(uint32_t)0;
  1514. return it->second;
  1515. }
  1516. const char *ysfx_get_bank_path(ysfx_t *fx)
  1517. {
  1518. return fx->source.bank_path.c_str();
  1519. }
  1520. void ysfx_enum_vars(ysfx_t *fx, ysfx_enum_vars_callback_t *callback, void *userdata)
  1521. {
  1522. NSEEL_VM_enumallvars(fx->vm.get(), callback, userdata);
  1523. }
  1524. ysfx_real *ysfx_find_var(ysfx_t *fx, const char *name)
  1525. {
  1526. struct find_data {
  1527. ysfx_real *var = nullptr;
  1528. const char *name = nullptr;
  1529. };
  1530. find_data fd;
  1531. fd.name = name;
  1532. auto callback = [](const char *name, EEL_F *var, void *userdata) -> int {
  1533. find_data *fd = (find_data *)userdata;
  1534. if (strcmp(name, fd->name) != 0)
  1535. return 1;
  1536. fd->var = var;
  1537. return 0;
  1538. };
  1539. NSEEL_VM_enumallvars(fx->vm.get(), +callback, &fd);
  1540. return fd.var;
  1541. }
  1542. ysfx_real ysfx_read_var(ysfx_t *fx, const char *name)
  1543. {
  1544. return static_cast<ysfx_real>(*NSEEL_VM_getvar(fx->vm.get(), name));
  1545. }
  1546. void ysfx_read_vmem(ysfx_t *fx, uint32_t addr, ysfx_real *dest, uint32_t count)
  1547. {
  1548. ysfx_eel_ram_reader reader(fx->vm.get(), addr);
  1549. for (uint32_t i = 0; i < count; ++i)
  1550. dest[i] = reader.read_next();
  1551. }
  1552. ysfx_real ysfx_read_vmem_single(ysfx_t *fx, uint32_t addr)
  1553. {
  1554. uint32_t avail;
  1555. EEL_F* flt_addr = NSEEL_VM_getramptr_noalloc(fx->vm.get(), addr, (int32_t *)&avail);
  1556. return flt_addr ? *flt_addr : 0;
  1557. }
  1558. int ysfx_calculate_used_mem(ysfx_t *fx)
  1559. {
  1560. int validCount{0};
  1561. uint32_t addr{0};
  1562. int usedMemory{0};
  1563. for (uint32_t i = 0; i < UINT32_MAX / NSEEL_RAM_ITEMSPERBLOCK; i++) {
  1564. NSEEL_VM_getramptr_noalloc(fx->vm.get(), addr, &validCount);
  1565. addr += NSEEL_RAM_ITEMSPERBLOCK;
  1566. usedMemory += validCount;
  1567. }
  1568. return usedMemory;
  1569. }
  1570. bool ysfx_find_data_file(ysfx_t *fx, EEL_F *file, std::string &result)
  1571. {
  1572. // 3 possibilities for file
  1573. // - slider
  1574. // - index of filename
  1575. // - string
  1576. std::string filepart;
  1577. bool accept_absolute = false;
  1578. bool accept_relative = false;
  1579. int32_t index = ysfx_eel_round<int32_t>(*file);
  1580. uint32_t slideridx = ysfx_get_slider_of_var(fx, file);
  1581. ysfx_slider_t *slider = nullptr;
  1582. if (slideridx != ~(uint32_t)0)
  1583. slider = &fx->source.main->header.sliders[slideridx];
  1584. if (slider && !slider->path.empty()) {
  1585. int32_t value = ysfx_eel_round<int32_t>(*fx->var.slider[slideridx]);
  1586. if (value < 0 || (uint32_t)value >= slider->enum_names.size())
  1587. return false;
  1588. filepart = slider->path + '/' + slider->enum_names[(uint32_t)value];
  1589. accept_relative = true;
  1590. }
  1591. else if (index >= 0 && (uint32_t)index < fx->source.main->header.filenames.size()) {
  1592. filepart = fx->source.main->header.filenames[(uint32_t)index];
  1593. accept_relative = true;
  1594. }
  1595. else if (ysfx_string_get(fx, *file, filepart)) {
  1596. accept_absolute = true;
  1597. accept_relative = true;
  1598. }
  1599. else
  1600. return false;
  1601. std::vector<std::string> filecandidates;
  1602. filecandidates.reserve(2);
  1603. if (accept_absolute && !ysfx::path_is_relative(filepart.c_str()))
  1604. filecandidates.push_back(filepart);
  1605. else if (accept_relative) {
  1606. filecandidates.push_back(ysfx::path_directory(fx->source.main_file_path.c_str()) + filepart);
  1607. if (!fx->config->data_root.empty())
  1608. filecandidates.push_back(fx->config->data_root + filepart);
  1609. }
  1610. for (const std::string &filepath : filecandidates) {
  1611. if (ysfx::exists(filepath.c_str())) {
  1612. // LYNX: the host's file policy (the script's own folders only, by default) decides whether it may be read
  1613. if (ysfx_lynx_path_filter && !ysfx_lynx_path_filter(filepath.c_str()))
  1614. continue;
  1615. result.assign(filepath);
  1616. return true;
  1617. }
  1618. }
  1619. return false;
  1620. }
  1621. // LYNX: the file policy for scripts' file_open / file sliders / gfx_loadimg (nullptr = every existing file, as upstream)
  1622. ysfx_lynx_path_filter_t *ysfx_lynx_path_filter = nullptr;
  1623. void ysfx_lynx_set_path_filter(ysfx_lynx_path_filter_t *filter)
  1624. {
  1625. ysfx_lynx_path_filter = filter;
  1626. }
  1627. ysfx_file_type_t ysfx_detect_file_type(ysfx_t *fx, const char *path, void **fmtobj)
  1628. {
  1629. if (ysfx::path_has_suffix(path, "txt"))
  1630. return ysfx_file_type_txt;
  1631. if (ysfx::path_has_suffix(path, "raw"))
  1632. return ysfx_file_type_raw;
  1633. for (ysfx_audio_format_t &fmt : fx->config->audio_formats) {
  1634. if (fmt.can_handle(path)) {
  1635. if (fmtobj)
  1636. *fmtobj = &fmt;
  1637. return ysfx_file_type_audio;
  1638. }
  1639. }
  1640. return ysfx_file_type_none;
  1641. }
  1642. void ysfx_gfx_setup(ysfx_t *fx, ysfx_gfx_config_t *gc)
  1643. {
  1644. #if !defined(YSFX_NO_GFX)
  1645. bool doinit = false;
  1646. ysfx_scoped_gfx_t scope{fx, doinit};
  1647. ysfx_gfx_state_set_bitmap(fx->gfx.state.get(), gc->pixels, gc->pixel_width, gc->pixel_height, gc->pixel_stride);
  1648. ysfx_real scale = fx->gfx.wants_retina ? gc->scale_factor : 1;
  1649. ysfx_gfx_state_set_scale_factor(fx->gfx.state.get(), scale);
  1650. ysfx_gfx_state_set_callback_data(fx->gfx.state.get(), gc->user_data);
  1651. ysfx_gfx_state_set_show_menu_callback(fx->gfx.state.get(), gc->show_menu);
  1652. ysfx_gfx_state_set_set_cursor_callback(fx->gfx.state.get(), gc->set_cursor);
  1653. ysfx_gfx_state_set_get_drop_file_callback(fx->gfx.state.get(), gc->get_drop_file);
  1654. #else
  1655. (void)fx;
  1656. (void)gc;
  1657. #endif
  1658. }
  1659. bool ysfx_gfx_wants_retina(ysfx_t *fx)
  1660. {
  1661. #if !defined(YSFX_NO_GFX)
  1662. return fx->gfx.wants_retina;
  1663. #else
  1664. (void)fx;
  1665. return false;
  1666. #endif
  1667. }
  1668. void ysfx_gfx_add_key(ysfx_t *fx, uint32_t mods, uint32_t key, bool press)
  1669. {
  1670. #if !defined(YSFX_NO_GFX)
  1671. bool doinit = true;
  1672. ysfx_scoped_gfx_t scope{fx, doinit};
  1673. if (!fx->gfx.ready)
  1674. return;
  1675. ysfx_gfx_state_add_key(fx->gfx.state.get(), mods, key, press);
  1676. #else
  1677. (void)fx;
  1678. (void)mods;
  1679. (void)key;
  1680. #endif
  1681. }
  1682. void ysfx_gfx_update_mouse(ysfx_t *fx, uint32_t mods, int32_t xpos, int32_t ypos, uint32_t buttons, ysfx_real wheel, ysfx_real hwheel)
  1683. {
  1684. #if !defined(YSFX_NO_GFX)
  1685. bool doinit = true;
  1686. ysfx_scoped_gfx_t scope{fx, doinit};
  1687. if (!fx->gfx.ready)
  1688. return;
  1689. *fx->var.mouse_x = (EEL_F)xpos;
  1690. *fx->var.mouse_y = (EEL_F)ypos;
  1691. *fx->var.mouse_wheel += 512 * wheel;
  1692. *fx->var.mouse_hwheel += 512 * hwheel;
  1693. /*
  1694. 1: lmb
  1695. 2: rmb
  1696. 4: Control (Windows) or Command (macOS) key
  1697. 8: Shift key
  1698. 16: Alt (Windows) or Option (macOS) key
  1699. 32: Windows (Windows) or Control (macOS) key
  1700. 64: middle mouse button
  1701. */
  1702. uint32_t mouse_cap = 0;
  1703. if (buttons & ysfx_button_left)
  1704. mouse_cap |= 1;
  1705. if (buttons & ysfx_button_right)
  1706. mouse_cap |= 2;
  1707. if (buttons & ysfx_button_middle)
  1708. mouse_cap |= 64;
  1709. if (mouse_cap) {
  1710. if (mods & ysfx_mod_shift)
  1711. mouse_cap |= 8;
  1712. if (mods & ysfx_mod_alt)
  1713. mouse_cap |= 16;
  1714. #ifdef __APPLE__
  1715. if (mods & ysfx_mod_ctrl)
  1716. mouse_cap |= 32;
  1717. if (mods & ysfx_mod_super)
  1718. mouse_cap |= 4;
  1719. #else
  1720. // Windows key is currently unavailable
  1721. if (mods & ysfx_mod_ctrl)
  1722. mouse_cap |= 4;
  1723. #endif
  1724. }
  1725. *fx->var.mouse_cap = (EEL_F)mouse_cap;
  1726. #else
  1727. (void)fx;
  1728. (void)mods;
  1729. (void)xpos;
  1730. (void)ypos;
  1731. (void)buttons;
  1732. (void)wheel;
  1733. (void)hwheel;
  1734. #endif
  1735. }
  1736. bool ysfx_gfx_run(ysfx_t *fx)
  1737. {
  1738. #if !defined(YSFX_NO_GFX)
  1739. bool doinit = true;
  1740. ysfx_scoped_gfx_t scope{fx, doinit};
  1741. if (!fx->gfx.ready)
  1742. return false;
  1743. ysfx_gfx_prepare(fx);
  1744. NSEEL_code_execute(fx->code.gfx.get());
  1745. return ysfx_gfx_state_is_dirty(fx->gfx.state.get());
  1746. #else
  1747. (void)fx;
  1748. return false;
  1749. #endif
  1750. }