Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

731 lines
18KB

  1. // Copyright 2021 Jean Pierre Cimalando
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //
  15. // SPDX-License-Identifier: Apache-2.0
  16. //
  17. #include "ysfx_utils.hpp"
  18. #include "base64/Base64.hpp"
  19. #include <system_error>
  20. #include <algorithm>
  21. #include <deque>
  22. #include <clocale>
  23. #include <cstring>
  24. #include <cassert>
  25. #if !defined(_WIN32)
  26. # include <sys/stat.h>
  27. # include <sys/types.h>
  28. # include <unistd.h>
  29. # include <dirent.h>
  30. # include <fcntl.h>
  31. #else
  32. # include <windows.h>
  33. # include <io.h>
  34. #endif
  35. namespace ysfx {
  36. #if !defined(_WIN32)
  37. static_assert(sizeof(off_t) == 8, "64-bit large file support is not enabled");
  38. #endif
  39. FILE *fopen_utf8(const char *path, const char *mode)
  40. {
  41. #if defined(_WIN32)
  42. return _wfopen(widen(path).c_str(), widen(mode).c_str());
  43. #else
  44. return fopen(path, mode);
  45. #endif
  46. }
  47. int64_t fseek_lfs(FILE *stream, int64_t off, int whence)
  48. {
  49. #if defined(_WIN32)
  50. return _fseeki64(stream, off, whence);
  51. #else
  52. return fseeko(stream, off, whence);
  53. #endif
  54. }
  55. int64_t ftell_lfs(FILE *stream)
  56. {
  57. #if defined(_WIN32)
  58. return _ftelli64(stream);
  59. #else
  60. return ftello(stream);
  61. #endif
  62. }
  63. //------------------------------------------------------------------------------
  64. namespace {
  65. struct scoped_c_locale
  66. {
  67. scoped_c_locale(int lc, const char *name);
  68. ~scoped_c_locale();
  69. c_locale_t m_loc{};
  70. scoped_c_locale(const scoped_c_locale &) = delete;
  71. scoped_c_locale &operator=(const scoped_c_locale &) = delete;
  72. };
  73. scoped_c_locale::scoped_c_locale(int lc, const char *name)
  74. {
  75. #if defined(_WIN32)
  76. m_loc = _create_locale(lc, name);
  77. #else
  78. switch (lc) {
  79. case LC_ALL:
  80. m_loc = newlocale(LC_ALL_MASK, name, c_locale_t{});
  81. break;
  82. case LC_CTYPE:
  83. m_loc = newlocale(LC_CTYPE_MASK, name, c_locale_t{});
  84. break;
  85. case LC_COLLATE:
  86. m_loc = newlocale(LC_COLLATE_MASK, name, c_locale_t{});
  87. break;
  88. case LC_MONETARY:
  89. m_loc = newlocale(LC_MONETARY_MASK, name, c_locale_t{});
  90. break;
  91. case LC_NUMERIC:
  92. m_loc = newlocale(LC_NUMERIC_MASK, name, c_locale_t{});
  93. break;
  94. case LC_TIME:
  95. m_loc = newlocale(LC_TIME_MASK, name, c_locale_t{});
  96. break;
  97. case LC_MESSAGES:
  98. m_loc = newlocale(LC_MESSAGES_MASK, name, c_locale_t{});
  99. break;
  100. default:
  101. errno = EINVAL;
  102. break;
  103. }
  104. #endif
  105. if (!m_loc)
  106. throw std::system_error(errno, std::generic_category());
  107. }
  108. scoped_c_locale::~scoped_c_locale()
  109. {
  110. if (!m_loc) return;
  111. #if !defined(_WIN32)
  112. freelocale(m_loc);
  113. #else
  114. _free_locale(m_loc);
  115. #endif
  116. }
  117. #if !defined(_WIN32)
  118. struct scoped_posix_uselocale {
  119. explicit scoped_posix_uselocale(c_locale_t loc);
  120. ~scoped_posix_uselocale();
  121. c_locale_t m_loc{};
  122. c_locale_t m_old{};
  123. scoped_posix_uselocale(const scoped_posix_uselocale &) = delete;
  124. scoped_posix_uselocale &operator=(const scoped_posix_uselocale &) = delete;
  125. };
  126. scoped_posix_uselocale::scoped_posix_uselocale(c_locale_t loc)
  127. {
  128. if (loc)
  129. {
  130. m_loc = loc;
  131. m_old = uselocale(loc);
  132. }
  133. }
  134. scoped_posix_uselocale::~scoped_posix_uselocale()
  135. {
  136. if (m_loc)
  137. uselocale(m_old);
  138. }
  139. #endif
  140. } // namespace
  141. //------------------------------------------------------------------------------
  142. c_locale_t c_numeric_locale()
  143. {
  144. static scoped_c_locale loc(LC_NUMERIC, "C");
  145. return loc.m_loc;
  146. }
  147. //------------------------------------------------------------------------------
  148. double c_atof(const char *text, c_locale_t loc)
  149. {
  150. #if defined(_WIN32)
  151. return _atof_l(text, loc);
  152. #else
  153. scoped_posix_uselocale use(loc);
  154. return atof(text);
  155. #endif
  156. }
  157. double c_strtod(const char *text, char **endp, c_locale_t loc)
  158. {
  159. #if defined(_WIN32)
  160. return _strtod_l(text, endp, loc);
  161. #else
  162. scoped_posix_uselocale use(loc);
  163. return strtod(text, endp);
  164. #endif
  165. }
  166. double dot_atof(const char *text)
  167. {
  168. return c_atof(text, c_numeric_locale());
  169. }
  170. double dot_strtod(const char *text, char **endp)
  171. {
  172. return c_strtod(text, endp, c_numeric_locale());
  173. }
  174. bool ascii_isspace(char c)
  175. {
  176. switch (c) {
  177. case ' ': case '\f': case '\n': case '\r': case '\t': case '\v':
  178. return true;
  179. default:
  180. return false;
  181. }
  182. }
  183. bool ascii_isalpha(char c)
  184. {
  185. return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
  186. }
  187. char ascii_tolower(char c)
  188. {
  189. return (c >= 'A' && c <= 'Z') ? (c - 'A' + 'a') : c;
  190. }
  191. char ascii_toupper(char c)
  192. {
  193. return (c >= 'a' && c <= 'z') ? (c - 'a' + 'A') : c;
  194. }
  195. int ascii_casecmp(const char *a, const char *b)
  196. {
  197. for (char ca, cb; (ca = *a++) | (cb = *b++); ) {
  198. ca = ascii_tolower(ca);
  199. cb = ascii_tolower(cb);
  200. if (ca < cb) return -1;
  201. if (ca > cb) return +1;
  202. }
  203. return 0;
  204. }
  205. uint32_t latin1_toupper(uint32_t c)
  206. {
  207. if (c >= 'a' && c <= 'z')
  208. return c - 'a' + 'A';
  209. if ((c >= 0xe0 && c <= 0xf6) || (c >= 0xf8 && c <= 0xfe))
  210. return c - 0x20;
  211. return c;
  212. }
  213. uint32_t latin1_tolower(uint32_t c)
  214. {
  215. if (c >= 'A' && c <= 'Z')
  216. return c - 'A' + 'a';
  217. if ((c >= 0xc0 && c <= 0xd6) || (c >= 0xd8 && c <= 0xde))
  218. return c + 0x20;
  219. return c;
  220. }
  221. char *strdup_using_new(const char *src)
  222. {
  223. size_t len = strlen(src);
  224. char *dst = new char[len + 1];
  225. memcpy(dst, src, len + 1);
  226. return dst;
  227. }
  228. string_list split_strings_noempty(const char *input, bool(*pred)(char))
  229. {
  230. string_list list;
  231. if (input) {
  232. std::string acc;
  233. acc.reserve(256);
  234. for (char c; (c = *input++) != '\0'; ) {
  235. if (!pred(c))
  236. acc.push_back(c);
  237. else {
  238. if (!acc.empty()) {
  239. list.push_back(acc);
  240. acc.clear();
  241. }
  242. }
  243. }
  244. if (!acc.empty())
  245. list.push_back(acc);
  246. }
  247. return list;
  248. }
  249. std::string trim(const char *input, bool(*pred)(char))
  250. {
  251. const char *start = input;
  252. while (*start != '\0' && pred(*start))
  253. ++start;
  254. const char *end = start + strlen(start);
  255. while (end > start && pred(*(end - 1)))
  256. --end;
  257. return std::string(start, end);
  258. }
  259. //------------------------------------------------------------------------------
  260. void pack_u32le(uint32_t value, uint8_t data[4])
  261. {
  262. data[0] = value & 0xff;
  263. data[1] = (value >> 8) & 0xff;
  264. data[2] = (value >> 16) & 0xff;
  265. data[3] = value >> 24;
  266. }
  267. void pack_f32le(float value, uint8_t data[4])
  268. {
  269. uint32_t u;
  270. memcpy(&u, &value, 4);
  271. pack_u32le(u, data);
  272. }
  273. uint32_t unpack_u32le(const uint8_t data[4])
  274. {
  275. return data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
  276. }
  277. float unpack_f32le(const uint8_t data[4])
  278. {
  279. float value;
  280. uint32_t u = unpack_u32le(data);
  281. memcpy(&value, &u, 4);
  282. return value;
  283. }
  284. //------------------------------------------------------------------------------
  285. std::vector<uint8_t> decode_base64(const char *text, size_t len)
  286. {
  287. return d_getChunkFromBase64String(text, len);
  288. }
  289. //------------------------------------------------------------------------------
  290. bool get_file_uid(const char *path, file_uid &uid)
  291. {
  292. #ifdef _WIN32
  293. HANDLE handle = CreateFileW(widen(path).c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr);
  294. if (handle == INVALID_HANDLE_VALUE)
  295. return false;
  296. bool success = get_handle_file_uid((void *)handle, uid);
  297. CloseHandle(handle);
  298. return success;
  299. #else
  300. int fd = open(path, O_RDONLY);
  301. if (fd == -1)
  302. return false;
  303. bool success = get_descriptor_file_uid(fd, uid);
  304. close(fd);
  305. return success;
  306. #endif
  307. }
  308. bool get_stream_file_uid(FILE *stream, file_uid &uid)
  309. {
  310. #if !defined(_WIN32)
  311. int fd = fileno(stream);
  312. if (fd == -1)
  313. return false;
  314. #else
  315. int fd = _fileno(stream);
  316. if (fd == -1)
  317. return false;
  318. #endif
  319. return get_descriptor_file_uid(fd, uid);
  320. }
  321. bool get_descriptor_file_uid(int fd, file_uid &uid)
  322. {
  323. #if !defined(_WIN32)
  324. struct stat st;
  325. if (fstat(fd, &st) != 0)
  326. return false;
  327. uid.first = (uint64_t)st.st_dev;
  328. uid.second = (uint64_t)st.st_ino;
  329. return true;
  330. #else
  331. HANDLE handle = (HANDLE)_get_osfhandle(fd);
  332. if (handle == INVALID_HANDLE_VALUE)
  333. return false;
  334. return get_handle_file_uid((void *)handle, uid);
  335. #endif
  336. }
  337. #if defined(_WIN32)
  338. bool get_handle_file_uid(void *handle, file_uid &uid)
  339. {
  340. BY_HANDLE_FILE_INFORMATION info;
  341. if (!GetFileInformationByHandle((HANDLE)handle, &info))
  342. return false;
  343. uid.first = info.dwVolumeSerialNumber;
  344. uid.second = (uint64_t)info.nFileIndexLow | ((uint64_t)info.nFileIndexHigh << 32);
  345. return true;
  346. }
  347. #endif
  348. //------------------------------------------------------------------------------
  349. bool is_path_separator(char ch)
  350. {
  351. #if !defined(_WIN32)
  352. return ch == '/';
  353. #else
  354. return ch == '/' || ch == '\\';
  355. #endif
  356. }
  357. split_path_t split_path(const char *path)
  358. {
  359. split_path_t sp;
  360. #if !defined(_WIN32)
  361. size_t npos = ~(size_t)0;
  362. size_t pos = npos;
  363. for (size_t i = 0; path[i] != '\0'; ++i) {
  364. if (is_path_separator(path[i]))
  365. pos = i;
  366. }
  367. if (pos == npos)
  368. sp.file.assign(path);
  369. else {
  370. sp.dir.assign(path, pos + 1);
  371. sp.file.assign(path + pos + 1);
  372. }
  373. #else
  374. std::wstring wpath = widen(path);
  375. std::unique_ptr<wchar_t[]> drive{new wchar_t[wpath.size() + 1]{}};
  376. std::unique_ptr<wchar_t[]> dir{new wchar_t[wpath.size() + 1]{}};
  377. std::unique_ptr<wchar_t[]> fname{new wchar_t[wpath.size() + 1]{}};
  378. std::unique_ptr<wchar_t[]> ext{new wchar_t[wpath.size() + 1]{}};
  379. _wsplitpath(wpath.c_str(), drive.get(), dir.get(), fname.get(), ext.get());
  380. sp.drive = narrow(drive.get());
  381. if (!drive[0] || dir[0] == L'/' || dir[0] == L'\\')
  382. sp.dir = narrow(dir.get());
  383. else
  384. sp.dir = narrow(L'\\' + std::wstring(dir.get()));
  385. sp.file = narrow(std::wstring(fname.get()) + std::wstring(ext.get()));
  386. #endif
  387. return sp;
  388. }
  389. std::string path_file_name(const char *path)
  390. {
  391. return split_path(path).file;
  392. }
  393. std::string path_directory(const char *path)
  394. {
  395. split_path_t sp = split_path(path);
  396. return sp.dir.empty() ? std::string("./") : (sp.drive + sp.dir);
  397. }
  398. std::string path_ensure_final_separator(const char *path)
  399. {
  400. std::string result(path);
  401. if (!result.empty() && !is_path_separator(result.back()))
  402. result.push_back('/');
  403. return result;
  404. }
  405. bool path_has_suffix(const char *path, const char *suffix)
  406. {
  407. if (*suffix == '.')
  408. ++suffix;
  409. size_t plen = strlen(path);
  410. size_t slen = strlen(suffix);
  411. if (plen < slen + 2)
  412. return false;
  413. return path[plen - slen - 1] == '.' &&
  414. ascii_casecmp(suffix, &path[plen - slen]) == 0;
  415. }
  416. bool path_is_relative(const char *path)
  417. {
  418. #if !defined(_WIN32)
  419. return !is_path_separator(path[0]);
  420. #else
  421. return !is_path_separator(split_path(path).dir.c_str()[0]);
  422. #endif
  423. }
  424. //------------------------------------------------------------------------------
  425. #if !defined(_WIN32)
  426. bool exists(const char *path)
  427. {
  428. return access(path, F_OK) == 0;
  429. }
  430. string_list list_directory(const char *path)
  431. {
  432. string_list list;
  433. DIR *dir = opendir(path);
  434. if (!dir)
  435. return list;
  436. auto dir_cleanup = defer([dir]() { closedir(dir); });
  437. list.reserve(256);
  438. std::string pathbuf;
  439. pathbuf.reserve(1024);
  440. while (dirent *ent = readdir(dir)) {
  441. const char *name = ent->d_name;
  442. if (!strcmp(name, ".") || !strcmp(name, ".."))
  443. continue;
  444. pathbuf.assign(name);
  445. if (ent->d_type == DT_DIR)
  446. pathbuf.push_back('/');
  447. list.push_back(pathbuf);
  448. }
  449. std::sort(list.begin(), list.end());
  450. return list;
  451. }
  452. // void visit_directories(const char *rootpath, bool (*visit)(const std::string &, void *), void *data);
  453. // NOTE: implemented in separate file `ysfx_utils_fts.cpp`
  454. #else
  455. bool exists(const char *path)
  456. {
  457. return _waccess(widen(path).c_str(), 0) == 0;
  458. }
  459. string_list list_directory(const char *path)
  460. {
  461. string_list list;
  462. std::wstring pattern = widen(path) + L"\\*";
  463. WIN32_FIND_DATAW fd;
  464. HANDLE handle = FindFirstFileW(pattern.c_str(), &fd);
  465. if (handle == INVALID_HANDLE_VALUE)
  466. return list;
  467. auto handle_cleanup = defer([handle]() { FindClose(handle); });
  468. list.reserve(256);
  469. do {
  470. const wchar_t *name = fd.cFileName;
  471. if (!wcscmp(name, L".") || !wcscmp(name, L".."))
  472. continue;
  473. std::string entry = narrow(name);
  474. if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && !(fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT))
  475. entry.push_back('/');
  476. list.push_back(std::move(entry));
  477. } while (FindNextFileW(handle, &fd));
  478. std::sort(list.begin(), list.end());
  479. return list;
  480. }
  481. void visit_directories(const char *rootpath, bool (*visit)(const std::string &, void *), void *data)
  482. {
  483. std::deque<std::wstring> dirs;
  484. dirs.push_back(widen(path_ensure_final_separator(rootpath)));
  485. std::wstring pathbuf;
  486. pathbuf.reserve(1024);
  487. std::vector<std::wstring> entries;
  488. entries.reserve(256);
  489. while (!dirs.empty()) {
  490. std::wstring dir = std::move(dirs.front());
  491. dirs.pop_front();
  492. if (!visit(narrow(dir), data))
  493. return;
  494. pathbuf.assign(dir);
  495. pathbuf.append(L"\\*");
  496. WIN32_FIND_DATAW fd;
  497. HANDLE handle = FindFirstFileW(pathbuf.c_str(), &fd);
  498. if (handle == INVALID_HANDLE_VALUE)
  499. continue;
  500. auto handle_cleanup = defer([handle]() { FindClose(handle); });
  501. entries.clear();
  502. do {
  503. if (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
  504. continue;
  505. if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
  506. const wchar_t *name = fd.cFileName;
  507. if (!wcscmp(name, L".") || !wcscmp(name, L".."))
  508. continue;
  509. pathbuf.assign(dir);
  510. pathbuf.append(name);
  511. pathbuf.push_back(L'\\');
  512. entries.push_back(pathbuf);
  513. }
  514. } while (FindNextFileW(handle, &fd));
  515. std::sort(entries.begin(), entries.end());
  516. for (size_t n = entries.size(); n-- > 0; )
  517. dirs.push_front(std::move(entries[n]));
  518. }
  519. }
  520. #endif
  521. int case_resolve(const char *root_, const char *fragment, std::string &result)
  522. {
  523. if (fragment[0] == '\0')
  524. return 0;
  525. std::string root = path_ensure_final_separator(root_);
  526. std::string pathbuf;
  527. pathbuf.reserve(1024);
  528. pathbuf.assign(root);
  529. pathbuf.append(fragment);
  530. if (exists(pathbuf.c_str())) {
  531. result = std::move(pathbuf);
  532. return 1;
  533. }
  534. struct Item {
  535. std::string root;
  536. string_list components;
  537. };
  538. std::deque<Item> worklist;
  539. {
  540. Item item;
  541. item.root = root;
  542. item.components = split_strings_noempty(fragment, &is_path_separator);
  543. if (item.components.empty())
  544. return 0;
  545. for (size_t i = 0; i + 1 < item.components.size(); ++i)
  546. item.components[i].push_back('/');
  547. if (is_path_separator(fragment[strlen(fragment) - 1]))
  548. item.components.back().push_back('/');
  549. worklist.push_back(std::move(item));
  550. }
  551. while (!worklist.empty()) {
  552. Item item = std::move(worklist.front());
  553. worklist.pop_front();
  554. for (const std::string &entry : list_directory(item.root.c_str())) {
  555. if (ascii_casecmp(entry.c_str(), item.components[0].c_str()) != 0)
  556. continue;
  557. if (item.components.size() == 1) {
  558. pathbuf.assign(item.root);
  559. pathbuf.append(entry);
  560. if (exists(pathbuf.c_str())) {
  561. result = std::move(pathbuf);
  562. return 2;
  563. }
  564. }
  565. else {
  566. assert(item.components.size() > 1);
  567. Item newitem;
  568. newitem.root = item.root + entry;
  569. newitem.components.assign(item.components.begin() + 1, item.components.end());
  570. worklist.push_front(std::move(newitem));
  571. }
  572. }
  573. }
  574. return 0;
  575. }
  576. //------------------------------------------------------------------------------
  577. #if defined(_WIN32)
  578. std::wstring widen(const std::string &u8str)
  579. {
  580. return widen(u8str.data(), u8str.size());
  581. }
  582. std::wstring widen(const char *u8data, size_t u8len)
  583. {
  584. if (u8len == ~(size_t)0)
  585. u8len = strlen(u8data);
  586. std::wstring wstr;
  587. int wch = MultiByteToWideChar(CP_UTF8, 0, u8data, (int)u8len, nullptr, 0);
  588. if (wch != 0) {
  589. wstr.resize((size_t)wch);
  590. MultiByteToWideChar(CP_UTF8, 0, u8data, (int)u8len, &wstr[0], wch);
  591. }
  592. return wstr;
  593. }
  594. std::string narrow(const std::wstring &wstr)
  595. {
  596. return narrow(wstr.data(), wstr.size());
  597. }
  598. std::string narrow(const wchar_t *wdata, size_t wlen)
  599. {
  600. if (wlen == ~(size_t)0)
  601. wlen = wcslen(wdata);
  602. std::string u8str;
  603. int u8ch = WideCharToMultiByte(CP_UTF8, 0, wdata, (int)wlen, nullptr, 0, nullptr, nullptr);
  604. if (u8ch != 0) {
  605. u8str.resize((size_t)u8ch);
  606. WideCharToMultiByte(CP_UTF8, 0, wdata, (int)wlen, &u8str[0], u8ch, nullptr, nullptr);
  607. }
  608. return u8str;
  609. }
  610. #endif
  611. } // namespace ysfx
  612. //------------------------------------------------------------------------------
  613. // WDL helpers
  614. // our replacement `atof` for WDL, which is unaffected by current locale
  615. extern "C" double ysfx_wdl_atof(const char *text)
  616. {
  617. return ysfx::dot_atof(text);
  618. }