ysfx_preset.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  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.h"
  21. #include "ysfx_preset.hpp"
  22. #include "ysfx_utils.hpp"
  23. #include <vector>
  24. #include <string>
  25. #include <cstring>
  26. #include <cmath>
  27. #include <algorithm>
  28. #include <utility>
  29. #include <iomanip>
  30. #include <sstream>
  31. #include <locale>
  32. #include "WDL/lineparse.h"
  33. static ysfx_bank_t *ysfx_load_bank_from_rpl_text(const std::string &text);
  34. static void ysfx_parse_preset_from_rpl_blob(ysfx_preset_t *preset, const char *name, const std::vector<uint8_t> &data);
  35. ysfx_bank_t *ysfx_load_bank(const char *path)
  36. {
  37. #if defined(_WIN32)
  38. std::wstring wpath = ysfx::widen(path);
  39. ysfx::FILE_u stream{_wfopen(wpath.c_str(), L"rb")};
  40. #else
  41. ysfx::FILE_u stream{fopen(path, "rb")};
  42. #endif
  43. if (!stream)
  44. return nullptr;
  45. std::string input;
  46. constexpr uint32_t max_input = 1u << 24;
  47. input.reserve(1u << 16);
  48. for (int ch; input.size() < max_input && (ch = fgetc(stream.get())) != EOF; ) {
  49. ch = (ch == '\r' || ch == '\n') ? ' ' : ch;
  50. input.push_back((unsigned char)ch);
  51. }
  52. if (ferror(stream.get()))
  53. return nullptr;
  54. stream.reset();
  55. return ysfx_load_bank_from_rpl_text(input);
  56. }
  57. static void ysfx_preset_clear(ysfx_preset_t *preset)
  58. {
  59. if (!preset) return;
  60. delete[] preset->name;
  61. preset->name = nullptr;
  62. delete[] preset->blob_name;
  63. preset->blob_name = nullptr;
  64. ysfx_state_free(preset->state);
  65. preset->state = nullptr;
  66. }
  67. void ysfx_bank_free(ysfx_bank_t *bank)
  68. {
  69. if (!bank)
  70. return;
  71. delete[] bank->name;
  72. if (ysfx_preset_t *presets = bank->presets) {
  73. uint32_t count = bank->preset_count;
  74. for (uint32_t i = 0; i < count; ++i)
  75. ysfx_preset_clear(&presets[i]);
  76. delete[] presets;
  77. }
  78. delete bank;
  79. }
  80. static ysfx_bank_t *ysfx_load_bank_from_rpl_text(const std::string &text)
  81. {
  82. LineParser parser;
  83. if (parser.parse(text.c_str()) < 0)
  84. return nullptr;
  85. ///
  86. std::vector<ysfx_preset_t> preset_list;
  87. preset_list.reserve(256);
  88. auto list_cleanup = ysfx::defer([&preset_list]() {
  89. for (ysfx_preset_t &pst : preset_list)
  90. ysfx_preset_clear(&pst);
  91. });
  92. ///
  93. int ntok = parser.getnumtokens();
  94. int itok = 0;
  95. if (strcmp("<REAPER_PRESET_LIBRARY", parser.gettoken_str(itok++)) != 0)
  96. return nullptr;
  97. const char *bank_name = parser.gettoken_str(itok++);
  98. while (itok < ntok) {
  99. if (strcmp("<PRESET", parser.gettoken_str(itok++)) == 0) {
  100. const char *preset_name = parser.gettoken_str(itok++);
  101. std::vector<uint8_t> blob;
  102. blob.reserve(64 * 1024);
  103. for (const char *part; itok < ntok &&
  104. strcmp(">", (part = parser.gettoken_str(itok++))) != 0; )
  105. {
  106. std::vector<uint8_t> blobChunk = ysfx::decode_base64(part);
  107. blob.insert(blob.end(), blobChunk.begin(), blobChunk.end());
  108. }
  109. preset_list.emplace_back();
  110. ysfx_preset_t &preset = preset_list.back();
  111. ysfx_parse_preset_from_rpl_blob(&preset, preset_name, blob);
  112. }
  113. }
  114. ///
  115. ysfx_bank_u bank{new ysfx_bank_t{}};
  116. bank->name = ysfx::strdup_using_new(bank_name);
  117. bank->presets = new ysfx_preset_t[(uint32_t)preset_list.size()]{};
  118. bank->preset_count = (uint32_t)preset_list.size();
  119. for (uint32_t i = (uint32_t)preset_list.size(); i-- > 0; ) {
  120. bank->presets[i] = preset_list[i];
  121. preset_list.pop_back();
  122. }
  123. return bank.release();
  124. }
  125. static int hasFunkyCharacters(const char *in)
  126. {
  127. int flags = 0;
  128. const char *p = in;
  129. while (*p && (flags != 15))
  130. {
  131. char c = *p++;
  132. if (c == '"') flags |= 1;
  133. else if (c == '\'') flags |= 2;
  134. else if (c == '`') flags |= 4;
  135. else if (c == ' ') flags |= 8;
  136. }
  137. return flags;
  138. }
  139. std::string escapeString(const char *in)
  140. {
  141. int flags = hasFunkyCharacters(in);
  142. if (flags == 0) return std::string(in);
  143. std::string outString{""};
  144. outString.reserve(64);
  145. if (flags != 15)
  146. {
  147. const char src = (flags & 1) ? ((flags & 2) ? '`' : '\'') : '"';
  148. outString.append(1, src).append(in).append(1, src);
  149. }
  150. else // ick, change ` into '
  151. {
  152. outString.append(1, '`').append(in).append(1, '`');
  153. std::replace(outString.begin() + 1, outString.end() - 1, '`', '\'');
  154. }
  155. return outString;
  156. }
  157. static std::string remove_name_from_preset_blob(const char *text, const char *name, std::string& replaced_name)
  158. {
  159. // Unfortunately, there's some questionable escaping going on sometimes. This is not a problem
  160. // when it comes to the preset header, but in the middle of the blob it can be problematic.
  161. // Here we try to find the name in the blob and replace it, so that special characters don't
  162. // make our life harder than it needs to be.
  163. if (!(hasFunkyCharacters(name) & 7)) return std::string{""};
  164. std::string name_replace{text};
  165. std::size_t name_pos = name_replace.find(name);
  166. if (name_pos == std::string::npos) return std::string{""};
  167. // Make sure what we found is *unique*, otherwise bail out
  168. std::size_t differentMatch = name_replace.find("name", name_pos + 1, 6);
  169. if (differentMatch != std::string::npos) return std::string{""};
  170. // Move left from the name we found until we hit a space (separator).
  171. std::size_t start_pos = name_pos;
  172. while((name_replace[start_pos] != ' ') && (start_pos > 0)) start_pos -= 1;
  173. start_pos += 1;
  174. // Move right until we hit a space.
  175. std::size_t stop_pos = name_pos + strlen(name);
  176. while((name_replace[stop_pos] != ' ') && (stop_pos < name_replace.length())) stop_pos += 1;
  177. replaced_name = name_replace.substr(start_pos, stop_pos - start_pos);
  178. name_replace.replace(start_pos, stop_pos - start_pos, stop_pos - start_pos, '_');
  179. return name_replace;
  180. }
  181. static void ysfx_parse_preset_from_rpl_blob(ysfx_preset_t *preset, const char *name, const std::vector<uint8_t> &data)
  182. {
  183. ysfx_state_t state{};
  184. std::vector<ysfx_state_slider_t> sliders;
  185. preset->blob_name = nullptr;
  186. const char *text = (const char *)data.data();
  187. size_t len = data.size();
  188. // find the null terminator
  189. size_t pos = 0;
  190. while (pos < len && data[pos] != 0)
  191. ++pos;
  192. // skip null terminator if there was one
  193. // otherwise null-terminate the text
  194. std::string textbuf;
  195. if (pos < len)
  196. ++pos;
  197. else {
  198. textbuf.assign(text, len);
  199. text = textbuf.c_str();
  200. }
  201. // whatever follows null is the raw serialization
  202. state.data = const_cast<uint8_t *>(data.data() + pos);
  203. state.data_size = len - pos;
  204. std::string replaced_name;
  205. std::string name_removed = remove_name_from_preset_blob(text, name, replaced_name);
  206. if (!name_removed.empty()) {
  207. text = name_removed.c_str();
  208. // Store the blob name for recall later. This allows us to save files without changing
  209. // these names in any way (they may not actually be the same as the preset name unfortunately)
  210. preset->blob_name = ysfx::strdup_using_new(replaced_name.c_str());
  211. }
  212. // parse a line of 64 slider floats (or '-' if missing)
  213. LineParser parser;
  214. if (parser.parse(text) >= 0) {
  215. sliders.reserve(ysfx_max_sliders);
  216. // Grab the first 64 sliders
  217. for (uint32_t i = 0; i < 64; ++i) {
  218. const char *str = parser.gettoken_str(i);
  219. bool skip = str[0] == '-' && str[1] == '\0';
  220. if (!skip) {
  221. ysfx_state_slider_t slider{};
  222. slider.index = i;
  223. slider.value = (ysfx_real)ysfx::dot_atof(str);
  224. sliders.push_back(slider);
  225. }
  226. }
  227. // Token 64 has the "name" of the preset again, but escaped weirdly (see WDL/projectcontext.cpp maybe?).
  228. const char *str = parser.gettoken_str(65); // Determines whether we continue
  229. if (name_removed.empty()) {
  230. // Store the blob name for recall later
  231. preset->blob_name = ysfx::strdup_using_new(escapeString(parser.gettoken_str(64)).c_str());
  232. }
  233. if (str[0] != '\0') {
  234. // Grab the rest
  235. for (uint32_t i = 0; i < ysfx_max_sliders - 64; ++i) {
  236. const char *str = parser.gettoken_str(i + 65);
  237. bool skip = str[0] == '-' && str[1] == '\0';
  238. if (!skip) {
  239. ysfx_state_slider_t slider{};
  240. slider.index = i + 64;
  241. slider.value = (ysfx_real)ysfx::dot_atof(str);
  242. sliders.push_back(slider);
  243. }
  244. }
  245. }
  246. state.sliders = sliders.data();
  247. state.slider_count = (uint32_t)sliders.size();
  248. }
  249. // If for whatever reason we didn't find a blob name, use the regular name instead.
  250. if (!preset->blob_name) {
  251. preset->blob_name = ysfx::strdup_using_new(escapeString(name).c_str());
  252. }
  253. preset->name = ysfx::strdup_using_new(name);
  254. preset->state = ysfx_state_dup(&state);
  255. }
  256. uint32_t ysfx_preset_exists(ysfx_bank_t *bank, const char* preset_name)
  257. {
  258. if (!bank) return 0;
  259. uint32_t found = 0;
  260. for (uint32_t i=0; i < bank->preset_count; i++) {
  261. if (stricmp(bank->presets[i].name, preset_name) == 0) {
  262. // Preset already exists! We're gonna be overwriting this thing.
  263. found = i + 1;
  264. }
  265. }
  266. return found;
  267. }
  268. ysfx_bank_t *ysfx_create_empty_bank(const char* bank_name)
  269. {
  270. ysfx_bank_u bank{new ysfx_bank_t{}};
  271. bank->name = ysfx::strdup_using_new(bank_name);
  272. bank->preset_count = 0;
  273. return bank.release();
  274. }
  275. // Adds preset to a bank and returns new bank with extra preset. Note that the preset takes responsibility for the memory
  276. // ysfx_state_t* is pointing to. This function returns a *new* bank and you are responsible for cleaning up the old bank.
  277. ysfx_bank_t *ysfx_add_preset_to_bank(ysfx_bank_t *bank_in, const char* preset_name, ysfx_state_t *state)
  278. {
  279. ysfx_bank_u bank{new ysfx_bank_t{}};
  280. bank->name = ysfx::strdup_using_new(bank_in->name);
  281. uint32_t found = ysfx_preset_exists(bank_in, preset_name);
  282. bank->preset_count = (uint32_t)(bank_in->preset_count);
  283. if (found == 0) bank->preset_count += 1;
  284. bank->presets = new ysfx_preset_t[(uint32_t)bank->preset_count]{};
  285. for (uint32_t i=0; i < bank_in->preset_count; i++) {
  286. if ((!found) || (i != (found - 1))) {
  287. bank->presets[i].name = ysfx::strdup_using_new(bank_in->presets[i].name);
  288. bank->presets[i].blob_name = ysfx::strdup_using_new(bank_in->presets[i].blob_name);
  289. bank->presets[i].state = ysfx_state_dup(bank_in->presets[i].state);
  290. }
  291. }
  292. uint32_t index = (found == 0) ? (bank->preset_count - 1) : (found - 1);
  293. bank->presets[index].name = ysfx::strdup_using_new(preset_name);
  294. bank->presets[index].blob_name = ysfx::strdup_using_new(escapeString(preset_name).c_str());
  295. bank->presets[index].state = state;
  296. return bank.release();
  297. }
  298. // Deletes a preset from the bank. This function returns a *new* bank and you are responsible for cleaning up the old bank.
  299. ysfx_bank_t *ysfx_delete_preset_from_bank(ysfx_bank_t *bank_in, const char* preset_name)
  300. {
  301. ysfx_bank_u bank{new ysfx_bank_t{}};
  302. bank->name = ysfx::strdup_using_new(bank_in->name);
  303. uint32_t found = ysfx_preset_exists(bank_in, preset_name);
  304. bank->preset_count = (uint32_t)(bank_in->preset_count);
  305. if (found > 0) bank->preset_count -= 1;
  306. bank->presets = new ysfx_preset_t[(uint32_t)bank->preset_count]{};
  307. uint32_t j = 0;
  308. for (uint32_t i=0; i < bank_in->preset_count; i++) {
  309. if (i != (found - 1)) {
  310. bank->presets[j].name = ysfx::strdup_using_new(bank_in->presets[i].name);
  311. bank->presets[j].blob_name = ysfx::strdup_using_new(bank_in->presets[i].blob_name);
  312. bank->presets[j].state = ysfx_state_dup(bank_in->presets[i].state);
  313. j += 1;
  314. }
  315. }
  316. return bank.release();
  317. }
  318. // Rename a preset from the bank. This function returns a *new* bank and you are responsible for cleaning up the old bank.
  319. ysfx_bank_t *ysfx_rename_preset_from_bank(ysfx_bank_t *bank_in, const char* preset_name, const char* new_preset_name)
  320. {
  321. ysfx_bank_u bank{new ysfx_bank_t{}};
  322. bank->name = ysfx::strdup_using_new(bank_in->name);
  323. uint32_t found = ysfx_preset_exists(bank_in, preset_name);
  324. bank->preset_count = (uint32_t)(bank_in->preset_count);
  325. bank->presets = new ysfx_preset_t[(uint32_t)bank->preset_count]{};
  326. uint32_t j = 0;
  327. for (uint32_t i=0; i < bank_in->preset_count; i++) {
  328. bank->presets[j].state = ysfx_state_dup(bank_in->presets[i].state);
  329. if (i != (found - 1)) {
  330. bank->presets[j].name = ysfx::strdup_using_new(bank_in->presets[i].name);
  331. bank->presets[j].blob_name = ysfx::strdup_using_new(bank_in->presets[i].blob_name);
  332. } else {
  333. bank->presets[j].name = ysfx::strdup_using_new(new_preset_name);
  334. bank->presets[j].blob_name = ysfx::strdup_using_new(new_preset_name);
  335. }
  336. j += 1;
  337. }
  338. return bank.release();
  339. }
  340. // Swap two presets in-place. Does not clear the bank
  341. void ysfx_swap_preset_in_bank(ysfx_bank_t *bank, int32_t preset_idx_1, int32_t preset_idx_2)
  342. {
  343. // Early out if we get invalid counts or in the no-change situation
  344. if (
  345. preset_idx_1 >= static_cast<int32_t>(bank->preset_count) ||
  346. preset_idx_2 >= static_cast<int32_t>(bank->preset_count) ||
  347. preset_idx_1 < 0 ||
  348. preset_idx_2 < 0 ||
  349. preset_idx_1 == preset_idx_2
  350. ) {
  351. return;
  352. }
  353. std::swap(bank->presets[preset_idx_1], bank->presets[preset_idx_2]);
  354. }
  355. std::string double_string(double value) {
  356. std::ostringstream oss;
  357. oss.imbue(std::locale::classic()); // ensure the period is the decimal separator
  358. oss << std::fixed << std::setprecision(6) << value;
  359. std::string result{oss.str()};
  360. result.erase(result.find_last_not_of('0') + 1, std::string::npos);
  361. if (result.back() == '.') {
  362. result.pop_back();
  363. }
  364. result.push_back(' ');
  365. return result;
  366. }
  367. static std::string preset_blob(std::string blob_preset_name, ysfx_state_t *state)
  368. {
  369. std::string blob{""};
  370. blob.reserve(4096);
  371. std::vector<ysfx_real> slider_values(ysfx_max_sliders, 0.0);
  372. std::vector<int> slider_used(ysfx_max_sliders, 0);
  373. bool more_than_64 = true;
  374. for (uint32_t i = 0; i < state->slider_count; i++) {
  375. uint32_t slider_index = state->sliders[i].index;
  376. slider_used[slider_index] = 1;
  377. slider_values[slider_index] = state->sliders[i].value;
  378. if (slider_index >= 64) more_than_64 = true;
  379. }
  380. // Serialize the first 64 sliders
  381. for (uint32_t i = 0; i < 64; i++) {
  382. if (slider_used[i]) {
  383. blob += double_string(slider_values[i]);
  384. } else {
  385. blob += "- ";
  386. }
  387. }
  388. // Print escaped name again
  389. blob += blob_preset_name + " ";
  390. // Serialize the remaining 192 sliders
  391. if (more_than_64) {
  392. for (uint32_t i = 0; i < 192; i++) {
  393. if (slider_used[i + 64]) {
  394. blob += double_string(slider_values[i + 64]);
  395. } else {
  396. blob += "- ";
  397. }
  398. }
  399. }
  400. blob = blob.substr(0, blob.length() - 1); // Strip final space.
  401. // Terminate slider section with a null terminator
  402. blob += '\0';
  403. // Serialize the binary blob
  404. blob += std::string(reinterpret_cast<const char *>(state->data), state->data_size);
  405. const uint8_t *uint8_blob = reinterpret_cast<const uint8_t*>(&blob[0]);
  406. std::string base64_preset = ysfx::encode_base64(uint8_blob, blob.length());
  407. std::string preset_with_linebreaks{""};
  408. for (size_t i = 0; i < base64_preset.length(); i += 128) {
  409. preset_with_linebreaks += std::string(" ") + base64_preset.substr(i, 128) + std::string("\n");
  410. }
  411. return preset_with_linebreaks;
  412. }
  413. std::string ysfx_save_bank_to_rpl_text(ysfx_bank_t *bank)
  414. {
  415. std::string rpl_text{"<REAPER_PRESET_LIBRARY " + escapeString(bank->name) + "\n"};
  416. for (uint32_t i = 0; i < bank->preset_count; i++) {
  417. ysfx_preset_t preset = bank->presets[i];
  418. std::string preset_name{preset.name};
  419. std::string blob_name{preset.blob_name};
  420. std::string presetString{" <PRESET `" + preset_name + "`\n" + preset_blob(blob_name, preset.state) + " >\n"};
  421. rpl_text += presetString;
  422. }
  423. rpl_text += ">\n";
  424. return rpl_text;
  425. }
  426. bool ysfx_save_bank(const char *path, ysfx_bank_t *bank)
  427. {
  428. #if defined(_WIN32)
  429. std::wstring wpath = ysfx::widen(path);
  430. ysfx::FILE_u stream{_wfopen(wpath.c_str(), L"wb")};
  431. #else
  432. ysfx::FILE_u stream{fopen(path, "wb")};
  433. #endif
  434. if (!stream) {
  435. return false;
  436. }
  437. std::string txt = ysfx_save_bank_to_rpl_text(bank);
  438. fwrite(txt.data(), 1, txt.length(), stream.get());
  439. if (ferror(stream.get())) {
  440. return false;
  441. }
  442. stream.reset();
  443. return true;
  444. }