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.

3618 lines
122KB

  1. /*
  2. * Carla Plugin Host
  3. * Copyright (C) 2011-2022 Filipe Coelho <falktx@falktx.com>
  4. *
  5. * This program is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU General Public License as
  7. * published by the Free Software Foundation; either version 2 of
  8. * the License, or any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * For a full copy of the GNU General Public License see the doc/GPL.txt file.
  16. */
  17. /* TODO:
  18. * - complete processRack(): carefully add to input, sorted events
  19. * - implement processPatchbay()
  20. * - implement oscSend_control_switch_plugins()
  21. * - something about the peaks?
  22. */
  23. #include "CarlaEngineClient.hpp"
  24. #include "CarlaEngineInit.hpp"
  25. #include "CarlaEngineInternal.hpp"
  26. #include "CarlaPlugin.hpp"
  27. #include "CarlaBackendUtils.hpp"
  28. #include "CarlaBinaryUtils.hpp"
  29. #include "CarlaEngineUtils.hpp"
  30. #include "CarlaMathUtils.hpp"
  31. #include "CarlaPipeUtils.hpp"
  32. #include "CarlaProcessUtils.hpp"
  33. #include "CarlaScopeUtils.hpp"
  34. #include "CarlaStateUtils.hpp"
  35. #include "CarlaMIDI.h"
  36. #include "jackbridge/JackBridge.hpp"
  37. #include "water/files/File.h"
  38. #include "water/streams/MemoryOutputStream.h"
  39. #include "water/xml/XmlDocument.h"
  40. #include "water/xml/XmlElement.h"
  41. #ifdef CARLA_OS_MAC
  42. # include "CarlaMacUtils.hpp"
  43. # if defined(CARLA_OS_64BIT) && defined(HAVE_LIBMAGIC) && ! defined(BUILD_BRIDGE_ALTERNATIVE_ARCH)
  44. # define ADAPT_FOR_APPLE_SILLICON
  45. # endif
  46. #endif
  47. #include <map>
  48. // FIXME Remove on 2.1 release
  49. #include "lv2/atom.h"
  50. using water::Array;
  51. using water::CharPointer_UTF8;
  52. using water::File;
  53. using water::MemoryOutputStream;
  54. using water::String;
  55. using water::StringArray;
  56. using water::XmlDocument;
  57. using water::XmlElement;
  58. // #define SFZ_FILES_USING_SFIZZ
  59. CARLA_BACKEND_START_NAMESPACE
  60. // -----------------------------------------------------------------------
  61. // Carla Engine
  62. CarlaEngine::CarlaEngine()
  63. : pData(new ProtectedData(this))
  64. {
  65. carla_debug("CarlaEngine::CarlaEngine()");
  66. }
  67. CarlaEngine::~CarlaEngine()
  68. {
  69. carla_debug("CarlaEngine::~CarlaEngine()");
  70. delete pData;
  71. }
  72. // -----------------------------------------------------------------------
  73. // Static calls
  74. uint CarlaEngine::getDriverCount()
  75. {
  76. carla_debug("CarlaEngine::getDriverCount()");
  77. using namespace EngineInit;
  78. uint count = 0;
  79. #ifdef HAVE_JACK
  80. if (jackbridge_is_ok())
  81. ++count;
  82. #endif
  83. #ifdef USING_JUCE_AUDIO_DEVICES
  84. count += getJuceApiCount();
  85. #endif
  86. #ifdef USING_RTAUDIO
  87. count += getRtAudioApiCount();
  88. #endif
  89. #ifdef HAVE_SDL
  90. ++count;
  91. #endif
  92. return count;
  93. }
  94. const char* CarlaEngine::getDriverName(const uint index)
  95. {
  96. carla_debug("CarlaEngine::getDriverName(%u)", index);
  97. using namespace EngineInit;
  98. uint index2 = index;
  99. #ifdef HAVE_JACK
  100. if (jackbridge_is_ok())
  101. {
  102. if (index2 == 0)
  103. return "JACK";
  104. --index2;
  105. }
  106. #endif
  107. #ifdef USING_JUCE_AUDIO_DEVICES
  108. if (const uint count = getJuceApiCount())
  109. {
  110. if (index2 < count)
  111. return getJuceApiName(index2);
  112. index2 -= count;
  113. }
  114. #endif
  115. #ifdef USING_RTAUDIO
  116. if (const uint count = getRtAudioApiCount())
  117. {
  118. if (index2 < count)
  119. return getRtAudioApiName(index2);
  120. index2 -= count;
  121. }
  122. #endif
  123. #ifdef HAVE_SDL
  124. if (index2 == 0)
  125. return "SDL";
  126. --index2;
  127. #endif
  128. carla_stderr("CarlaEngine::getDriverName(%u) - invalid index %u", index, index2);
  129. return nullptr;
  130. }
  131. const char* const* CarlaEngine::getDriverDeviceNames(const uint index)
  132. {
  133. carla_debug("CarlaEngine::getDriverDeviceNames(%u)", index);
  134. using namespace EngineInit;
  135. uint index2 = index;
  136. #ifdef HAVE_JACK
  137. if (jackbridge_is_ok())
  138. {
  139. if (index2 == 0)
  140. {
  141. static const char* ret[3] = { "Auto-Connect ON", "Auto-Connect OFF", nullptr };
  142. return ret;
  143. }
  144. --index2;
  145. }
  146. #endif
  147. #ifdef USING_JUCE_AUDIO_DEVICES
  148. if (const uint count = getJuceApiCount())
  149. {
  150. if (index2 < count)
  151. return getJuceApiDeviceNames(index2);
  152. index2 -= count;
  153. }
  154. #endif
  155. #ifdef USING_RTAUDIO
  156. if (const uint count = getRtAudioApiCount())
  157. {
  158. if (index2 < count)
  159. return getRtAudioApiDeviceNames(index2);
  160. index2 -= count;
  161. }
  162. #endif
  163. #ifdef HAVE_SDL
  164. if (index2 == 0)
  165. return getSDLDeviceNames();
  166. --index2;
  167. #endif
  168. carla_stderr("CarlaEngine::getDriverDeviceNames(%u) - invalid index %u", index, index2);
  169. return nullptr;
  170. }
  171. const EngineDriverDeviceInfo* CarlaEngine::getDriverDeviceInfo(const uint index, const char* const deviceName)
  172. {
  173. carla_debug("CarlaEngine::getDriverDeviceInfo(%u, \"%s\")", index, deviceName);
  174. using namespace EngineInit;
  175. uint index2 = index;
  176. #ifdef HAVE_JACK
  177. if (jackbridge_is_ok())
  178. {
  179. if (index2 == 0)
  180. {
  181. static EngineDriverDeviceInfo devInfo;
  182. devInfo.hints = ENGINE_DRIVER_DEVICE_VARIABLE_BUFFER_SIZE;
  183. devInfo.bufferSizes = nullptr;
  184. devInfo.sampleRates = nullptr;
  185. return &devInfo;
  186. }
  187. }
  188. --index2;
  189. #endif
  190. #ifdef USING_JUCE_AUDIO_DEVICES
  191. if (const uint count = getJuceApiCount())
  192. {
  193. if (index2 < count)
  194. return getJuceDeviceInfo(index2, deviceName);
  195. index2 -= count;
  196. }
  197. #endif
  198. #ifdef USING_RTAUDIO
  199. if (const uint count = getRtAudioApiCount())
  200. {
  201. if (index2 < count)
  202. return getRtAudioDeviceInfo(index2, deviceName);
  203. index2 -= count;
  204. }
  205. #endif
  206. #ifdef HAVE_SDL
  207. if (index2 == 0)
  208. {
  209. static uint32_t sdlBufferSizes[] = { 512, 1024, 2048, 4096, 8192, 0 };
  210. static double sdlSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 0.0 };
  211. static EngineDriverDeviceInfo devInfo;
  212. devInfo.hints = 0x0;
  213. devInfo.bufferSizes = sdlBufferSizes;
  214. devInfo.sampleRates = sdlSampleRates;
  215. return &devInfo;
  216. }
  217. --index2;
  218. #endif
  219. carla_stderr("CarlaEngine::getDriverDeviceInfo(%u, \"%s\") - invalid index %u", index, index2, deviceName);
  220. return nullptr;
  221. }
  222. bool CarlaEngine::showDriverDeviceControlPanel(const uint index, const char* const deviceName)
  223. {
  224. carla_debug("CarlaEngine::showDriverDeviceControlPanel(%u, \"%s\")", index, deviceName);
  225. using namespace EngineInit;
  226. uint index2 = index;
  227. #ifdef HAVE_JACK
  228. if (jackbridge_is_ok())
  229. {
  230. if (index2 == 0)
  231. return false;
  232. --index2;
  233. }
  234. #endif
  235. #ifdef USING_JUCE_AUDIO_DEVICES
  236. if (const uint count = getJuceApiCount())
  237. {
  238. if (index2 < count)
  239. return showJuceDeviceControlPanel(index2, deviceName);
  240. index2 -= count;
  241. }
  242. #endif
  243. #ifdef USING_RTAUDIO
  244. if (const uint count = getRtAudioApiCount())
  245. {
  246. if (index2 < count)
  247. return false;
  248. index2 -= count;
  249. }
  250. #endif
  251. #ifdef HAVE_SDL
  252. if (index2 == 0)
  253. return false;
  254. --index2;
  255. #endif
  256. carla_stderr("CarlaEngine::showDriverDeviceControlPanel(%u, \"%s\") - invalid index %u", index, index2, deviceName);
  257. return false;
  258. }
  259. CarlaEngine* CarlaEngine::newDriverByName(const char* const driverName)
  260. {
  261. CARLA_SAFE_ASSERT_RETURN(driverName != nullptr && driverName[0] != '\0', nullptr);
  262. carla_debug("CarlaEngine::newDriverByName(\"%s\")", driverName);
  263. using namespace EngineInit;
  264. #ifdef HAVE_JACK
  265. if (std::strcmp(driverName, "JACK") == 0)
  266. return newJack();
  267. #endif
  268. #if !(defined(BUILD_BRIDGE_ALTERNATIVE_ARCH) || defined(CARLA_OS_WASM))
  269. if (std::strcmp(driverName, "Dummy") == 0)
  270. return newDummy();
  271. #endif
  272. #ifdef USING_JUCE_AUDIO_DEVICES
  273. // -------------------------------------------------------------------
  274. // linux
  275. if (std::strcmp(driverName, "ALSA") == 0)
  276. return newJuce(AUDIO_API_ALSA);
  277. // -------------------------------------------------------------------
  278. // macos
  279. if (std::strcmp(driverName, "CoreAudio") == 0)
  280. return newJuce(AUDIO_API_COREAUDIO);
  281. // -------------------------------------------------------------------
  282. // windows
  283. if (std::strcmp(driverName, "ASIO") == 0)
  284. return newJuce(AUDIO_API_ASIO);
  285. if (std::strcmp(driverName, "DirectSound") == 0)
  286. return newJuce(AUDIO_API_DIRECTSOUND);
  287. if (std::strcmp(driverName, "WASAPI") == 0 || std::strcmp(driverName, "Windows Audio") == 0)
  288. return newJuce(AUDIO_API_WASAPI);
  289. #endif
  290. #ifdef USING_RTAUDIO
  291. // -------------------------------------------------------------------
  292. // common
  293. if (std::strncmp(driverName, "JACK ", 5) == 0)
  294. return newRtAudio(AUDIO_API_JACK);
  295. if (std::strcmp(driverName, "OSS") == 0)
  296. return newRtAudio(AUDIO_API_OSS);
  297. // -------------------------------------------------------------------
  298. // linux
  299. if (std::strcmp(driverName, "ALSA") == 0)
  300. return newRtAudio(AUDIO_API_ALSA);
  301. if (std::strcmp(driverName, "PulseAudio") == 0)
  302. return newRtAudio(AUDIO_API_PULSEAUDIO);
  303. // -------------------------------------------------------------------
  304. // macos
  305. if (std::strcmp(driverName, "CoreAudio") == 0)
  306. return newRtAudio(AUDIO_API_COREAUDIO);
  307. // -------------------------------------------------------------------
  308. // windows
  309. if (std::strcmp(driverName, "ASIO") == 0)
  310. return newRtAudio(AUDIO_API_ASIO);
  311. if (std::strcmp(driverName, "DirectSound") == 0)
  312. return newRtAudio(AUDIO_API_DIRECTSOUND);
  313. if (std::strcmp(driverName, "WASAPI") == 0)
  314. return newRtAudio(AUDIO_API_WASAPI);
  315. #endif
  316. #ifdef HAVE_SDL
  317. if (std::strcmp(driverName, "SDL") == 0)
  318. return newSDL();
  319. #endif
  320. carla_stderr("CarlaEngine::newDriverByName(\"%s\") - invalid driver name", driverName);
  321. return nullptr;
  322. }
  323. // -----------------------------------------------------------------------
  324. // Constant values
  325. uint CarlaEngine::getMaxClientNameSize() const noexcept
  326. {
  327. return STR_MAX/2;
  328. }
  329. uint CarlaEngine::getMaxPortNameSize() const noexcept
  330. {
  331. return STR_MAX;
  332. }
  333. uint CarlaEngine::getCurrentPluginCount() const noexcept
  334. {
  335. return pData->curPluginCount;
  336. }
  337. uint CarlaEngine::getMaxPluginNumber() const noexcept
  338. {
  339. return pData->maxPluginNumber;
  340. }
  341. // -----------------------------------------------------------------------
  342. // Virtual, per-engine type calls
  343. bool CarlaEngine::close()
  344. {
  345. carla_debug("CarlaEngine::close()");
  346. if (pData->curPluginCount != 0)
  347. {
  348. pData->aboutToClose = true;
  349. removeAllPlugins();
  350. }
  351. pData->close();
  352. callback(true, true, ENGINE_CALLBACK_ENGINE_STOPPED, 0, 0, 0, 0, 0.0f, nullptr);
  353. return true;
  354. }
  355. bool CarlaEngine::usesConstantBufferSize() const noexcept
  356. {
  357. return true;
  358. }
  359. void CarlaEngine::idle() noexcept
  360. {
  361. CARLA_SAFE_ASSERT_RETURN(pData->nextAction.opcode == kEnginePostActionNull,);
  362. CARLA_SAFE_ASSERT_RETURN(pData->nextPluginId == pData->maxPluginNumber,);
  363. CARLA_SAFE_ASSERT_RETURN(getType() != kEngineTypePlugin,);
  364. const bool engineNotRunning = !isRunning();
  365. for (uint i=0; i < pData->curPluginCount; ++i)
  366. {
  367. if (const CarlaPluginPtr plugin = pData->plugins[i].plugin)
  368. {
  369. if (plugin->isEnabled())
  370. {
  371. const uint hints = plugin->getHints();
  372. if (engineNotRunning)
  373. {
  374. try {
  375. plugin->idle();
  376. } CARLA_SAFE_EXCEPTION_CONTINUE("Plugin idle");
  377. if (hints & PLUGIN_HAS_CUSTOM_UI)
  378. {
  379. try {
  380. plugin->uiIdle();
  381. } CARLA_SAFE_EXCEPTION_CONTINUE("Plugin uiIdle");
  382. }
  383. }
  384. else if ((hints & PLUGIN_HAS_CUSTOM_UI) != 0 && (hints & PLUGIN_NEEDS_UI_MAIN_THREAD) != 0)
  385. {
  386. try {
  387. plugin->uiIdle();
  388. } CARLA_SAFE_EXCEPTION_CONTINUE("Plugin uiIdle");
  389. }
  390. }
  391. }
  392. }
  393. #if defined(HAVE_LIBLO) && !defined(BUILD_BRIDGE)
  394. pData->osc.idle();
  395. #endif
  396. pData->deletePluginsAsNeeded();
  397. }
  398. CarlaEngineClient* CarlaEngine::addClient(CarlaPluginPtr plugin)
  399. {
  400. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  401. return new CarlaEngineClientForStandalone(*this, pData->graph, plugin);
  402. #else
  403. return new CarlaEngineClientForBridge(*this);
  404. // unused
  405. (void)plugin;
  406. #endif
  407. }
  408. float CarlaEngine::getDSPLoad() const noexcept
  409. {
  410. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  411. return pData->dspLoad;
  412. #else
  413. return 0.0f;
  414. #endif
  415. }
  416. uint32_t CarlaEngine::getTotalXruns() const noexcept
  417. {
  418. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  419. return pData->xruns;
  420. #else
  421. return 0;
  422. #endif
  423. }
  424. void CarlaEngine::clearXruns() const noexcept
  425. {
  426. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  427. pData->xruns = 0;
  428. #endif
  429. }
  430. bool CarlaEngine::showDeviceControlPanel() const noexcept
  431. {
  432. return false;
  433. }
  434. bool CarlaEngine::setBufferSizeAndSampleRate(const uint, const double)
  435. {
  436. return false;
  437. }
  438. // -----------------------------------------------------------------------
  439. // Plugin management
  440. bool CarlaEngine::addPlugin(const BinaryType btype,
  441. const PluginType ptype,
  442. const char* const filename,
  443. const char* const name,
  444. const char* const label,
  445. const int64_t uniqueId,
  446. const void* const extra,
  447. const uint options)
  448. {
  449. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  450. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  451. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  452. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextPluginId <= pData->maxPluginNumber, "Invalid engine internal data");
  453. #endif
  454. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  455. CARLA_SAFE_ASSERT_RETURN_ERR(btype != BINARY_NONE, "Invalid plugin binary mode");
  456. CARLA_SAFE_ASSERT_RETURN_ERR(ptype != PLUGIN_NONE, "Invalid plugin type");
  457. CARLA_SAFE_ASSERT_RETURN_ERR((filename != nullptr && filename[0] != '\0') || (label != nullptr && label[0] != '\0'), "Invalid plugin filename and label");
  458. carla_debug("CarlaEngine::addPlugin(%i:%s, %i:%s, \"%s\", \"%s\", \"%s\", " P_INT64 ", %p, %u)",
  459. btype, BinaryType2Str(btype), ptype, PluginType2Str(ptype), filename, name, label, uniqueId, extra, options);
  460. #ifndef CARLA_OS_WIN
  461. if (ptype != PLUGIN_JACK && ptype != PLUGIN_LV2 && filename != nullptr && filename[0] != '\0') {
  462. CARLA_SAFE_ASSERT_RETURN_ERR(filename[0] == CARLA_OS_SEP || filename[0] == '.' || filename[0] == '~', "Invalid plugin filename");
  463. }
  464. #endif
  465. uint id;
  466. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  467. CarlaPluginPtr oldPlugin;
  468. if (pData->nextPluginId < pData->curPluginCount)
  469. {
  470. id = pData->nextPluginId;
  471. pData->nextPluginId = pData->maxPluginNumber;
  472. oldPlugin = pData->plugins[id].plugin;
  473. CARLA_SAFE_ASSERT_RETURN_ERR(oldPlugin.get() != nullptr, "Invalid replace plugin Id");
  474. }
  475. else
  476. #endif
  477. {
  478. id = pData->curPluginCount;
  479. if (id == pData->maxPluginNumber)
  480. {
  481. setLastError("Maximum number of plugins reached");
  482. return false;
  483. }
  484. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  485. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins[id].plugin.get() == nullptr, "Invalid engine internal data");
  486. #endif
  487. }
  488. CarlaPlugin::Initializer initializer = {
  489. this,
  490. id,
  491. filename,
  492. name,
  493. label,
  494. uniqueId,
  495. options
  496. };
  497. CarlaPluginPtr plugin;
  498. CarlaString bridgeBinary(pData->options.binaryDir);
  499. if (bridgeBinary.isNotEmpty())
  500. {
  501. #ifndef CARLA_OS_WIN
  502. if (btype == BINARY_NATIVE)
  503. {
  504. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-native";
  505. }
  506. else
  507. #endif
  508. {
  509. switch (btype)
  510. {
  511. case BINARY_POSIX32:
  512. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-posix32";
  513. break;
  514. case BINARY_POSIX64:
  515. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-posix64";
  516. break;
  517. case BINARY_WIN32:
  518. #if defined(CARLA_OS_WIN) && !defined(CARLA_OS_64BIT)
  519. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-native.exe";
  520. #else
  521. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-win32.exe";
  522. #endif
  523. break;
  524. case BINARY_WIN64:
  525. #if defined(CARLA_OS_WIN) && defined(CARLA_OS_64BIT)
  526. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-native.exe";
  527. #else
  528. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-win64.exe";
  529. #endif
  530. break;
  531. default:
  532. bridgeBinary.clear();
  533. break;
  534. }
  535. }
  536. if (! File(bridgeBinary.buffer()).existsAsFile())
  537. bridgeBinary.clear();
  538. }
  539. const bool canBeBridged = ptype != PLUGIN_INTERNAL
  540. && ptype != PLUGIN_DLS
  541. && ptype != PLUGIN_GIG
  542. && ptype != PLUGIN_SF2
  543. && ptype != PLUGIN_SFZ
  544. && ptype != PLUGIN_JSFX
  545. && ptype != PLUGIN_JACK;
  546. // Prefer bridges for some specific plugins
  547. bool preferBridges = pData->options.preferPluginBridges;
  548. const char* needsArchBridge = nullptr;
  549. #ifdef CARLA_OS_MAC
  550. // Plugin might be in quarentine due to Apple stupid notarization rules, let's remove that if possible
  551. if (canBeBridged && ptype != PLUGIN_LV2 && ptype != PLUGIN_AU)
  552. removeFileFromQuarantine(filename);
  553. #endif
  554. #ifndef BUILD_BRIDGE
  555. if (canBeBridged && ! preferBridges)
  556. {
  557. # if 0
  558. if (ptype == PLUGIN_LV2 && label != nullptr)
  559. {
  560. if (std::strncmp(label, "http://calf.sourceforge.net/plugins/", 36) == 0 ||
  561. std::strcmp(label, "http://factorial.hu/plugins/lv2/ir") == 0 ||
  562. std::strstr(label, "v1.sourceforge.net/lv2") != nullptr)
  563. {
  564. preferBridges = true;
  565. }
  566. }
  567. # endif
  568. # ifdef ADAPT_FOR_APPLE_SILLICON
  569. // see if this binary needs bridging
  570. if (ptype == PLUGIN_VST2 || ptype == PLUGIN_VST3)
  571. {
  572. if (const char* const vst2Binary = findBinaryInBundle(filename))
  573. {
  574. const CarlaMagic magic;
  575. if (const char* const output = magic.getFileDescription(vst2Binary))
  576. {
  577. carla_stdout("VST binary magic output is '%s'", output);
  578. # ifdef __aarch64__
  579. if (std::strstr(output, "arm64") == nullptr && std::strstr(output, "x86_64") != nullptr)
  580. needsArchBridge = "x86_64";
  581. # else
  582. if (std::strstr(output, "x86_64") == nullptr && std::strstr(output, "arm64") != nullptr)
  583. needsArchBridge = "arm64";
  584. # endif
  585. }
  586. else
  587. {
  588. carla_stdout("VST binary magic output is null");
  589. }
  590. }
  591. else
  592. {
  593. carla_stdout("Search for binary in VST bundle failed");
  594. }
  595. }
  596. # endif
  597. }
  598. #endif // ! BUILD_BRIDGE
  599. #ifndef CARLA_OS_WASM
  600. if (canBeBridged && (needsArchBridge || btype != BINARY_NATIVE || (preferBridges && bridgeBinary.isNotEmpty())))
  601. {
  602. if (bridgeBinary.isNotEmpty())
  603. {
  604. plugin = CarlaPlugin::newBridge(initializer, btype, ptype, needsArchBridge, bridgeBinary);
  605. }
  606. else
  607. {
  608. setLastError("This Carla build cannot handle this binary");
  609. return false;
  610. }
  611. }
  612. else
  613. #endif
  614. {
  615. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  616. bool use16Outs;
  617. #endif
  618. setLastError("Invalid or unsupported plugin type");
  619. // Some stupid plugins mess up with global signals, err!!
  620. const CarlaSignalRestorer csr;
  621. switch (ptype)
  622. {
  623. case PLUGIN_NONE:
  624. case PLUGIN_TYPE_COUNT:
  625. break;
  626. case PLUGIN_LADSPA:
  627. plugin = CarlaPlugin::newLADSPA(initializer, (const LADSPA_RDF_Descriptor*)extra);
  628. break;
  629. case PLUGIN_DSSI:
  630. plugin = CarlaPlugin::newDSSI(initializer);
  631. break;
  632. case PLUGIN_LV2:
  633. plugin = CarlaPlugin::newLV2(initializer);
  634. break;
  635. case PLUGIN_VST2:
  636. plugin = CarlaPlugin::newVST2(initializer);
  637. break;
  638. case PLUGIN_VST3:
  639. plugin = CarlaPlugin::newVST3(initializer);
  640. break;
  641. case PLUGIN_AU:
  642. plugin = CarlaPlugin::newAU(initializer);
  643. break;
  644. case PLUGIN_CLAP:
  645. plugin = CarlaPlugin::newCLAP(initializer);
  646. break;
  647. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  648. case PLUGIN_INTERNAL:
  649. plugin = CarlaPlugin::newNative(initializer);
  650. break;
  651. case PLUGIN_DLS:
  652. case PLUGIN_GIG:
  653. case PLUGIN_SF2:
  654. use16Outs = (extra != nullptr && std::strcmp((const char*)extra, "true") == 0);
  655. plugin = CarlaPlugin::newFluidSynth(initializer, ptype, use16Outs);
  656. break;
  657. case PLUGIN_SFZ:
  658. # ifdef SFZ_FILES_USING_SFIZZ
  659. {
  660. CarlaPlugin::Initializer sfizzInitializer = {
  661. this,
  662. id,
  663. name,
  664. "",
  665. "http://sfztools.github.io/sfizz",
  666. 0,
  667. options
  668. };
  669. plugin = CarlaPlugin::newLV2(sfizzInitializer);
  670. }
  671. # else
  672. plugin = CarlaPlugin::newSFZero(initializer);
  673. # endif
  674. break;
  675. case PLUGIN_JSFX:
  676. plugin = CarlaPlugin::newJSFX(initializer);
  677. break;
  678. case PLUGIN_JACK:
  679. # ifdef HAVE_JACK
  680. plugin = CarlaPlugin::newJackApp(initializer);
  681. # else
  682. setLastError("JACK plugin target is not available");
  683. # endif
  684. break;
  685. #else
  686. case PLUGIN_INTERNAL:
  687. case PLUGIN_DLS:
  688. case PLUGIN_GIG:
  689. case PLUGIN_SF2:
  690. case PLUGIN_SFZ:
  691. case PLUGIN_JACK:
  692. case PLUGIN_JSFX:
  693. setLastError("Plugin bridges cannot handle this binary");
  694. break;
  695. #endif
  696. }
  697. }
  698. if (plugin.get() == nullptr)
  699. return false;
  700. plugin->reload();
  701. #ifdef SFZ_FILES_USING_SFIZZ
  702. if (ptype == PLUGIN_SFZ && plugin->getType() == PLUGIN_LV2)
  703. {
  704. plugin->setCustomData(LV2_ATOM__Path,
  705. "http://sfztools.github.io/sfizz:sfzfile",
  706. filename,
  707. false);
  708. plugin->restoreLV2State(true);
  709. }
  710. #endif
  711. bool canRun = true;
  712. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  713. {
  714. /**/ if (plugin->getMidiInCount() > 1 || plugin->getMidiOutCount() > 1)
  715. {
  716. setLastError("Carla's patchbay mode cannot work with plugins that have multiple MIDI ports, sorry!");
  717. canRun = false;
  718. }
  719. }
  720. if (! canRun)
  721. {
  722. return false;
  723. }
  724. EnginePluginData& pluginData(pData->plugins[id]);
  725. pluginData.plugin = plugin;
  726. carla_zeroFloats(pluginData.peaks, 4);
  727. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  728. if (oldPlugin.get() != nullptr)
  729. {
  730. CARLA_SAFE_ASSERT(! pData->loadingProject);
  731. const ScopedRunnerStopper srs(this);
  732. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  733. pData->graph.replacePlugin(oldPlugin, plugin);
  734. const bool wasActive = oldPlugin->getInternalParameterValue(PARAMETER_ACTIVE) >= 0.5f;
  735. const float oldDryWet = oldPlugin->getInternalParameterValue(PARAMETER_DRYWET);
  736. const float oldVolume = oldPlugin->getInternalParameterValue(PARAMETER_VOLUME);
  737. oldPlugin->prepareForDeletion();
  738. {
  739. const CarlaMutexLocker cml(pData->pluginsToDeleteMutex);
  740. pData->pluginsToDelete.push_back(oldPlugin);
  741. }
  742. if (plugin->getHints() & PLUGIN_CAN_DRYWET)
  743. plugin->setDryWet(oldDryWet, true, true);
  744. if (plugin->getHints() & PLUGIN_CAN_VOLUME)
  745. plugin->setVolume(oldVolume, true, true);
  746. plugin->setActive(wasActive, true, true);
  747. plugin->setEnabled(true);
  748. callback(true, true, ENGINE_CALLBACK_RELOAD_ALL, id, 0, 0, 0, 0.0f, nullptr);
  749. }
  750. else if (! pData->loadingProject)
  751. #endif
  752. {
  753. plugin->setEnabled(true);
  754. ++pData->curPluginCount;
  755. callback(true, true, ENGINE_CALLBACK_PLUGIN_ADDED, id, plugin->getType(), 0, 0, 0.0f, plugin->getName());
  756. if (getType() != kEngineTypeBridge)
  757. plugin->setActive(true, true, true);
  758. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  759. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  760. pData->graph.addPlugin(plugin);
  761. #endif
  762. }
  763. return true;
  764. }
  765. bool CarlaEngine::addPlugin(const PluginType ptype,
  766. const char* const filename,
  767. const char* const name,
  768. const char* const label,
  769. const int64_t uniqueId,
  770. const void* const extra)
  771. {
  772. return addPlugin(BINARY_NATIVE, ptype, filename, name, label, uniqueId, extra, PLUGIN_OPTIONS_NULL);
  773. }
  774. bool CarlaEngine::removePlugin(const uint id)
  775. {
  776. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  777. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  778. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  779. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount != 0, "Invalid engine internal data");
  780. #else
  781. CARLA_SAFE_ASSERT_RETURN_ERR(id == 0, "Invalid engine internal data");
  782. #endif
  783. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  784. CARLA_SAFE_ASSERT_RETURN_ERR(id < pData->curPluginCount, "Invalid plugin Id");
  785. carla_debug("CarlaEngine::removePlugin(%i)", id);
  786. const CarlaPluginPtr plugin = pData->plugins[id].plugin;
  787. CARLA_SAFE_ASSERT_RETURN_ERR(plugin.get() != nullptr, "Could not find plugin to remove");
  788. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  789. const ScopedRunnerStopper srs(this);
  790. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  791. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  792. pData->graph.removePlugin(plugin);
  793. const ScopedActionLock sal(this, kEnginePostActionRemovePlugin, id, 0);
  794. /*
  795. for (uint i=id; i < pData->curPluginCount; ++i)
  796. {
  797. CarlaPlugin* const plugin2(pData->plugins[i].plugin);
  798. CARLA_SAFE_ASSERT_BREAK(plugin2 != nullptr);
  799. plugin2->updateOscURL();
  800. }
  801. */
  802. #else
  803. pData->curPluginCount = 0;
  804. pData->plugins[0].plugin.reset();
  805. carla_zeroStruct(pData->plugins[0].peaks);
  806. #endif
  807. plugin->prepareForDeletion();
  808. {
  809. const CarlaMutexLocker cml(pData->pluginsToDeleteMutex);
  810. pData->pluginsToDelete.push_back(plugin);
  811. }
  812. callback(true, true, ENGINE_CALLBACK_PLUGIN_REMOVED, id, 0, 0, 0, 0.0f, nullptr);
  813. return true;
  814. }
  815. bool CarlaEngine::removeAllPlugins()
  816. {
  817. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  818. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  819. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  820. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextPluginId == pData->maxPluginNumber, "Invalid engine internal data");
  821. #endif
  822. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  823. carla_debug("CarlaEngine::removeAllPlugins()");
  824. if (pData->curPluginCount == 0)
  825. return true;
  826. const ScopedRunnerStopper srs(this);
  827. const uint curPluginCount = pData->curPluginCount;
  828. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  829. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  830. pData->graph.removeAllPlugins(pData->aboutToClose);
  831. #endif
  832. const ScopedActionLock sal(this, kEnginePostActionZeroCount, 0, 0);
  833. callback(true, false, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  834. for (uint i=0; i < curPluginCount; ++i)
  835. {
  836. const uint id = curPluginCount - i - 1;
  837. EnginePluginData& pluginData(pData->plugins[id]);
  838. pluginData.plugin->prepareForDeletion();
  839. {
  840. const CarlaMutexLocker cml(pData->pluginsToDeleteMutex);
  841. pData->pluginsToDelete.push_back(pluginData.plugin);
  842. }
  843. pluginData.plugin.reset();
  844. carla_zeroStruct(pluginData.peaks);
  845. callback(true, true, ENGINE_CALLBACK_PLUGIN_REMOVED, id, 0, 0, 0, 0.0f, nullptr);
  846. callback(true, false, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  847. }
  848. return true;
  849. }
  850. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  851. bool CarlaEngine::renamePlugin(const uint id, const char* const newName)
  852. {
  853. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  854. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  855. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount != 0, "Invalid engine internal data");
  856. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  857. CARLA_SAFE_ASSERT_RETURN_ERR(id < pData->curPluginCount, "Invalid plugin Id");
  858. CARLA_SAFE_ASSERT_RETURN_ERR(newName != nullptr && newName[0] != '\0', "Invalid plugin name");
  859. carla_debug("CarlaEngine::renamePlugin(%i, \"%s\")", id, newName);
  860. const CarlaPluginPtr plugin = pData->plugins[id].plugin;
  861. CARLA_SAFE_ASSERT_RETURN_ERR(plugin.get() != nullptr, "Could not find plugin to rename");
  862. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  863. const char* const uniqueName(getUniquePluginName(newName));
  864. CARLA_SAFE_ASSERT_RETURN_ERR(uniqueName != nullptr, "Unable to get new unique plugin name");
  865. plugin->setName(uniqueName);
  866. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  867. pData->graph.renamePlugin(plugin, uniqueName);
  868. callback(true, true, ENGINE_CALLBACK_PLUGIN_RENAMED, id, 0, 0, 0, 0.0f, uniqueName);
  869. delete[] uniqueName;
  870. return true;
  871. }
  872. bool CarlaEngine::clonePlugin(const uint id)
  873. {
  874. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  875. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  876. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount != 0, "Invalid engine internal data");
  877. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  878. CARLA_SAFE_ASSERT_RETURN_ERR(id < pData->curPluginCount, "Invalid plugin Id");
  879. carla_debug("CarlaEngine::clonePlugin(%i)", id);
  880. const CarlaPluginPtr plugin = pData->plugins[id].plugin;
  881. CARLA_SAFE_ASSERT_RETURN_ERR(plugin.get() != nullptr, "Could not find plugin to clone");
  882. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  883. char label[STR_MAX+1];
  884. carla_zeroChars(label, STR_MAX+1);
  885. if (! plugin->getLabel(label))
  886. label[0] = '\0';
  887. const uint pluginCountBefore(pData->curPluginCount);
  888. if (! addPlugin(plugin->getBinaryType(), plugin->getType(),
  889. plugin->getFilename(), plugin->getName(), label, plugin->getUniqueId(),
  890. plugin->getExtraStuff(), plugin->getOptionsEnabled()))
  891. return false;
  892. CARLA_SAFE_ASSERT_RETURN_ERR(pluginCountBefore+1 == pData->curPluginCount, "No new plugin found");
  893. if (const CarlaPluginPtr newPlugin = pData->plugins[pluginCountBefore].plugin)
  894. {
  895. if (newPlugin->getType() == PLUGIN_LV2)
  896. newPlugin->cloneLV2Files(*plugin);
  897. newPlugin->loadStateSave(plugin->getStateSave(true));
  898. }
  899. return true;
  900. }
  901. bool CarlaEngine::replacePlugin(const uint id) noexcept
  902. {
  903. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  904. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  905. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount != 0, "Invalid engine internal data");
  906. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  907. carla_debug("CarlaEngine::replacePlugin(%i)", id);
  908. // might use this to reset
  909. if (id == pData->maxPluginNumber)
  910. {
  911. pData->nextPluginId = pData->maxPluginNumber;
  912. return true;
  913. }
  914. CARLA_SAFE_ASSERT_RETURN_ERR(id < pData->curPluginCount, "Invalid plugin Id");
  915. const CarlaPluginPtr plugin = pData->plugins[id].plugin;
  916. CARLA_SAFE_ASSERT_RETURN_ERR(plugin.get() != nullptr, "Could not find plugin to replace");
  917. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  918. pData->nextPluginId = id;
  919. return true;
  920. }
  921. bool CarlaEngine::switchPlugins(const uint idA, const uint idB) noexcept
  922. {
  923. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  924. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  925. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount >= 2, "Invalid engine internal data");
  926. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  927. CARLA_SAFE_ASSERT_RETURN_ERR(idA != idB, "Invalid operation, cannot switch plugin with itself");
  928. CARLA_SAFE_ASSERT_RETURN_ERR(idA < pData->curPluginCount, "Invalid plugin Id");
  929. CARLA_SAFE_ASSERT_RETURN_ERR(idB < pData->curPluginCount, "Invalid plugin Id");
  930. carla_debug("CarlaEngine::switchPlugins(%i)", idA, idB);
  931. const CarlaPluginPtr pluginA = pData->plugins[idA].plugin;
  932. const CarlaPluginPtr pluginB = pData->plugins[idB].plugin;
  933. CARLA_SAFE_ASSERT_RETURN_ERR(pluginA.get() != nullptr, "Could not find plugin to switch");
  934. CARLA_SAFE_ASSERT_RETURN_ERR(pluginB.get() != nullptr, "Could not find plugin to switch");
  935. CARLA_SAFE_ASSERT_RETURN_ERR(pluginA->getId() == idA, "Invalid engine internal data");
  936. CARLA_SAFE_ASSERT_RETURN_ERR(pluginB->getId() == idB, "Invalid engine internal data");
  937. const ScopedRunnerStopper srs(this);
  938. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  939. pData->graph.switchPlugins(pluginA, pluginB);
  940. const ScopedActionLock sal(this, kEnginePostActionSwitchPlugins, idA, idB);
  941. // TODO
  942. /*
  943. pluginA->updateOscURL();
  944. pluginB->updateOscURL();
  945. if (isOscControlRegistered())
  946. oscSend_control_switch_plugins(idA, idB);
  947. */
  948. return true;
  949. }
  950. #endif
  951. void CarlaEngine::touchPluginParameter(const uint, const uint32_t, const bool) noexcept
  952. {
  953. }
  954. CarlaPluginPtr CarlaEngine::getPlugin(const uint id) const noexcept
  955. {
  956. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  957. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->plugins != nullptr, "Invalid engine internal data");
  958. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->curPluginCount != 0, "Invalid engine internal data");
  959. #endif
  960. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  961. CARLA_SAFE_ASSERT_RETURN_ERRN(id < pData->curPluginCount, "Invalid plugin Id");
  962. return pData->plugins[id].plugin;
  963. }
  964. CarlaPluginPtr CarlaEngine::getPluginUnchecked(const uint id) const noexcept
  965. {
  966. return pData->plugins[id].plugin;
  967. }
  968. const char* CarlaEngine::getUniquePluginName(const char* const name) const
  969. {
  970. CARLA_SAFE_ASSERT_RETURN(pData->nextAction.opcode == kEnginePostActionNull, nullptr);
  971. CARLA_SAFE_ASSERT_RETURN(name != nullptr && name[0] != '\0', nullptr);
  972. carla_debug("CarlaEngine::getUniquePluginName(\"%s\")", name);
  973. CarlaString sname;
  974. sname = name;
  975. if (sname.isEmpty())
  976. {
  977. sname = "(No name)";
  978. return sname.dup();
  979. }
  980. const std::size_t maxNameSize(carla_minConstrained<uint>(getMaxClientNameSize(), 0xff, 6U) - 6); // 6 = strlen(" (10)") + 1
  981. if (maxNameSize == 0 || ! isRunning())
  982. return sname.dup();
  983. sname.truncate(maxNameSize);
  984. sname.replace(':', '.'); // ':' is used in JACK1 to split client/port names
  985. sname.replace('/', '.'); // '/' is used by us for client name prefix
  986. for (uint i=0; i < pData->curPluginCount; ++i)
  987. {
  988. const CarlaPluginPtr plugin = pData->plugins[i].plugin;
  989. CARLA_SAFE_ASSERT_BREAK(plugin.use_count() > 0);
  990. // Check if unique name doesn't exist
  991. if (const char* const pluginName = plugin->getName())
  992. {
  993. if (sname != pluginName)
  994. continue;
  995. }
  996. // Check if string has already been modified
  997. {
  998. const std::size_t len(sname.length());
  999. // 1 digit, ex: " (2)"
  1000. if (len > 4 && sname[len-4] == ' ' && sname[len-3] == '(' && sname.isDigit(len-2) && sname[len-1] == ')')
  1001. {
  1002. const int number = sname[len-2] - '0';
  1003. if (number == 9)
  1004. {
  1005. // next number is 10, 2 digits
  1006. sname.truncate(len-4);
  1007. sname += " (10)";
  1008. //sname.replace(" (9)", " (10)");
  1009. }
  1010. else
  1011. sname[len-2] = char('0' + number + 1);
  1012. continue;
  1013. }
  1014. // 2 digits, ex: " (11)"
  1015. if (len > 5 && sname[len-5] == ' ' && sname[len-4] == '(' && sname.isDigit(len-3) && sname.isDigit(len-2) && sname[len-1] == ')')
  1016. {
  1017. char n2 = sname[len-2];
  1018. char n3 = sname[len-3];
  1019. if (n2 == '9')
  1020. {
  1021. n2 = '0';
  1022. n3 = static_cast<char>(n3 + 1);
  1023. }
  1024. else
  1025. n2 = static_cast<char>(n2 + 1);
  1026. sname[len-2] = n2;
  1027. sname[len-3] = n3;
  1028. continue;
  1029. }
  1030. }
  1031. // Modify string if not
  1032. sname += " (2)";
  1033. }
  1034. return sname.dup();
  1035. }
  1036. // -----------------------------------------------------------------------
  1037. // Project management
  1038. bool CarlaEngine::loadFile(const char* const filename)
  1039. {
  1040. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  1041. CARLA_SAFE_ASSERT_RETURN_ERR(filename != nullptr && filename[0] != '\0', "Invalid filename");
  1042. carla_debug("CarlaEngine::loadFile(\"%s\")", filename);
  1043. const String jfilename = String(CharPointer_UTF8(filename));
  1044. File file(jfilename);
  1045. CARLA_SAFE_ASSERT_RETURN_ERR(file.exists(), "Requested file does not exist or is not a readable");
  1046. CarlaString baseName(file.getFileNameWithoutExtension().toRawUTF8());
  1047. CarlaString extension(file.getFileExtension().replace(".","").toLowerCase().toRawUTF8());
  1048. const uint curPluginId(pData->nextPluginId < pData->curPluginCount ? pData->nextPluginId : pData->curPluginCount);
  1049. // -------------------------------------------------------------------
  1050. // NOTE: please keep in sync with carla_get_supported_file_extensions!!
  1051. if (extension == "carxp" || extension == "carxs")
  1052. return loadProject(filename, false);
  1053. // -------------------------------------------------------------------
  1054. if (extension == "dls")
  1055. return addPlugin(PLUGIN_DLS, filename, baseName, baseName, 0, nullptr);
  1056. if (extension == "gig")
  1057. return addPlugin(PLUGIN_GIG, filename, baseName, baseName, 0, nullptr);
  1058. if (extension == "sf2" || extension == "sf3")
  1059. return addPlugin(PLUGIN_SF2, filename, baseName, baseName, 0, nullptr);
  1060. if (extension == "sfz")
  1061. return addPlugin(PLUGIN_SFZ, filename, baseName, baseName, 0, nullptr);
  1062. if (extension == "jsfx")
  1063. return addPlugin(PLUGIN_JSFX, filename, baseName, baseName, 0, nullptr);
  1064. // -------------------------------------------------------------------
  1065. if (
  1066. extension == "mp3" ||
  1067. #ifdef HAVE_SNDFILE
  1068. extension == "aif" ||
  1069. extension == "aifc" ||
  1070. extension == "aiff" ||
  1071. extension == "au" ||
  1072. extension == "bwf" ||
  1073. extension == "flac" ||
  1074. extension == "htk" ||
  1075. extension == "iff" ||
  1076. extension == "mat4" ||
  1077. extension == "mat5" ||
  1078. extension == "oga" ||
  1079. extension == "ogg" ||
  1080. extension == "opus" ||
  1081. extension == "paf" ||
  1082. extension == "pvf" ||
  1083. extension == "pvf5" ||
  1084. extension == "sd2" ||
  1085. extension == "sf" ||
  1086. extension == "snd" ||
  1087. extension == "svx" ||
  1088. extension == "vcc" ||
  1089. extension == "w64" ||
  1090. extension == "wav" ||
  1091. extension == "xi" ||
  1092. #endif
  1093. #ifdef HAVE_FFMPEG
  1094. extension == "3g2" ||
  1095. extension == "3gp" ||
  1096. extension == "aac" ||
  1097. extension == "ac3" ||
  1098. extension == "amr" ||
  1099. extension == "ape" ||
  1100. extension == "mp2" ||
  1101. extension == "mpc" ||
  1102. extension == "wma" ||
  1103. # ifndef HAVE_SNDFILE
  1104. // FFmpeg without sndfile
  1105. extension == "flac" ||
  1106. extension == "oga" ||
  1107. extension == "ogg" ||
  1108. extension == "w64" ||
  1109. extension == "wav" ||
  1110. # endif
  1111. #endif
  1112. false
  1113. )
  1114. {
  1115. if (addPlugin(PLUGIN_INTERNAL, nullptr, baseName, "audiofile", 0, nullptr))
  1116. {
  1117. if (const CarlaPluginPtr plugin = getPlugin(curPluginId))
  1118. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "file", filename, true);
  1119. return true;
  1120. }
  1121. return false;
  1122. }
  1123. // -------------------------------------------------------------------
  1124. if (extension == "mid" || extension == "midi")
  1125. {
  1126. if (addPlugin(PLUGIN_INTERNAL, nullptr, baseName, "midifile", 0, nullptr))
  1127. {
  1128. if (const CarlaPluginPtr plugin = getPlugin(curPluginId))
  1129. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "file", filename, true);
  1130. return true;
  1131. }
  1132. return false;
  1133. }
  1134. // -------------------------------------------------------------------
  1135. // ZynAddSubFX
  1136. if (extension == "xmz" || extension == "xiz")
  1137. {
  1138. #ifdef HAVE_ZYN_DEPS
  1139. CarlaString nicerName("Zyn - ");
  1140. const std::size_t sep(baseName.find('-')+1);
  1141. if (sep < baseName.length())
  1142. nicerName += baseName.buffer()+sep;
  1143. else
  1144. nicerName += baseName;
  1145. if (addPlugin(PLUGIN_INTERNAL, nullptr, nicerName, "zynaddsubfx", 0, nullptr))
  1146. {
  1147. callback(true, true, ENGINE_CALLBACK_UI_STATE_CHANGED, curPluginId, 0, 0, 0, 0.0f, nullptr);
  1148. if (const CarlaPluginPtr plugin = getPlugin(curPluginId))
  1149. {
  1150. const char* const ext = (extension == "xmz") ? "CarlaAlternateFile1" : "CarlaAlternateFile2";
  1151. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, ext, filename, true);
  1152. }
  1153. return true;
  1154. }
  1155. return false;
  1156. #else
  1157. setLastError("This Carla build does not have ZynAddSubFX support");
  1158. return false;
  1159. #endif
  1160. }
  1161. // -------------------------------------------------------------------
  1162. // Direct plugin binaries
  1163. #ifdef CARLA_OS_MAC
  1164. if (extension == "vst")
  1165. return addPlugin(PLUGIN_VST2, filename, nullptr, nullptr, 0, nullptr);
  1166. #else
  1167. if (extension == "dll" || extension == "so")
  1168. return addPlugin(getBinaryTypeFromFile(filename), PLUGIN_VST2, filename, nullptr, nullptr, 0, nullptr);
  1169. #endif
  1170. if (extension == "vst3")
  1171. return addPlugin(getBinaryTypeFromFile(filename), PLUGIN_VST3, filename, nullptr, nullptr, 0, nullptr);
  1172. if (extension == "clap")
  1173. return addPlugin(getBinaryTypeFromFile(filename), PLUGIN_CLAP, filename, nullptr, nullptr, 0, nullptr);
  1174. // -------------------------------------------------------------------
  1175. setLastError("Unknown file extension");
  1176. return false;
  1177. }
  1178. bool CarlaEngine::loadProject(const char* const filename, const bool setAsCurrentProject)
  1179. {
  1180. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  1181. CARLA_SAFE_ASSERT_RETURN_ERR(filename != nullptr && filename[0] != '\0', "Invalid filename");
  1182. carla_debug("CarlaEngine::loadProject(\"%s\")", filename);
  1183. const String jfilename = String(CharPointer_UTF8(filename));
  1184. const File file(jfilename);
  1185. CARLA_SAFE_ASSERT_RETURN_ERR(file.existsAsFile(), "Requested file does not exist or is not a readable file");
  1186. if (setAsCurrentProject)
  1187. {
  1188. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1189. if (pData->currentProjectFilename != filename)
  1190. {
  1191. pData->currentProjectFilename = filename;
  1192. bool found;
  1193. const size_t r = pData->currentProjectFilename.rfind(CARLA_OS_SEP, &found);
  1194. if (found)
  1195. {
  1196. pData->currentProjectFolder = filename;
  1197. pData->currentProjectFolder[r] = '\0';
  1198. }
  1199. else
  1200. {
  1201. pData->currentProjectFolder.clear();
  1202. }
  1203. }
  1204. #endif
  1205. }
  1206. XmlDocument xml(file);
  1207. return loadProjectInternal(xml, !setAsCurrentProject);
  1208. }
  1209. bool CarlaEngine::saveProject(const char* const filename, const bool setAsCurrentProject)
  1210. {
  1211. CARLA_SAFE_ASSERT_RETURN_ERR(filename != nullptr && filename[0] != '\0', "Invalid filename");
  1212. carla_debug("CarlaEngine::saveProject(\"%s\")", filename);
  1213. if (setAsCurrentProject)
  1214. {
  1215. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1216. if (pData->currentProjectFilename != filename)
  1217. {
  1218. pData->currentProjectFilename = filename;
  1219. bool found;
  1220. const size_t r = pData->currentProjectFilename.rfind(CARLA_OS_SEP, &found);
  1221. if (found)
  1222. {
  1223. pData->currentProjectFolder = filename;
  1224. pData->currentProjectFolder[r] = '\0';
  1225. }
  1226. else
  1227. {
  1228. pData->currentProjectFolder.clear();
  1229. }
  1230. }
  1231. #endif
  1232. }
  1233. MemoryOutputStream out;
  1234. saveProjectInternal(out);
  1235. const String jfilename = String(CharPointer_UTF8(filename));
  1236. File file(jfilename);
  1237. if (file.replaceWithData(out.getData(), out.getDataSize()))
  1238. return true;
  1239. setLastError("Failed to write file");
  1240. return false;
  1241. }
  1242. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1243. const char* CarlaEngine::getCurrentProjectFolder() const noexcept
  1244. {
  1245. return pData->currentProjectFolder.isNotEmpty() ? pData->currentProjectFolder.buffer()
  1246. : nullptr;
  1247. }
  1248. const char* CarlaEngine::getCurrentProjectFilename() const noexcept
  1249. {
  1250. return pData->currentProjectFilename;
  1251. }
  1252. void CarlaEngine::clearCurrentProjectFilename() noexcept
  1253. {
  1254. pData->currentProjectFilename.clear();
  1255. pData->currentProjectFolder.clear();
  1256. }
  1257. #endif
  1258. // -----------------------------------------------------------------------
  1259. // Information (base)
  1260. uint32_t CarlaEngine::getBufferSize() const noexcept
  1261. {
  1262. return pData->bufferSize;
  1263. }
  1264. double CarlaEngine::getSampleRate() const noexcept
  1265. {
  1266. return pData->sampleRate;
  1267. }
  1268. const char* CarlaEngine::getName() const noexcept
  1269. {
  1270. return pData->name;
  1271. }
  1272. EngineProcessMode CarlaEngine::getProccessMode() const noexcept
  1273. {
  1274. return pData->options.processMode;
  1275. }
  1276. const EngineOptions& CarlaEngine::getOptions() const noexcept
  1277. {
  1278. return pData->options;
  1279. }
  1280. EngineTimeInfo CarlaEngine::getTimeInfo() const noexcept
  1281. {
  1282. return pData->timeInfo;
  1283. }
  1284. // -----------------------------------------------------------------------
  1285. // Information (peaks)
  1286. const float* CarlaEngine::getPeaks(const uint pluginId) const noexcept
  1287. {
  1288. static const float kFallback[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
  1289. if (pluginId == MAIN_CARLA_PLUGIN_ID)
  1290. {
  1291. // get peak from first plugin, if available
  1292. if (const uint count = pData->curPluginCount)
  1293. {
  1294. pData->peaks[0] = pData->plugins[0].peaks[0];
  1295. pData->peaks[1] = pData->plugins[0].peaks[1];
  1296. pData->peaks[2] = pData->plugins[count-1].peaks[2];
  1297. pData->peaks[3] = pData->plugins[count-1].peaks[3];
  1298. }
  1299. else
  1300. {
  1301. carla_zeroFloats(pData->peaks, 4);
  1302. }
  1303. return pData->peaks;
  1304. }
  1305. CARLA_SAFE_ASSERT_RETURN(pluginId < pData->curPluginCount, kFallback);
  1306. return pData->plugins[pluginId].peaks;
  1307. }
  1308. float CarlaEngine::getInputPeak(const uint pluginId, const bool isLeft) const noexcept
  1309. {
  1310. if (pluginId == MAIN_CARLA_PLUGIN_ID)
  1311. {
  1312. // get peak from first plugin, if available
  1313. if (pData->curPluginCount > 0)
  1314. return pData->plugins[0].peaks[isLeft ? 0 : 1];
  1315. return 0.0f;
  1316. }
  1317. CARLA_SAFE_ASSERT_RETURN(pluginId < pData->curPluginCount, 0.0f);
  1318. return pData->plugins[pluginId].peaks[isLeft ? 0 : 1];
  1319. }
  1320. float CarlaEngine::getOutputPeak(const uint pluginId, const bool isLeft) const noexcept
  1321. {
  1322. if (pluginId == MAIN_CARLA_PLUGIN_ID)
  1323. {
  1324. // get peak from last plugin, if available
  1325. if (pData->curPluginCount > 0)
  1326. return pData->plugins[pData->curPluginCount-1].peaks[isLeft ? 2 : 3];
  1327. return 0.0f;
  1328. }
  1329. CARLA_SAFE_ASSERT_RETURN(pluginId < pData->curPluginCount, 0.0f);
  1330. return pData->plugins[pluginId].peaks[isLeft ? 2 : 3];
  1331. }
  1332. // -----------------------------------------------------------------------
  1333. // Callback
  1334. void CarlaEngine::callback(const bool sendHost, const bool sendOSC,
  1335. const EngineCallbackOpcode action, const uint pluginId,
  1336. const int value1, const int value2, const int value3,
  1337. const float valuef, const char* const valueStr) noexcept
  1338. {
  1339. #ifdef DEBUG
  1340. if (pData->isIdling)
  1341. carla_stdout("CarlaEngine::callback [while idling] (%s, %s, %i:%s, %i, %i, %i, %i, %f, \"%s\")",
  1342. bool2str(sendHost), bool2str(sendOSC),
  1343. action, EngineCallbackOpcode2Str(action), pluginId, value1, value2, value3,
  1344. static_cast<double>(valuef), valueStr);
  1345. else if (action != ENGINE_CALLBACK_IDLE && action != ENGINE_CALLBACK_NOTE_ON && action != ENGINE_CALLBACK_NOTE_OFF)
  1346. carla_debug("CarlaEngine::callback(%s, %s, %i:%s, %i, %i, %i, %i, %f, \"%s\")",
  1347. bool2str(sendHost), bool2str(sendOSC),
  1348. action, EngineCallbackOpcode2Str(action), pluginId, value1, value2, value3,
  1349. static_cast<double>(valuef), valueStr);
  1350. #endif
  1351. if (sendHost && pData->callback != nullptr)
  1352. {
  1353. if (action == ENGINE_CALLBACK_IDLE)
  1354. ++pData->isIdling;
  1355. try {
  1356. pData->callback(pData->callbackPtr, action, pluginId, value1, value2, value3, valuef, valueStr);
  1357. } CARLA_SAFE_EXCEPTION("callback")
  1358. if (action == ENGINE_CALLBACK_IDLE)
  1359. --pData->isIdling;
  1360. }
  1361. if (sendOSC)
  1362. {
  1363. #if defined(HAVE_LIBLO) && ! defined(BUILD_BRIDGE)
  1364. if (pData->osc.isControlRegisteredForTCP())
  1365. {
  1366. switch (action)
  1367. {
  1368. case ENGINE_CALLBACK_RELOAD_INFO:
  1369. {
  1370. CarlaPluginPtr plugin = pData->plugins[pluginId].plugin;
  1371. CARLA_SAFE_ASSERT_BREAK(plugin != nullptr);
  1372. pData->osc.sendPluginInfo(plugin);
  1373. break;
  1374. }
  1375. case ENGINE_CALLBACK_RELOAD_PARAMETERS:
  1376. {
  1377. CarlaPluginPtr plugin = pData->plugins[pluginId].plugin;
  1378. CARLA_SAFE_ASSERT_BREAK(plugin != nullptr);
  1379. pData->osc.sendPluginPortCount(plugin);
  1380. if (const uint32_t count = plugin->getParameterCount())
  1381. {
  1382. for (uint32_t i=0; i<count; ++i)
  1383. pData->osc.sendPluginParameterInfo(plugin, i);
  1384. }
  1385. break;
  1386. }
  1387. case ENGINE_CALLBACK_RELOAD_PROGRAMS:
  1388. {
  1389. CarlaPluginPtr plugin = pData->plugins[pluginId].plugin;
  1390. CARLA_SAFE_ASSERT_BREAK(plugin != nullptr);
  1391. pData->osc.sendPluginProgramCount(plugin);
  1392. if (const uint32_t count = plugin->getProgramCount())
  1393. {
  1394. for (uint32_t i=0; i<count; ++i)
  1395. pData->osc.sendPluginProgram(plugin, i);
  1396. }
  1397. if (const uint32_t count = plugin->getMidiProgramCount())
  1398. {
  1399. for (uint32_t i=0; i<count; ++i)
  1400. pData->osc.sendPluginMidiProgram(plugin, i);
  1401. }
  1402. break;
  1403. }
  1404. case ENGINE_CALLBACK_PLUGIN_ADDED:
  1405. case ENGINE_CALLBACK_RELOAD_ALL:
  1406. {
  1407. CarlaPluginPtr plugin = pData->plugins[pluginId].plugin;
  1408. CARLA_SAFE_ASSERT_BREAK(plugin != nullptr);
  1409. pData->osc.sendPluginInfo(plugin);
  1410. pData->osc.sendPluginPortCount(plugin);
  1411. pData->osc.sendPluginDataCount(plugin);
  1412. if (const uint32_t count = plugin->getParameterCount())
  1413. {
  1414. for (uint32_t i=0; i<count; ++i)
  1415. pData->osc.sendPluginParameterInfo(plugin, i);
  1416. }
  1417. if (const uint32_t count = plugin->getProgramCount())
  1418. {
  1419. for (uint32_t i=0; i<count; ++i)
  1420. pData->osc.sendPluginProgram(plugin, i);
  1421. }
  1422. if (const uint32_t count = plugin->getMidiProgramCount())
  1423. {
  1424. for (uint32_t i=0; i<count; ++i)
  1425. pData->osc.sendPluginMidiProgram(plugin, i);
  1426. }
  1427. if (const uint32_t count = plugin->getCustomDataCount())
  1428. {
  1429. for (uint32_t i=0; i<count; ++i)
  1430. pData->osc.sendPluginCustomData(plugin, i);
  1431. }
  1432. pData->osc.sendPluginInternalParameterValues(plugin);
  1433. break;
  1434. }
  1435. case ENGINE_CALLBACK_IDLE:
  1436. return;
  1437. default:
  1438. break;
  1439. }
  1440. pData->osc.sendCallback(action, pluginId, value1, value2, value3, valuef, valueStr);
  1441. }
  1442. #endif
  1443. }
  1444. }
  1445. void CarlaEngine::setCallback(const EngineCallbackFunc func, void* const ptr) noexcept
  1446. {
  1447. carla_debug("CarlaEngine::setCallback(%p, %p)", func, ptr);
  1448. pData->callback = func;
  1449. pData->callbackPtr = ptr;
  1450. }
  1451. // -----------------------------------------------------------------------
  1452. // File Callback
  1453. const char* CarlaEngine::runFileCallback(const FileCallbackOpcode action, const bool isDir, const char* const title, const char* const filter) noexcept
  1454. {
  1455. CARLA_SAFE_ASSERT_RETURN(title != nullptr && title[0] != '\0', nullptr);
  1456. CARLA_SAFE_ASSERT_RETURN(filter != nullptr, nullptr);
  1457. carla_debug("CarlaEngine::runFileCallback(%i:%s, %s, \"%s\", \"%s\")", action, FileCallbackOpcode2Str(action), bool2str(isDir), title, filter);
  1458. const char* ret = nullptr;
  1459. if (pData->fileCallback != nullptr)
  1460. {
  1461. try {
  1462. ret = pData->fileCallback(pData->fileCallbackPtr, action, isDir, title, filter);
  1463. } CARLA_SAFE_EXCEPTION("runFileCallback");
  1464. }
  1465. return ret;
  1466. }
  1467. void CarlaEngine::setFileCallback(const FileCallbackFunc func, void* const ptr) noexcept
  1468. {
  1469. carla_debug("CarlaEngine::setFileCallback(%p, %p)", func, ptr);
  1470. pData->fileCallback = func;
  1471. pData->fileCallbackPtr = ptr;
  1472. }
  1473. // -----------------------------------------------------------------------
  1474. // Transport
  1475. void CarlaEngine::transportPlay() noexcept
  1476. {
  1477. pData->timeInfo.playing = true;
  1478. pData->time.setNeedsReset();
  1479. }
  1480. void CarlaEngine::transportPause() noexcept
  1481. {
  1482. if (pData->timeInfo.playing)
  1483. pData->time.pause();
  1484. else
  1485. pData->time.setNeedsReset();
  1486. }
  1487. void CarlaEngine::transportBPM(const double bpm) noexcept
  1488. {
  1489. CARLA_SAFE_ASSERT_RETURN(bpm >= 20.0,)
  1490. try {
  1491. pData->time.setBPM(bpm);
  1492. } CARLA_SAFE_EXCEPTION("CarlaEngine::transportBPM");
  1493. }
  1494. void CarlaEngine::transportRelocate(const uint64_t frame) noexcept
  1495. {
  1496. pData->time.relocate(frame);
  1497. }
  1498. // -----------------------------------------------------------------------
  1499. // Error handling
  1500. const char* CarlaEngine::getLastError() const noexcept
  1501. {
  1502. return pData->lastError;
  1503. }
  1504. void CarlaEngine::setLastError(const char* const error) const noexcept
  1505. {
  1506. pData->lastError = error;
  1507. }
  1508. // -----------------------------------------------------------------------
  1509. // Misc
  1510. bool CarlaEngine::isAboutToClose() const noexcept
  1511. {
  1512. return pData->aboutToClose;
  1513. }
  1514. bool CarlaEngine::setAboutToClose() noexcept
  1515. {
  1516. carla_debug("CarlaEngine::setAboutToClose()");
  1517. pData->aboutToClose = true;
  1518. return (pData->isIdling == 0);
  1519. }
  1520. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1521. bool CarlaEngine::isLoadingProject() const noexcept
  1522. {
  1523. return pData->loadingProject;
  1524. }
  1525. #endif
  1526. void CarlaEngine::setActionCanceled(const bool canceled) noexcept
  1527. {
  1528. pData->actionCanceled = canceled;
  1529. }
  1530. bool CarlaEngine::wasActionCanceled() const noexcept
  1531. {
  1532. return pData->actionCanceled;
  1533. }
  1534. // -----------------------------------------------------------------------
  1535. // Global options
  1536. void CarlaEngine::setOption(const EngineOption option, const int value, const char* const valueStr) noexcept
  1537. {
  1538. carla_debug("CarlaEngine::setOption(%i:%s, %i, \"%s\")", option, EngineOption2Str(option), value, valueStr);
  1539. if (isRunning())
  1540. {
  1541. switch (option)
  1542. {
  1543. case ENGINE_OPTION_PROCESS_MODE:
  1544. case ENGINE_OPTION_AUDIO_TRIPLE_BUFFER:
  1545. case ENGINE_OPTION_AUDIO_DRIVER:
  1546. case ENGINE_OPTION_AUDIO_DEVICE:
  1547. return carla_stderr("CarlaEngine::setOption(%i:%s, %i, \"%s\") - Cannot set this option while engine is running!",
  1548. option, EngineOption2Str(option), value, valueStr);
  1549. default:
  1550. break;
  1551. }
  1552. }
  1553. // do not un-force stereo for rack mode
  1554. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK && option == ENGINE_OPTION_FORCE_STEREO && value != 0)
  1555. return;
  1556. switch (option)
  1557. {
  1558. case ENGINE_OPTION_DEBUG:
  1559. break;
  1560. case ENGINE_OPTION_PROCESS_MODE:
  1561. CARLA_SAFE_ASSERT_RETURN(value >= ENGINE_PROCESS_MODE_SINGLE_CLIENT && value <= ENGINE_PROCESS_MODE_BRIDGE,);
  1562. pData->options.processMode = static_cast<EngineProcessMode>(value);
  1563. break;
  1564. case ENGINE_OPTION_TRANSPORT_MODE:
  1565. CARLA_SAFE_ASSERT_RETURN(value >= ENGINE_TRANSPORT_MODE_DISABLED && value <= ENGINE_TRANSPORT_MODE_BRIDGE,);
  1566. CARLA_SAFE_ASSERT_RETURN(getType() == kEngineTypeJack || value != ENGINE_TRANSPORT_MODE_JACK,);
  1567. pData->options.transportMode = static_cast<EngineTransportMode>(value);
  1568. delete[] pData->options.transportExtra;
  1569. if (value >= ENGINE_TRANSPORT_MODE_DISABLED && valueStr != nullptr)
  1570. pData->options.transportExtra = carla_strdup_safe(valueStr);
  1571. else
  1572. pData->options.transportExtra = nullptr;
  1573. pData->time.setNeedsReset();
  1574. #if defined(HAVE_HYLIA) && !defined(BUILD_BRIDGE)
  1575. // enable link now if needed
  1576. {
  1577. const bool linkEnabled = pData->options.transportExtra != nullptr && std::strstr(pData->options.transportExtra, ":link:") != nullptr;
  1578. pData->time.enableLink(linkEnabled);
  1579. }
  1580. #endif
  1581. break;
  1582. case ENGINE_OPTION_FORCE_STEREO:
  1583. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1584. pData->options.forceStereo = (value != 0);
  1585. break;
  1586. case ENGINE_OPTION_PREFER_PLUGIN_BRIDGES:
  1587. #ifdef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1588. CARLA_SAFE_ASSERT_RETURN(value == 0,);
  1589. #else
  1590. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1591. #endif
  1592. pData->options.preferPluginBridges = (value != 0);
  1593. break;
  1594. case ENGINE_OPTION_PREFER_UI_BRIDGES:
  1595. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1596. pData->options.preferUiBridges = (value != 0);
  1597. break;
  1598. case ENGINE_OPTION_UIS_ALWAYS_ON_TOP:
  1599. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1600. pData->options.uisAlwaysOnTop = (value != 0);
  1601. break;
  1602. case ENGINE_OPTION_MAX_PARAMETERS:
  1603. CARLA_SAFE_ASSERT_RETURN(value >= 0,);
  1604. pData->options.maxParameters = static_cast<uint>(value);
  1605. break;
  1606. case ENGINE_OPTION_RESET_XRUNS:
  1607. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1608. pData->options.resetXruns = (value != 0);
  1609. break;
  1610. case ENGINE_OPTION_UI_BRIDGES_TIMEOUT:
  1611. CARLA_SAFE_ASSERT_RETURN(value >= 0,);
  1612. pData->options.uiBridgesTimeout = static_cast<uint>(value);
  1613. break;
  1614. case ENGINE_OPTION_AUDIO_BUFFER_SIZE:
  1615. CARLA_SAFE_ASSERT_RETURN(value >= 8,);
  1616. pData->options.audioBufferSize = static_cast<uint>(value);
  1617. break;
  1618. case ENGINE_OPTION_AUDIO_SAMPLE_RATE:
  1619. CARLA_SAFE_ASSERT_RETURN(value >= 22050,);
  1620. pData->options.audioSampleRate = static_cast<uint>(value);
  1621. break;
  1622. case ENGINE_OPTION_AUDIO_TRIPLE_BUFFER:
  1623. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1624. pData->options.audioTripleBuffer = (value != 0);
  1625. break;
  1626. case ENGINE_OPTION_AUDIO_DRIVER:
  1627. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr,);
  1628. if (pData->options.audioDriver != nullptr)
  1629. delete[] pData->options.audioDriver;
  1630. pData->options.audioDriver = carla_strdup_safe(valueStr);
  1631. break;
  1632. case ENGINE_OPTION_AUDIO_DEVICE:
  1633. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr,);
  1634. if (pData->options.audioDevice != nullptr)
  1635. delete[] pData->options.audioDevice;
  1636. pData->options.audioDevice = carla_strdup_safe(valueStr);
  1637. break;
  1638. #ifndef BUILD_BRIDGE
  1639. case ENGINE_OPTION_OSC_ENABLED:
  1640. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1641. pData->options.oscEnabled = (value != 0);
  1642. break;
  1643. case ENGINE_OPTION_OSC_PORT_TCP:
  1644. CARLA_SAFE_ASSERT_RETURN(value <= 0 || value >= 1024,);
  1645. pData->options.oscPortTCP = value;
  1646. break;
  1647. case ENGINE_OPTION_OSC_PORT_UDP:
  1648. CARLA_SAFE_ASSERT_RETURN(value <= 0 || value >= 1024,);
  1649. pData->options.oscPortUDP = value;
  1650. break;
  1651. #endif
  1652. case ENGINE_OPTION_FILE_PATH:
  1653. CARLA_SAFE_ASSERT_RETURN(value > FILE_NONE,);
  1654. CARLA_SAFE_ASSERT_RETURN(value <= FILE_MIDI,);
  1655. switch (value)
  1656. {
  1657. case FILE_AUDIO:
  1658. if (pData->options.pathAudio != nullptr)
  1659. delete[] pData->options.pathAudio;
  1660. if (valueStr != nullptr)
  1661. pData->options.pathAudio = carla_strdup_safe(valueStr);
  1662. else
  1663. pData->options.pathAudio = nullptr;
  1664. break;
  1665. case FILE_MIDI:
  1666. if (pData->options.pathMIDI != nullptr)
  1667. delete[] pData->options.pathMIDI;
  1668. if (valueStr != nullptr)
  1669. pData->options.pathMIDI = carla_strdup_safe(valueStr);
  1670. else
  1671. pData->options.pathMIDI = nullptr;
  1672. break;
  1673. default:
  1674. return carla_stderr("CarlaEngine::setOption(%i:%s, %i, \"%s\") - Invalid file type",
  1675. option, EngineOption2Str(option), value, valueStr);
  1676. break;
  1677. }
  1678. break;
  1679. case ENGINE_OPTION_PLUGIN_PATH:
  1680. CARLA_SAFE_ASSERT_RETURN(value > PLUGIN_NONE,);
  1681. CARLA_SAFE_ASSERT_RETURN(value <= PLUGIN_TYPE_COUNT,);
  1682. switch (value)
  1683. {
  1684. case PLUGIN_LADSPA:
  1685. if (pData->options.pathLADSPA != nullptr)
  1686. delete[] pData->options.pathLADSPA;
  1687. if (valueStr != nullptr)
  1688. pData->options.pathLADSPA = carla_strdup_safe(valueStr);
  1689. else
  1690. pData->options.pathLADSPA = nullptr;
  1691. break;
  1692. case PLUGIN_DSSI:
  1693. if (pData->options.pathDSSI != nullptr)
  1694. delete[] pData->options.pathDSSI;
  1695. if (valueStr != nullptr)
  1696. pData->options.pathDSSI = carla_strdup_safe(valueStr);
  1697. else
  1698. pData->options.pathDSSI = nullptr;
  1699. break;
  1700. case PLUGIN_LV2:
  1701. if (pData->options.pathLV2 != nullptr)
  1702. delete[] pData->options.pathLV2;
  1703. if (valueStr != nullptr)
  1704. pData->options.pathLV2 = carla_strdup_safe(valueStr);
  1705. else
  1706. pData->options.pathLV2 = nullptr;
  1707. break;
  1708. case PLUGIN_VST2:
  1709. if (pData->options.pathVST2 != nullptr)
  1710. delete[] pData->options.pathVST2;
  1711. if (valueStr != nullptr)
  1712. pData->options.pathVST2 = carla_strdup_safe(valueStr);
  1713. else
  1714. pData->options.pathVST2 = nullptr;
  1715. break;
  1716. case PLUGIN_VST3:
  1717. if (pData->options.pathVST3 != nullptr)
  1718. delete[] pData->options.pathVST3;
  1719. if (valueStr != nullptr)
  1720. pData->options.pathVST3 = carla_strdup_safe(valueStr);
  1721. else
  1722. pData->options.pathVST3 = nullptr;
  1723. break;
  1724. case PLUGIN_SF2:
  1725. if (pData->options.pathSF2 != nullptr)
  1726. delete[] pData->options.pathSF2;
  1727. if (valueStr != nullptr)
  1728. pData->options.pathSF2 = carla_strdup_safe(valueStr);
  1729. else
  1730. pData->options.pathSF2 = nullptr;
  1731. break;
  1732. case PLUGIN_SFZ:
  1733. if (pData->options.pathSFZ != nullptr)
  1734. delete[] pData->options.pathSFZ;
  1735. if (valueStr != nullptr)
  1736. pData->options.pathSFZ = carla_strdup_safe(valueStr);
  1737. else
  1738. pData->options.pathSFZ = nullptr;
  1739. break;
  1740. case PLUGIN_JSFX:
  1741. if (pData->options.pathJSFX != nullptr)
  1742. delete[] pData->options.pathJSFX;
  1743. if (valueStr != nullptr)
  1744. pData->options.pathJSFX = carla_strdup_safe(valueStr);
  1745. else
  1746. pData->options.pathJSFX = nullptr;
  1747. break;
  1748. case PLUGIN_CLAP:
  1749. if (pData->options.pathCLAP != nullptr)
  1750. delete[] pData->options.pathCLAP;
  1751. if (valueStr != nullptr)
  1752. pData->options.pathCLAP = carla_strdup_safe(valueStr);
  1753. else
  1754. pData->options.pathCLAP = nullptr;
  1755. break;
  1756. default:
  1757. return carla_stderr("CarlaEngine::setOption(%i:%s, %i, \"%s\") - Invalid plugin type",
  1758. option, EngineOption2Str(option), value, valueStr);
  1759. break;
  1760. }
  1761. break;
  1762. case ENGINE_OPTION_PATH_BINARIES:
  1763. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1764. if (pData->options.binaryDir != nullptr)
  1765. delete[] pData->options.binaryDir;
  1766. pData->options.binaryDir = carla_strdup_safe(valueStr);
  1767. break;
  1768. case ENGINE_OPTION_PATH_RESOURCES:
  1769. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1770. if (pData->options.resourceDir != nullptr)
  1771. delete[] pData->options.resourceDir;
  1772. pData->options.resourceDir = carla_strdup_safe(valueStr);
  1773. break;
  1774. case ENGINE_OPTION_PREVENT_BAD_BEHAVIOUR: {
  1775. CARLA_SAFE_ASSERT_RETURN(pData->options.binaryDir != nullptr && pData->options.binaryDir[0] != '\0',);
  1776. #ifdef CARLA_OS_LINUX
  1777. const ScopedEngineEnvironmentLocker _seel(this);
  1778. if (value != 0)
  1779. {
  1780. CarlaString interposerPath(CarlaString(pData->options.binaryDir) + "/libcarla_interposer-safe.so");
  1781. ::setenv("LD_PRELOAD", interposerPath.buffer(), 1);
  1782. }
  1783. else
  1784. {
  1785. ::unsetenv("LD_PRELOAD");
  1786. }
  1787. #endif
  1788. } break;
  1789. case ENGINE_OPTION_FRONTEND_BACKGROUND_COLOR:
  1790. pData->options.bgColor = static_cast<uint>(value);
  1791. break;
  1792. case ENGINE_OPTION_FRONTEND_FOREGROUND_COLOR:
  1793. pData->options.fgColor = static_cast<uint>(value);
  1794. break;
  1795. case ENGINE_OPTION_FRONTEND_UI_SCALE:
  1796. CARLA_SAFE_ASSERT_RETURN(value > 0,);
  1797. pData->options.uiScale = static_cast<float>(value) / 1000;
  1798. break;
  1799. case ENGINE_OPTION_FRONTEND_WIN_ID: {
  1800. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1801. const long long winId(std::strtoll(valueStr, nullptr, 16));
  1802. CARLA_SAFE_ASSERT_RETURN(winId >= 0,);
  1803. pData->options.frontendWinId = static_cast<uintptr_t>(winId);
  1804. } break;
  1805. #if !defined(BUILD_BRIDGE_ALTERNATIVE_ARCH) && !defined(CARLA_OS_WIN)
  1806. case ENGINE_OPTION_WINE_EXECUTABLE:
  1807. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1808. if (pData->options.wine.executable != nullptr)
  1809. delete[] pData->options.wine.executable;
  1810. pData->options.wine.executable = carla_strdup_safe(valueStr);
  1811. break;
  1812. case ENGINE_OPTION_WINE_AUTO_PREFIX:
  1813. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1814. pData->options.wine.autoPrefix = (value != 0);
  1815. break;
  1816. case ENGINE_OPTION_WINE_FALLBACK_PREFIX:
  1817. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1818. if (pData->options.wine.fallbackPrefix != nullptr)
  1819. delete[] pData->options.wine.fallbackPrefix;
  1820. pData->options.wine.fallbackPrefix = carla_strdup_safe(valueStr);
  1821. break;
  1822. case ENGINE_OPTION_WINE_RT_PRIO_ENABLED:
  1823. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1824. pData->options.wine.rtPrio = (value != 0);
  1825. break;
  1826. case ENGINE_OPTION_WINE_BASE_RT_PRIO:
  1827. CARLA_SAFE_ASSERT_RETURN(value >= 1 && value <= 89,);
  1828. pData->options.wine.baseRtPrio = value;
  1829. break;
  1830. case ENGINE_OPTION_WINE_SERVER_RT_PRIO:
  1831. CARLA_SAFE_ASSERT_RETURN(value >= 1 && value <= 99,);
  1832. pData->options.wine.serverRtPrio = value;
  1833. break;
  1834. #endif
  1835. #ifndef BUILD_BRIDGE
  1836. case ENGINE_OPTION_DEBUG_CONSOLE_OUTPUT:
  1837. break;
  1838. #endif
  1839. case ENGINE_OPTION_CLIENT_NAME_PREFIX:
  1840. if (pData->options.clientNamePrefix != nullptr)
  1841. delete[] pData->options.clientNamePrefix;
  1842. pData->options.clientNamePrefix = valueStr != nullptr && valueStr[0] != '\0'
  1843. ? carla_strdup_safe(valueStr)
  1844. : nullptr;
  1845. break;
  1846. case ENGINE_OPTION_PLUGINS_ARE_STANDALONE:
  1847. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1848. pData->options.pluginsAreStandalone = (value != 0);
  1849. break;
  1850. }
  1851. }
  1852. #ifndef BUILD_BRIDGE
  1853. // -----------------------------------------------------------------------
  1854. // OSC Stuff
  1855. bool CarlaEngine::isOscControlRegistered() const noexcept
  1856. {
  1857. # ifdef HAVE_LIBLO
  1858. return pData->osc.isControlRegisteredForTCP();
  1859. # else
  1860. return false;
  1861. # endif
  1862. }
  1863. const char* CarlaEngine::getOscServerPathTCP() const noexcept
  1864. {
  1865. # ifdef HAVE_LIBLO
  1866. return pData->osc.getServerPathTCP();
  1867. # else
  1868. return nullptr;
  1869. # endif
  1870. }
  1871. const char* CarlaEngine::getOscServerPathUDP() const noexcept
  1872. {
  1873. # ifdef HAVE_LIBLO
  1874. return pData->osc.getServerPathUDP();
  1875. # else
  1876. return nullptr;
  1877. # endif
  1878. }
  1879. #endif
  1880. // -----------------------------------------------------------------------
  1881. // Internal stuff
  1882. void CarlaEngine::bufferSizeChanged(const uint32_t newBufferSize)
  1883. {
  1884. carla_debug("CarlaEngine::bufferSizeChanged(%i)", newBufferSize);
  1885. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1886. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1887. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1888. {
  1889. pData->graph.setBufferSize(newBufferSize);
  1890. }
  1891. #endif
  1892. pData->time.updateAudioValues(newBufferSize, pData->sampleRate);
  1893. for (uint i=0; i < pData->curPluginCount; ++i)
  1894. {
  1895. if (const CarlaPluginPtr plugin = pData->plugins[i].plugin)
  1896. {
  1897. if (plugin->isEnabled() && plugin->tryLock(true))
  1898. {
  1899. plugin->bufferSizeChanged(newBufferSize);
  1900. plugin->unlock();
  1901. }
  1902. }
  1903. }
  1904. callback(true, true, ENGINE_CALLBACK_BUFFER_SIZE_CHANGED, 0, static_cast<int>(newBufferSize), 0, 0, 0.0f, nullptr);
  1905. }
  1906. void CarlaEngine::sampleRateChanged(const double newSampleRate)
  1907. {
  1908. carla_debug("CarlaEngine::sampleRateChanged(%g)", newSampleRate);
  1909. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1910. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1911. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1912. {
  1913. pData->graph.setSampleRate(newSampleRate);
  1914. }
  1915. #endif
  1916. pData->time.updateAudioValues(pData->bufferSize, newSampleRate);
  1917. for (uint i=0; i < pData->curPluginCount; ++i)
  1918. {
  1919. if (const CarlaPluginPtr plugin = pData->plugins[i].plugin)
  1920. {
  1921. if (plugin->isEnabled() && plugin->tryLock(true))
  1922. {
  1923. plugin->sampleRateChanged(newSampleRate);
  1924. plugin->unlock();
  1925. }
  1926. }
  1927. }
  1928. callback(true, true, ENGINE_CALLBACK_SAMPLE_RATE_CHANGED, 0, 0, 0, 0, static_cast<float>(newSampleRate), nullptr);
  1929. }
  1930. void CarlaEngine::offlineModeChanged(const bool isOfflineNow)
  1931. {
  1932. carla_debug("CarlaEngine::offlineModeChanged(%s)", bool2str(isOfflineNow));
  1933. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1934. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1935. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1936. {
  1937. pData->graph.setOffline(isOfflineNow);
  1938. }
  1939. #endif
  1940. for (uint i=0; i < pData->curPluginCount; ++i)
  1941. {
  1942. if (const CarlaPluginPtr plugin = pData->plugins[i].plugin)
  1943. if (plugin->isEnabled())
  1944. plugin->offlineModeChanged(isOfflineNow);
  1945. }
  1946. }
  1947. void CarlaEngine::setPluginPeaksRT(const uint pluginId, float const inPeaks[2], float const outPeaks[2]) noexcept
  1948. {
  1949. EnginePluginData& pluginData(pData->plugins[pluginId]);
  1950. pluginData.peaks[0] = inPeaks[0];
  1951. pluginData.peaks[1] = inPeaks[1];
  1952. pluginData.peaks[2] = outPeaks[0];
  1953. pluginData.peaks[3] = outPeaks[1];
  1954. }
  1955. void CarlaEngine::saveProjectInternal(water::MemoryOutputStream& outStream) const
  1956. {
  1957. // send initial prepareForSave first, giving time for bridges to act
  1958. for (uint i=0; i < pData->curPluginCount; ++i)
  1959. {
  1960. if (const CarlaPluginPtr plugin = pData->plugins[i].plugin)
  1961. {
  1962. if (plugin->isEnabled())
  1963. {
  1964. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1965. // deactivate bridge client-side ping check, since some plugins block during save
  1966. if (plugin->getHints() & PLUGIN_IS_BRIDGE)
  1967. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "false", false);
  1968. #endif
  1969. plugin->prepareForSave(false);
  1970. }
  1971. }
  1972. }
  1973. outStream << "<?xml version='1.0' encoding='UTF-8'?>\n";
  1974. outStream << "<!DOCTYPE CARLA-PROJECT>\n";
  1975. outStream << "<CARLA-PROJECT VERSION='" CARLA_VERSION_STRMIN "'";
  1976. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1977. if (pData->ignoreClientPrefix)
  1978. outStream << " IgnoreClientPrefix='true'";
  1979. #endif
  1980. outStream << ">\n";
  1981. const bool isPlugin(getType() == kEngineTypePlugin);
  1982. const EngineOptions& options(pData->options);
  1983. {
  1984. MemoryOutputStream outSettings(1024);
  1985. outSettings << " <EngineSettings>\n";
  1986. outSettings << " <ForceStereo>" << bool2str(options.forceStereo) << "</ForceStereo>\n";
  1987. outSettings << " <PreferPluginBridges>" << bool2str(options.preferPluginBridges) << "</PreferPluginBridges>\n";
  1988. outSettings << " <PreferUiBridges>" << bool2str(options.preferUiBridges) << "</PreferUiBridges>\n";
  1989. outSettings << " <UIsAlwaysOnTop>" << bool2str(options.uisAlwaysOnTop) << "</UIsAlwaysOnTop>\n";
  1990. outSettings << " <MaxParameters>" << String(options.maxParameters) << "</MaxParameters>\n";
  1991. outSettings << " <UIBridgesTimeout>" << String(options.uiBridgesTimeout) << "</UIBridgesTimeout>\n";
  1992. if (isPlugin)
  1993. {
  1994. outSettings << " <LADSPA_PATH>" << xmlSafeString(options.pathLADSPA, true) << "</LADSPA_PATH>\n";
  1995. outSettings << " <DSSI_PATH>" << xmlSafeString(options.pathDSSI, true) << "</DSSI_PATH>\n";
  1996. outSettings << " <LV2_PATH>" << xmlSafeString(options.pathLV2, true) << "</LV2_PATH>\n";
  1997. outSettings << " <VST2_PATH>" << xmlSafeString(options.pathVST2, true) << "</VST2_PATH>\n";
  1998. outSettings << " <VST3_PATH>" << xmlSafeString(options.pathVST3, true) << "</VST3_PATH>\n";
  1999. outSettings << " <SF2_PATH>" << xmlSafeString(options.pathSF2, true) << "</SF2_PATH>\n";
  2000. outSettings << " <SFZ_PATH>" << xmlSafeString(options.pathSFZ, true) << "</SFZ_PATH>\n";
  2001. outSettings << " <JSFX_PATH>" << xmlSafeString(options.pathJSFX, true) << "</JSFX_PATH>\n";
  2002. outSettings << " <CLAP_PATH>" << xmlSafeString(options.pathCLAP, true) << "</CLAP_PATH>\n";
  2003. }
  2004. outSettings << " </EngineSettings>\n";
  2005. outStream << outSettings;
  2006. }
  2007. if (pData->timeInfo.bbt.valid && ! isPlugin)
  2008. {
  2009. MemoryOutputStream outTransport(128);
  2010. outTransport << "\n <Transport>\n";
  2011. // outTransport << " <BeatsPerBar>" << pData->timeInfo.bbt.beatsPerBar << "</BeatsPerBar>\n";
  2012. outTransport << " <BeatsPerMinute>" << pData->timeInfo.bbt.beatsPerMinute << "</BeatsPerMinute>\n";
  2013. outTransport << " </Transport>\n";
  2014. outStream << outTransport;
  2015. }
  2016. char strBuf[STR_MAX+1];
  2017. carla_zeroChars(strBuf, STR_MAX+1);
  2018. for (uint i=0; i < pData->curPluginCount; ++i)
  2019. {
  2020. if (const CarlaPluginPtr plugin = pData->plugins[i].plugin)
  2021. {
  2022. if (plugin->isEnabled())
  2023. {
  2024. MemoryOutputStream outPlugin(4096), streamPlugin;
  2025. plugin->getStateSave(false).dumpToMemoryStream(streamPlugin);
  2026. outPlugin << "\n";
  2027. if (plugin->getRealName(strBuf))
  2028. outPlugin << " <!-- " << xmlSafeString(strBuf, true) << " -->\n";
  2029. outPlugin << " <Plugin>\n";
  2030. outPlugin << streamPlugin;
  2031. outPlugin << " </Plugin>\n";
  2032. outStream << outPlugin;
  2033. }
  2034. }
  2035. }
  2036. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2037. // tell bridges we're done saving
  2038. for (uint i=0; i < pData->curPluginCount; ++i)
  2039. {
  2040. if (const CarlaPluginPtr plugin = pData->plugins[i].plugin)
  2041. if (plugin->isEnabled() && (plugin->getHints() & PLUGIN_IS_BRIDGE) != 0)
  2042. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "true", false);
  2043. }
  2044. // save internal connections
  2045. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  2046. {
  2047. uint posCount = 0;
  2048. const char* const* const patchbayConns = getPatchbayConnections(false);
  2049. const PatchbayPosition* const patchbayPos = getPatchbayPositions(false, posCount);
  2050. if (patchbayConns != nullptr || patchbayPos != nullptr)
  2051. {
  2052. MemoryOutputStream outPatchbay(2048);
  2053. outPatchbay << "\n <Patchbay>\n";
  2054. if (patchbayConns != nullptr)
  2055. {
  2056. for (int i=0; patchbayConns[i] != nullptr && patchbayConns[i+1] != nullptr; ++i, ++i)
  2057. {
  2058. const char* const connSource(patchbayConns[i]);
  2059. const char* const connTarget(patchbayConns[i+1]);
  2060. CARLA_SAFE_ASSERT_CONTINUE(connSource != nullptr && connSource[0] != '\0');
  2061. CARLA_SAFE_ASSERT_CONTINUE(connTarget != nullptr && connTarget[0] != '\0');
  2062. outPatchbay << " <Connection>\n";
  2063. outPatchbay << " <Source>" << xmlSafeString(connSource, true) << "</Source>\n";
  2064. outPatchbay << " <Target>" << xmlSafeString(connTarget, true) << "</Target>\n";
  2065. outPatchbay << " </Connection>\n";
  2066. }
  2067. }
  2068. if (patchbayPos != nullptr && posCount != 0)
  2069. {
  2070. outPatchbay << " <Positions>\n";
  2071. for (uint i=0; i<posCount; ++i)
  2072. {
  2073. const PatchbayPosition& ppos(patchbayPos[i]);
  2074. CARLA_SAFE_ASSERT_CONTINUE(ppos.name != nullptr && ppos.name[0] != '\0');
  2075. outPatchbay << " <Position x1=\"" << ppos.x1 << "\" y1=\"" << ppos.y1;
  2076. if (ppos.x2 != 0 || ppos.y2 != 0)
  2077. outPatchbay << "\" x2=\"" << ppos.x2 << "\" y2=\"" << ppos.y2;
  2078. if (ppos.pluginId >= 0)
  2079. outPatchbay << "\" pluginId=\"" << ppos.pluginId;
  2080. outPatchbay << "\">\n";
  2081. outPatchbay << " <Name>" << xmlSafeString(ppos.name, true) << "</Name>\n";
  2082. outPatchbay << " </Position>\n";
  2083. if (ppos.dealloc)
  2084. delete[] ppos.name;
  2085. }
  2086. outPatchbay << " </Positions>\n";
  2087. }
  2088. outPatchbay << " </Patchbay>\n";
  2089. outStream << outPatchbay;
  2090. delete[] patchbayPos;
  2091. }
  2092. }
  2093. // if we're running inside some session-manager (and using JACK), let them handle the connections
  2094. bool saveExternalConnections, saveExternalPositions = true;
  2095. /**/ if (isPlugin)
  2096. {
  2097. saveExternalConnections = false;
  2098. saveExternalPositions = false;
  2099. }
  2100. else if (std::strcmp(getCurrentDriverName(), "JACK") != 0)
  2101. {
  2102. saveExternalConnections = true;
  2103. }
  2104. else if (std::getenv("CARLA_DONT_MANAGE_CONNECTIONS") != nullptr)
  2105. {
  2106. saveExternalConnections = false;
  2107. }
  2108. else
  2109. {
  2110. saveExternalConnections = true;
  2111. }
  2112. if (saveExternalConnections || saveExternalPositions)
  2113. {
  2114. uint posCount = 0;
  2115. const char* const* const patchbayConns = saveExternalConnections
  2116. ? getPatchbayConnections(true)
  2117. : nullptr;
  2118. const PatchbayPosition* const patchbayPos = saveExternalPositions
  2119. ? getPatchbayPositions(true, posCount)
  2120. : nullptr;
  2121. if (patchbayConns != nullptr || patchbayPos != nullptr)
  2122. {
  2123. MemoryOutputStream outPatchbay(2048);
  2124. outPatchbay << "\n <ExternalPatchbay>\n";
  2125. if (patchbayConns != nullptr)
  2126. {
  2127. for (int i=0; patchbayConns[i] != nullptr && patchbayConns[i+1] != nullptr; ++i, ++i )
  2128. {
  2129. const char* const connSource(patchbayConns[i]);
  2130. const char* const connTarget(patchbayConns[i+1]);
  2131. CARLA_SAFE_ASSERT_CONTINUE(connSource != nullptr && connSource[0] != '\0');
  2132. CARLA_SAFE_ASSERT_CONTINUE(connTarget != nullptr && connTarget[0] != '\0');
  2133. outPatchbay << " <Connection>\n";
  2134. outPatchbay << " <Source>" << xmlSafeString(connSource, true) << "</Source>\n";
  2135. outPatchbay << " <Target>" << xmlSafeString(connTarget, true) << "</Target>\n";
  2136. outPatchbay << " </Connection>\n";
  2137. }
  2138. }
  2139. if (patchbayPos != nullptr && posCount != 0)
  2140. {
  2141. outPatchbay << " <Positions>\n";
  2142. for (uint i=0; i<posCount; ++i)
  2143. {
  2144. const PatchbayPosition& ppos(patchbayPos[i]);
  2145. CARLA_SAFE_ASSERT_CONTINUE(ppos.name != nullptr && ppos.name[0] != '\0');
  2146. outPatchbay << " <Position x1=\"" << ppos.x1 << "\" y1=\"" << ppos.y1;
  2147. if (ppos.x2 != 0 || ppos.y2 != 0)
  2148. outPatchbay << "\" x2=\"" << ppos.x2 << "\" y2=\"" << ppos.y2;
  2149. if (ppos.pluginId >= 0)
  2150. outPatchbay << "\" pluginId=\"" << ppos.pluginId;
  2151. outPatchbay << "\">\n";
  2152. outPatchbay << " <Name>" << xmlSafeString(ppos.name, true) << "</Name>\n";
  2153. outPatchbay << " </Position>\n";
  2154. if (ppos.dealloc)
  2155. delete[] ppos.name;
  2156. }
  2157. outPatchbay << " </Positions>\n";
  2158. }
  2159. outPatchbay << " </ExternalPatchbay>\n";
  2160. outStream << outPatchbay;
  2161. }
  2162. }
  2163. #endif
  2164. outStream << "</CARLA-PROJECT>\n";
  2165. }
  2166. static String findBinaryInCustomPath(const char* const searchPath, const char* const binary)
  2167. {
  2168. const StringArray searchPaths(StringArray::fromTokens(searchPath, CARLA_OS_SPLIT_STR, ""));
  2169. // try direct filename first
  2170. String jbinary(binary);
  2171. // adjust for current platform
  2172. #ifdef CARLA_OS_WIN
  2173. if (jbinary[0] == '/')
  2174. jbinary = "C:" + jbinary.replaceCharacter('/', '\\');
  2175. #else
  2176. if (jbinary[1] == ':' && (jbinary[2] == '\\' || jbinary[2] == '/'))
  2177. jbinary = jbinary.substring(2).replaceCharacter('\\', '/');
  2178. #endif
  2179. String filename = File(jbinary).getFileName();
  2180. int searchFlags = File::findFiles|File::ignoreHiddenFiles;
  2181. if (filename.endsWithIgnoreCase(".vst3"))
  2182. searchFlags |= File::findDirectories;
  2183. #ifdef CARLA_OS_MAC
  2184. else if (filename.endsWithIgnoreCase(".vst"))
  2185. searchFlags |= File::findDirectories;
  2186. #endif
  2187. std::vector<File> results;
  2188. for (const String *it=searchPaths.begin(), *end=searchPaths.end(); it != end; ++it)
  2189. {
  2190. const File path(*it);
  2191. results.clear();
  2192. path.findChildFiles(results, searchFlags, true, filename);
  2193. if (!results.empty())
  2194. return results.front().getFullPathName();
  2195. }
  2196. // try changing extension
  2197. #if defined(CARLA_OS_MAC)
  2198. if (filename.endsWithIgnoreCase(".dll") || filename.endsWithIgnoreCase(".so"))
  2199. filename = File(jbinary).getFileNameWithoutExtension() + ".dylib";
  2200. #elif defined(CARLA_OS_WIN)
  2201. if (filename.endsWithIgnoreCase(".dylib") || filename.endsWithIgnoreCase(".so"))
  2202. filename = File(jbinary).getFileNameWithoutExtension() + ".dll";
  2203. #else
  2204. if (filename.endsWithIgnoreCase(".dll") || filename.endsWithIgnoreCase(".dylib"))
  2205. filename = File(jbinary).getFileNameWithoutExtension() + ".so";
  2206. #endif
  2207. else
  2208. return String();
  2209. for (const String *it=searchPaths.begin(), *end=searchPaths.end(); it != end; ++it)
  2210. {
  2211. const File path(*it);
  2212. results.clear();
  2213. path.findChildFiles(results, searchFlags, true, filename);
  2214. if (!results.empty())
  2215. return results.front().getFullPathName();
  2216. }
  2217. return String();
  2218. }
  2219. bool CarlaEngine::loadProjectInternal(water::XmlDocument& xmlDoc, const bool alwaysLoadConnections)
  2220. {
  2221. carla_debug("CarlaEngine::loadProjectInternal(%p, %s) - START", &xmlDoc, bool2str(alwaysLoadConnections));
  2222. CarlaScopedPointer<XmlElement> xmlElement(xmlDoc.getDocumentElement(true));
  2223. CARLA_SAFE_ASSERT_RETURN_ERR(xmlElement != nullptr, "Failed to parse project file");
  2224. const String& xmlType(xmlElement->getTagName());
  2225. const bool isPreset(xmlType.equalsIgnoreCase("carla-preset"));
  2226. if (! (xmlType.equalsIgnoreCase("carla-project") || isPreset))
  2227. {
  2228. callback(true, true, ENGINE_CALLBACK_PROJECT_LOAD_FINISHED, 0, 0, 0, 0, 0.0f, nullptr);
  2229. setLastError("Not a valid Carla project or preset file");
  2230. return false;
  2231. }
  2232. pData->actionCanceled = false;
  2233. callback(true, true, ENGINE_CALLBACK_CANCELABLE_ACTION, 0, 1, 0, 0, 0.0f, "Loading project");
  2234. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2235. if (pData->options.clientNamePrefix != nullptr)
  2236. {
  2237. if (carla_isEqual(xmlElement->getDoubleAttribute("VERSION", 0.0), 2.0) ||
  2238. xmlElement->getBoolAttribute("IgnoreClientPrefix", false))
  2239. {
  2240. carla_stdout("Loading project in compatibility mode, will ignore client name prefix");
  2241. pData->ignoreClientPrefix = true;
  2242. setOption(ENGINE_OPTION_CLIENT_NAME_PREFIX, 0, "");
  2243. }
  2244. }
  2245. const CarlaScopedValueSetter<bool> csvs(pData->loadingProject, true, false);
  2246. #endif
  2247. // completely load file
  2248. xmlElement = xmlDoc.getDocumentElement(false);
  2249. CARLA_SAFE_ASSERT_RETURN_ERR(xmlElement != nullptr, "Failed to completely parse project file");
  2250. if (pData->aboutToClose)
  2251. return true;
  2252. if (pData->actionCanceled)
  2253. {
  2254. setLastError("Project load canceled");
  2255. return false;
  2256. }
  2257. callback(true, false, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  2258. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2259. const bool isMultiClient = pData->options.processMode == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS;
  2260. const bool isPatchbay = pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY;
  2261. #endif
  2262. const bool isPlugin = getType() == kEngineTypePlugin;
  2263. // load engine settings first of all
  2264. if (XmlElement* const elem = isPreset ? nullptr : xmlElement->getChildByName("EngineSettings"))
  2265. {
  2266. for (XmlElement* settElem = elem->getFirstChildElement(); settElem != nullptr; settElem = settElem->getNextElement())
  2267. {
  2268. const String& tag(settElem->getTagName());
  2269. const String text(settElem->getAllSubText().trim());
  2270. /** some settings might be incorrect or require extra work,
  2271. so we call setOption rather than modifying them direly */
  2272. int option = -1;
  2273. int value = 0;
  2274. const char* valueStr = nullptr;
  2275. /**/ if (tag == "ForceStereo")
  2276. {
  2277. option = ENGINE_OPTION_FORCE_STEREO;
  2278. value = text == "true" ? 1 : 0;
  2279. }
  2280. else if (tag == "PreferPluginBridges")
  2281. {
  2282. option = ENGINE_OPTION_PREFER_PLUGIN_BRIDGES;
  2283. value = text == "true" ? 1 : 0;
  2284. }
  2285. else if (tag == "PreferUiBridges")
  2286. {
  2287. option = ENGINE_OPTION_PREFER_UI_BRIDGES;
  2288. value = text == "true" ? 1 : 0;
  2289. }
  2290. else if (tag == "UIsAlwaysOnTop")
  2291. {
  2292. option = ENGINE_OPTION_UIS_ALWAYS_ON_TOP;
  2293. value = text == "true" ? 1 : 0;
  2294. }
  2295. else if (tag == "MaxParameters")
  2296. {
  2297. option = ENGINE_OPTION_MAX_PARAMETERS;
  2298. value = text.getIntValue();
  2299. }
  2300. else if (tag == "UIBridgesTimeout")
  2301. {
  2302. option = ENGINE_OPTION_UI_BRIDGES_TIMEOUT;
  2303. value = text.getIntValue();
  2304. }
  2305. else if (isPlugin)
  2306. {
  2307. /**/ if (tag == "LADSPA_PATH")
  2308. {
  2309. option = ENGINE_OPTION_PLUGIN_PATH;
  2310. value = PLUGIN_LADSPA;
  2311. valueStr = text.toRawUTF8();
  2312. }
  2313. else if (tag == "DSSI_PATH")
  2314. {
  2315. option = ENGINE_OPTION_PLUGIN_PATH;
  2316. value = PLUGIN_DSSI;
  2317. valueStr = text.toRawUTF8();
  2318. }
  2319. else if (tag == "LV2_PATH")
  2320. {
  2321. option = ENGINE_OPTION_PLUGIN_PATH;
  2322. value = PLUGIN_LV2;
  2323. valueStr = text.toRawUTF8();
  2324. }
  2325. else if (tag == "VST2_PATH")
  2326. {
  2327. option = ENGINE_OPTION_PLUGIN_PATH;
  2328. value = PLUGIN_VST2;
  2329. valueStr = text.toRawUTF8();
  2330. }
  2331. else if (tag.equalsIgnoreCase("VST3_PATH"))
  2332. {
  2333. option = ENGINE_OPTION_PLUGIN_PATH;
  2334. value = PLUGIN_VST3;
  2335. valueStr = text.toRawUTF8();
  2336. }
  2337. else if (tag == "SF2_PATH")
  2338. {
  2339. option = ENGINE_OPTION_PLUGIN_PATH;
  2340. value = PLUGIN_SF2;
  2341. valueStr = text.toRawUTF8();
  2342. }
  2343. else if (tag == "SFZ_PATH")
  2344. {
  2345. option = ENGINE_OPTION_PLUGIN_PATH;
  2346. value = PLUGIN_SFZ;
  2347. valueStr = text.toRawUTF8();
  2348. }
  2349. else if (tag == "JSFX_PATH")
  2350. {
  2351. option = ENGINE_OPTION_PLUGIN_PATH;
  2352. value = PLUGIN_JSFX;
  2353. valueStr = text.toRawUTF8();
  2354. }
  2355. else if (tag == "CLAP_PATH")
  2356. {
  2357. option = ENGINE_OPTION_PLUGIN_PATH;
  2358. value = PLUGIN_CLAP;
  2359. valueStr = text.toRawUTF8();
  2360. }
  2361. }
  2362. if (option == -1)
  2363. {
  2364. // check old stuff, unhandled now
  2365. if (tag == "GIG_PATH")
  2366. continue;
  2367. // ignored tags
  2368. if (tag == "LADSPA_PATH" || tag == "DSSI_PATH" || tag == "LV2_PATH" || tag == "VST2_PATH")
  2369. continue;
  2370. if (tag == "VST3_PATH" || tag == "AU_PATH")
  2371. continue;
  2372. if (tag == "SF2_PATH" || tag == "SFZ_PATH" || tag == "JSFX_PATH" || tag == "CLAP_PATH")
  2373. continue;
  2374. // hmm something is wrong..
  2375. carla_stderr2("CarlaEngine::loadProjectInternal() - Unhandled option '%s'", tag.toRawUTF8());
  2376. continue;
  2377. }
  2378. setOption(static_cast<EngineOption>(option), value, valueStr);
  2379. }
  2380. if (pData->aboutToClose)
  2381. return true;
  2382. if (pData->actionCanceled)
  2383. {
  2384. setLastError("Project load canceled");
  2385. return false;
  2386. }
  2387. }
  2388. // now setup transport
  2389. if (XmlElement* const elem = (isPreset || isPlugin) ? nullptr : xmlElement->getChildByName("Transport"))
  2390. {
  2391. if (XmlElement* const bpmElem = elem->getChildByName("BeatsPerMinute"))
  2392. {
  2393. const String bpmText(bpmElem->getAllSubText().trim());
  2394. const double bpm = bpmText.getDoubleValue();
  2395. // some sane limits
  2396. if (bpm >= 20.0 && bpm < 400.0)
  2397. pData->time.setBPM(bpm);
  2398. if (pData->aboutToClose)
  2399. return true;
  2400. if (pData->actionCanceled)
  2401. {
  2402. setLastError("Project load canceled");
  2403. return false;
  2404. }
  2405. }
  2406. }
  2407. // and we handle plugins
  2408. for (XmlElement* elem = xmlElement->getFirstChildElement(); elem != nullptr; elem = elem->getNextElement())
  2409. {
  2410. const String& tagName(elem->getTagName());
  2411. if (isPreset || tagName == "Plugin")
  2412. {
  2413. CarlaStateSave stateSave;
  2414. stateSave.fillFromXmlElement(isPreset ? xmlElement.get() : elem);
  2415. if (pData->aboutToClose)
  2416. return true;
  2417. if (pData->actionCanceled)
  2418. {
  2419. setLastError("Project load canceled");
  2420. return false;
  2421. }
  2422. CARLA_SAFE_ASSERT_CONTINUE(stateSave.type != nullptr);
  2423. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2424. // compatibility code to load projects with GIG files
  2425. // FIXME Remove on 2.1 release
  2426. if (std::strcmp(stateSave.type, "GIG") == 0)
  2427. {
  2428. if (addPlugin(PLUGIN_LV2, "", stateSave.name, "http://linuxsampler.org/plugins/linuxsampler", 0, nullptr))
  2429. {
  2430. const uint pluginId = pData->curPluginCount;
  2431. if (const CarlaPluginPtr plugin = pData->plugins[pluginId].plugin)
  2432. {
  2433. if (pData->aboutToClose)
  2434. return true;
  2435. if (pData->actionCanceled)
  2436. {
  2437. setLastError("Project load canceled");
  2438. return false;
  2439. }
  2440. String lsState;
  2441. lsState << "0.35\n";
  2442. lsState << "18 0 Chromatic\n";
  2443. lsState << "18 1 Drum Kits\n";
  2444. lsState << "20 0\n";
  2445. lsState << "0 1 " << stateSave.binary << "\n";
  2446. lsState << "0 0 0 0 1 0 GIG\n";
  2447. plugin->setCustomData(LV2_ATOM__String, "http://linuxsampler.org/schema#state-string", lsState.toRawUTF8(), true);
  2448. plugin->restoreLV2State(true);
  2449. plugin->setDryWet(stateSave.dryWet, true, true);
  2450. plugin->setVolume(stateSave.volume, true, true);
  2451. plugin->setBalanceLeft(stateSave.balanceLeft, true, true);
  2452. plugin->setBalanceRight(stateSave.balanceRight, true, true);
  2453. plugin->setPanning(stateSave.panning, true, true);
  2454. plugin->setCtrlChannel(stateSave.ctrlChannel, true, true);
  2455. plugin->setActive(stateSave.active, true, true);
  2456. plugin->setEnabled(true);
  2457. ++pData->curPluginCount;
  2458. callback(true, true, ENGINE_CALLBACK_PLUGIN_ADDED, pluginId, plugin->getType(),
  2459. 0, 0, 0.0f,
  2460. plugin->getName());
  2461. if (isPatchbay)
  2462. pData->graph.addPlugin(plugin);
  2463. }
  2464. else
  2465. {
  2466. carla_stderr2("Failed to get new plugin, state will not be restored correctly\n");
  2467. }
  2468. }
  2469. else
  2470. {
  2471. carla_stderr2("Failed to load a linuxsampler LV2 plugin, GIG file won't be loaded");
  2472. }
  2473. callback(true, true, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  2474. continue;
  2475. }
  2476. # ifdef SFZ_FILES_USING_SFIZZ
  2477. if (std::strcmp(stateSave.type, "SFZ") == 0)
  2478. {
  2479. if (addPlugin(PLUGIN_LV2, "", stateSave.name, "http://sfztools.github.io/sfizz", 0, nullptr))
  2480. {
  2481. const uint pluginId = pData->curPluginCount;
  2482. if (const CarlaPluginPtr plugin = pData->plugins[pluginId].plugin)
  2483. {
  2484. if (pData->aboutToClose)
  2485. return true;
  2486. if (pData->actionCanceled)
  2487. {
  2488. setLastError("Project load canceled");
  2489. return false;
  2490. }
  2491. plugin->setCustomData(LV2_ATOM__Path,
  2492. "http://sfztools.github.io/sfizz:sfzfile",
  2493. stateSave.binary,
  2494. false);
  2495. plugin->restoreLV2State(true);
  2496. plugin->setDryWet(stateSave.dryWet, true, true);
  2497. plugin->setVolume(stateSave.volume, true, true);
  2498. plugin->setBalanceLeft(stateSave.balanceLeft, true, true);
  2499. plugin->setBalanceRight(stateSave.balanceRight, true, true);
  2500. plugin->setPanning(stateSave.panning, true, true);
  2501. plugin->setCtrlChannel(stateSave.ctrlChannel, true, true);
  2502. plugin->setActive(stateSave.active, true, true);
  2503. plugin->setEnabled(true);
  2504. ++pData->curPluginCount;
  2505. callback(true, true, ENGINE_CALLBACK_PLUGIN_ADDED, pluginId, plugin->getType(),
  2506. 0, 0, 0.0f,
  2507. plugin->getName());
  2508. if (isPatchbay)
  2509. pData->graph.addPlugin(plugin);
  2510. }
  2511. else
  2512. {
  2513. carla_stderr2("Failed to get new plugin, state will not be restored correctly\n");
  2514. }
  2515. }
  2516. else
  2517. {
  2518. carla_stderr2("Failed to load a sfizz LV2 plugin, SFZ file won't be loaded");
  2519. }
  2520. callback(true, true, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  2521. continue;
  2522. }
  2523. # endif
  2524. #endif
  2525. const void* extraStuff = nullptr;
  2526. static const char kTrue[] = "true";
  2527. const PluginType ptype = getPluginTypeFromString(stateSave.type);
  2528. switch (ptype)
  2529. {
  2530. case PLUGIN_SF2:
  2531. if (CarlaString(stateSave.label).endsWith(" (16 outs)"))
  2532. extraStuff = kTrue;
  2533. // fall through
  2534. case PLUGIN_LADSPA:
  2535. case PLUGIN_DSSI:
  2536. case PLUGIN_VST2:
  2537. case PLUGIN_VST3:
  2538. case PLUGIN_SFZ:
  2539. case PLUGIN_JSFX:
  2540. case PLUGIN_CLAP:
  2541. if (stateSave.binary != nullptr && stateSave.binary[0] != '\0' &&
  2542. ! (File::isAbsolutePath(stateSave.binary) && File(stateSave.binary).exists()))
  2543. {
  2544. const char* searchPath;
  2545. switch (ptype)
  2546. {
  2547. case PLUGIN_LADSPA: searchPath = pData->options.pathLADSPA; break;
  2548. case PLUGIN_DSSI: searchPath = pData->options.pathDSSI; break;
  2549. case PLUGIN_VST2: searchPath = pData->options.pathVST2; break;
  2550. case PLUGIN_VST3: searchPath = pData->options.pathVST3; break;
  2551. case PLUGIN_SF2: searchPath = pData->options.pathSF2; break;
  2552. case PLUGIN_SFZ: searchPath = pData->options.pathSFZ; break;
  2553. case PLUGIN_JSFX: searchPath = pData->options.pathJSFX; break;
  2554. case PLUGIN_CLAP: searchPath = pData->options.pathCLAP; break;
  2555. default: searchPath = nullptr; break;
  2556. }
  2557. if (searchPath != nullptr && searchPath[0] != '\0')
  2558. {
  2559. carla_stderr("Plugin binary '%s' doesn't exist on this filesystem, let's look for it...",
  2560. stateSave.binary);
  2561. String result = findBinaryInCustomPath(searchPath, stateSave.binary);
  2562. if (result.isEmpty())
  2563. {
  2564. switch (ptype)
  2565. {
  2566. case PLUGIN_LADSPA: searchPath = std::getenv("LADSPA_PATH"); break;
  2567. case PLUGIN_DSSI: searchPath = std::getenv("DSSI_PATH"); break;
  2568. case PLUGIN_VST2: searchPath = std::getenv("VST_PATH"); break;
  2569. case PLUGIN_VST3: searchPath = std::getenv("VST3_PATH"); break;
  2570. case PLUGIN_SF2: searchPath = std::getenv("SF2_PATH"); break;
  2571. case PLUGIN_SFZ: searchPath = std::getenv("SFZ_PATH"); break;
  2572. case PLUGIN_JSFX: searchPath = std::getenv("JSFX_PATH"); break;
  2573. case PLUGIN_CLAP: searchPath = std::getenv("CLAP_PATH"); break;
  2574. default: searchPath = nullptr; break;
  2575. }
  2576. if (searchPath != nullptr && searchPath[0] != '\0')
  2577. result = findBinaryInCustomPath(searchPath, stateSave.binary);
  2578. }
  2579. if (result.isNotEmpty())
  2580. {
  2581. delete[] stateSave.binary;
  2582. stateSave.binary = carla_strdup(result.toRawUTF8());
  2583. carla_stderr("Found it! :)");
  2584. }
  2585. else
  2586. {
  2587. carla_stderr("Damn, we failed... :(");
  2588. }
  2589. callback(true, true, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  2590. }
  2591. }
  2592. break;
  2593. default:
  2594. break;
  2595. }
  2596. BinaryType btype;
  2597. switch (ptype)
  2598. {
  2599. case PLUGIN_LADSPA:
  2600. case PLUGIN_DSSI:
  2601. case PLUGIN_LV2:
  2602. case PLUGIN_VST2:
  2603. case PLUGIN_VST3:
  2604. case PLUGIN_CLAP:
  2605. btype = getBinaryTypeFromFile(stateSave.binary);
  2606. break;
  2607. default:
  2608. btype = BINARY_NATIVE;
  2609. break;
  2610. }
  2611. if (addPlugin(btype, ptype, stateSave.binary,
  2612. stateSave.name, stateSave.label, stateSave.uniqueId, extraStuff, stateSave.options))
  2613. {
  2614. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2615. const uint pluginId = pData->curPluginCount;
  2616. #else
  2617. const uint pluginId = 0;
  2618. #endif
  2619. if (const CarlaPluginPtr plugin = pData->plugins[pluginId].plugin)
  2620. {
  2621. if (pData->aboutToClose)
  2622. return true;
  2623. if (pData->actionCanceled)
  2624. {
  2625. setLastError("Project load canceled");
  2626. return false;
  2627. }
  2628. // deactivate bridge client-side ping check, since some plugins block during load
  2629. if ((plugin->getHints() & PLUGIN_IS_BRIDGE) != 0 && ! isPreset)
  2630. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "false", false);
  2631. plugin->loadStateSave(stateSave);
  2632. /* NOTE: The following code is the same as the end of addPlugin().
  2633. * When project is loading we do not enable the plugin right away,
  2634. * as we want to load state first.
  2635. */
  2636. plugin->setEnabled(true);
  2637. ++pData->curPluginCount;
  2638. callback(true, true, ENGINE_CALLBACK_PLUGIN_ADDED, pluginId, plugin->getType(),
  2639. 0, 0, 0.0f,
  2640. plugin->getName());
  2641. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2642. if (isPatchbay)
  2643. pData->graph.addPlugin(plugin);
  2644. #endif
  2645. }
  2646. else
  2647. {
  2648. carla_stderr2("Failed to get new plugin, state will not be restored correctly\n");
  2649. }
  2650. }
  2651. else
  2652. {
  2653. carla_stderr2("Failed to load a plugin '%s', error was:\n%s", stateSave.name, getLastError());
  2654. }
  2655. if (! isPreset)
  2656. callback(true, true, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  2657. }
  2658. if (isPreset)
  2659. {
  2660. callback(true, true, ENGINE_CALLBACK_PROJECT_LOAD_FINISHED, 0, 0, 0, 0, 0.0f, nullptr);
  2661. callback(true, true, ENGINE_CALLBACK_CANCELABLE_ACTION, 0, 0, 0, 0, 0.0f, "Loading project");
  2662. return true;
  2663. }
  2664. }
  2665. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2666. // tell bridges we're done loading
  2667. for (uint i=0; i < pData->curPluginCount; ++i)
  2668. {
  2669. if (const CarlaPluginPtr plugin = pData->plugins[i].plugin)
  2670. if (plugin->isEnabled() && (plugin->getHints() & PLUGIN_IS_BRIDGE) != 0)
  2671. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "true", false);
  2672. }
  2673. if (pData->aboutToClose)
  2674. return true;
  2675. if (pData->actionCanceled)
  2676. {
  2677. setLastError("Project load canceled");
  2678. return false;
  2679. }
  2680. // now we handle positions
  2681. bool loadingAsExternal;
  2682. std::map<water::String, water::String> mapGroupNamesInternal, mapGroupNamesExternal;
  2683. bool hasInternalPositions = false;
  2684. if (XmlElement* const elemPatchbay = xmlElement->getChildByName("Patchbay"))
  2685. {
  2686. hasInternalPositions = true;
  2687. if (XmlElement* const elemPositions = elemPatchbay->getChildByName("Positions"))
  2688. {
  2689. String name;
  2690. PatchbayPosition ppos = { nullptr, -1, 0, 0, 0, 0, false };
  2691. for (XmlElement* patchElem = elemPositions->getFirstChildElement(); patchElem != nullptr; patchElem = patchElem->getNextElement())
  2692. {
  2693. const String& patchTag(patchElem->getTagName());
  2694. if (patchTag != "Position")
  2695. continue;
  2696. XmlElement* const patchName = patchElem->getChildByName("Name");
  2697. CARLA_SAFE_ASSERT_CONTINUE(patchName != nullptr);
  2698. const String nameText(patchName->getAllSubText().trim());
  2699. name = xmlSafeString(nameText, false);
  2700. ppos.name = name.toRawUTF8();
  2701. ppos.x1 = patchElem->getIntAttribute("x1");
  2702. ppos.y1 = patchElem->getIntAttribute("y1");
  2703. ppos.x2 = patchElem->getIntAttribute("x2");
  2704. ppos.y2 = patchElem->getIntAttribute("y2");
  2705. ppos.pluginId = patchElem->getIntAttribute("pluginId", -1);
  2706. ppos.dealloc = false;
  2707. loadingAsExternal = ppos.pluginId >= 0 && isMultiClient;
  2708. if (name.isNotEmpty() && restorePatchbayGroupPosition(loadingAsExternal, ppos))
  2709. {
  2710. if (name != ppos.name)
  2711. {
  2712. carla_stdout("Converted client name '%s' to '%s' for this session",
  2713. name.toRawUTF8(), ppos.name);
  2714. if (loadingAsExternal)
  2715. mapGroupNamesExternal[name] = ppos.name;
  2716. else
  2717. mapGroupNamesInternal[name] = ppos.name;
  2718. }
  2719. if (ppos.dealloc)
  2720. std::free(const_cast<char*>(ppos.name));
  2721. }
  2722. }
  2723. if (pData->aboutToClose)
  2724. return true;
  2725. if (pData->actionCanceled)
  2726. {
  2727. setLastError("Project load canceled");
  2728. return false;
  2729. }
  2730. }
  2731. }
  2732. if (XmlElement* const elemPatchbay = xmlElement->getChildByName("ExternalPatchbay"))
  2733. {
  2734. if (XmlElement* const elemPositions = elemPatchbay->getChildByName("Positions"))
  2735. {
  2736. String name;
  2737. PatchbayPosition ppos = { nullptr, -1, 0, 0, 0, 0, false };
  2738. for (XmlElement* patchElem = elemPositions->getFirstChildElement(); patchElem != nullptr; patchElem = patchElem->getNextElement())
  2739. {
  2740. const String& patchTag(patchElem->getTagName());
  2741. if (patchTag != "Position")
  2742. continue;
  2743. XmlElement* const patchName = patchElem->getChildByName("Name");
  2744. CARLA_SAFE_ASSERT_CONTINUE(patchName != nullptr);
  2745. const String nameText(patchName->getAllSubText().trim());
  2746. name = xmlSafeString(nameText, false);
  2747. ppos.name = name.toRawUTF8();
  2748. ppos.x1 = patchElem->getIntAttribute("x1");
  2749. ppos.y1 = patchElem->getIntAttribute("y1");
  2750. ppos.x2 = patchElem->getIntAttribute("x2");
  2751. ppos.y2 = patchElem->getIntAttribute("y2");
  2752. ppos.pluginId = patchElem->getIntAttribute("pluginId", -1);
  2753. ppos.dealloc = false;
  2754. loadingAsExternal = ppos.pluginId < 0 || hasInternalPositions || !isPatchbay;
  2755. carla_debug("loadingAsExternal: %i because %i %i %i",
  2756. loadingAsExternal, ppos.pluginId < 0, hasInternalPositions, !isPatchbay);
  2757. if (name.isNotEmpty() && restorePatchbayGroupPosition(loadingAsExternal, ppos))
  2758. {
  2759. if (name != ppos.name)
  2760. {
  2761. carla_stdout("Converted client name '%s' to '%s' for this session",
  2762. name.toRawUTF8(), ppos.name);
  2763. if (loadingAsExternal)
  2764. mapGroupNamesExternal[name] = ppos.name;
  2765. else
  2766. mapGroupNamesInternal[name] = ppos.name;
  2767. }
  2768. if (ppos.dealloc)
  2769. std::free(const_cast<char*>(ppos.name));
  2770. }
  2771. }
  2772. if (pData->aboutToClose)
  2773. return true;
  2774. if (pData->actionCanceled)
  2775. {
  2776. setLastError("Project load canceled");
  2777. return false;
  2778. }
  2779. }
  2780. }
  2781. bool hasInternalConnections = false;
  2782. // and now we handle connections (internal)
  2783. if (XmlElement* const elem = xmlElement->getChildByName("Patchbay"))
  2784. {
  2785. hasInternalConnections = true;
  2786. if (isPatchbay)
  2787. {
  2788. water::String sourcePort, targetPort;
  2789. for (XmlElement* patchElem = elem->getFirstChildElement(); patchElem != nullptr; patchElem = patchElem->getNextElement())
  2790. {
  2791. const String& patchTag(patchElem->getTagName());
  2792. if (patchTag != "Connection")
  2793. continue;
  2794. sourcePort.clear();
  2795. targetPort.clear();
  2796. for (XmlElement* connElem = patchElem->getFirstChildElement(); connElem != nullptr; connElem = connElem->getNextElement())
  2797. {
  2798. const String& tag(connElem->getTagName());
  2799. const String text(connElem->getAllSubText().trim());
  2800. /**/ if (tag == "Source")
  2801. sourcePort = xmlSafeString(text, false);
  2802. else if (tag == "Target")
  2803. targetPort = xmlSafeString(text, false);
  2804. }
  2805. if (sourcePort.isNotEmpty() && targetPort.isNotEmpty())
  2806. {
  2807. std::map<water::String, water::String>& map(mapGroupNamesInternal);
  2808. std::map<water::String, water::String>::iterator it;
  2809. if ((it = map.find(sourcePort.upToFirstOccurrenceOf(":", false, false))) != map.end())
  2810. sourcePort = it->second + sourcePort.fromFirstOccurrenceOf(":", true, false);
  2811. if ((it = map.find(targetPort.upToFirstOccurrenceOf(":", false, false))) != map.end())
  2812. targetPort = it->second + targetPort.fromFirstOccurrenceOf(":", true, false);
  2813. restorePatchbayConnection(false, sourcePort.toRawUTF8(), targetPort.toRawUTF8());
  2814. }
  2815. }
  2816. if (pData->aboutToClose)
  2817. return true;
  2818. if (pData->actionCanceled)
  2819. {
  2820. setLastError("Project load canceled");
  2821. return false;
  2822. }
  2823. }
  2824. }
  2825. // if we're running inside some session-manager (and using JACK), let them handle the external connections
  2826. bool loadExternalConnections;
  2827. if (alwaysLoadConnections)
  2828. {
  2829. loadExternalConnections = true;
  2830. }
  2831. else
  2832. {
  2833. /**/ if (std::strcmp(getCurrentDriverName(), "JACK") != 0)
  2834. loadExternalConnections = true;
  2835. else if (std::getenv("CARLA_DONT_MANAGE_CONNECTIONS") != nullptr)
  2836. loadExternalConnections = false;
  2837. else if (std::getenv("LADISH_APP_NAME") != nullptr)
  2838. loadExternalConnections = false;
  2839. else if (std::getenv("NSM_URL") != nullptr)
  2840. loadExternalConnections = false;
  2841. else
  2842. loadExternalConnections = true;
  2843. }
  2844. // plus external connections too
  2845. if (loadExternalConnections)
  2846. {
  2847. bool isExternal;
  2848. loadingAsExternal = hasInternalConnections &&
  2849. (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK || isPatchbay);
  2850. for (XmlElement* elem = xmlElement->getFirstChildElement(); elem != nullptr; elem = elem->getNextElement())
  2851. {
  2852. const String& tagName(elem->getTagName());
  2853. // check if we want to load patchbay-mode connections into an external (multi-client) graph
  2854. if (tagName == "Patchbay")
  2855. {
  2856. if (isPatchbay)
  2857. continue;
  2858. isExternal = false;
  2859. loadingAsExternal = true;
  2860. }
  2861. // or load external patchbay connections
  2862. else if (tagName == "ExternalPatchbay")
  2863. {
  2864. if (! isPatchbay)
  2865. loadingAsExternal = true;
  2866. isExternal = true;
  2867. }
  2868. else
  2869. {
  2870. continue;
  2871. }
  2872. water::String sourcePort, targetPort;
  2873. for (XmlElement* patchElem = elem->getFirstChildElement(); patchElem != nullptr; patchElem = patchElem->getNextElement())
  2874. {
  2875. const String& patchTag(patchElem->getTagName());
  2876. if (patchTag != "Connection")
  2877. continue;
  2878. sourcePort.clear();
  2879. targetPort.clear();
  2880. for (XmlElement* connElem = patchElem->getFirstChildElement(); connElem != nullptr; connElem = connElem->getNextElement())
  2881. {
  2882. const String& tag(connElem->getTagName());
  2883. const String text(connElem->getAllSubText().trim());
  2884. /**/ if (tag == "Source")
  2885. sourcePort = xmlSafeString(text, false);
  2886. else if (tag == "Target")
  2887. targetPort = xmlSafeString(text, false);
  2888. }
  2889. if (sourcePort.isNotEmpty() && targetPort.isNotEmpty())
  2890. {
  2891. std::map<water::String, water::String>& map(loadingAsExternal ? mapGroupNamesExternal
  2892. : mapGroupNamesInternal);
  2893. std::map<water::String, water::String>::iterator it;
  2894. if (isExternal && isPatchbay && !loadingAsExternal && sourcePort.startsWith("system:capture_"))
  2895. {
  2896. water::String internalPort = sourcePort.trimCharactersAtStart("system:capture_");
  2897. if (pData->graph.getNumAudioOuts() < 3)
  2898. {
  2899. /**/ if (internalPort == "1")
  2900. internalPort = "Audio Input:Left";
  2901. else if (internalPort == "2")
  2902. internalPort = "Audio Input:Right";
  2903. else if (internalPort == "3")
  2904. internalPort = "Audio Input:Sidechain";
  2905. else
  2906. continue;
  2907. }
  2908. else
  2909. {
  2910. internalPort = "Audio Input:Capture " + internalPort;
  2911. }
  2912. carla_stdout("Converted port name '%s' to '%s' for this session",
  2913. sourcePort.toRawUTF8(), internalPort.toRawUTF8());
  2914. sourcePort = internalPort;
  2915. }
  2916. else if (!isExternal && isMultiClient && sourcePort.startsWith("Audio Input:"))
  2917. {
  2918. water::String externalPort = sourcePort.trimCharactersAtStart("Audio Input:");
  2919. /**/ if (externalPort == "Left")
  2920. externalPort = "system:capture_1";
  2921. else if (externalPort == "Right")
  2922. externalPort = "system:capture_2";
  2923. else if (externalPort == "Sidechain")
  2924. externalPort = "system:capture_3";
  2925. else
  2926. externalPort = "system:capture_ " + externalPort.trimCharactersAtStart("Capture ");
  2927. carla_stdout("Converted port name '%s' to '%s' for this session",
  2928. sourcePort.toRawUTF8(), externalPort.toRawUTF8());
  2929. sourcePort = externalPort;
  2930. }
  2931. else if ((it = map.find(sourcePort.upToFirstOccurrenceOf(":", false, false))) != map.end())
  2932. {
  2933. sourcePort = it->second + sourcePort.fromFirstOccurrenceOf(":", true, false);
  2934. }
  2935. if (isExternal && isPatchbay && !loadingAsExternal && targetPort.startsWith("system:playback_"))
  2936. {
  2937. water::String internalPort = targetPort.trimCharactersAtStart("system:playback_");
  2938. if (pData->graph.getNumAudioOuts() < 3)
  2939. {
  2940. /**/ if (internalPort == "1")
  2941. internalPort = "Audio Output:Left";
  2942. else if (internalPort == "2")
  2943. internalPort = "Audio Output:Right";
  2944. else
  2945. continue;
  2946. }
  2947. else
  2948. {
  2949. internalPort = "Audio Input:Playback " + internalPort;
  2950. }
  2951. carla_stdout("Converted port name '%s' to '%s' for this session",
  2952. targetPort.toRawUTF8(), internalPort.toRawUTF8());
  2953. targetPort = internalPort;
  2954. }
  2955. else if (!isExternal && isMultiClient && targetPort.startsWith("Audio Output:"))
  2956. {
  2957. water::String externalPort = targetPort.trimCharactersAtStart("Audio Output:");
  2958. /**/ if (externalPort == "Left")
  2959. externalPort = "system:playback_1";
  2960. else if (externalPort == "Right")
  2961. externalPort = "system:playback_2";
  2962. else
  2963. externalPort = "system:playback_ " + externalPort.trimCharactersAtStart("Playback ");
  2964. carla_stdout("Converted port name '%s' to '%s' for this session",
  2965. targetPort.toRawUTF8(), externalPort.toRawUTF8());
  2966. targetPort = externalPort;
  2967. }
  2968. else if ((it = map.find(targetPort.upToFirstOccurrenceOf(":", false, false))) != map.end())
  2969. {
  2970. targetPort = it->second + targetPort.fromFirstOccurrenceOf(":", true, false);
  2971. }
  2972. restorePatchbayConnection(loadingAsExternal, sourcePort.toRawUTF8(), targetPort.toRawUTF8());
  2973. }
  2974. }
  2975. break;
  2976. }
  2977. }
  2978. #endif
  2979. if (pData->options.resetXruns)
  2980. clearXruns();
  2981. callback(true, true, ENGINE_CALLBACK_PROJECT_LOAD_FINISHED, 0, 0, 0, 0, 0.0f, nullptr);
  2982. callback(true, true, ENGINE_CALLBACK_CANCELABLE_ACTION, 0, 0, 0, 0, 0.0f, "Loading project");
  2983. carla_debug("CarlaEngine::loadProjectInternal(%p, %s) - END", &xmlDoc, bool2str(alwaysLoadConnections));
  2984. return true;
  2985. #ifdef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2986. // unused
  2987. (void)alwaysLoadConnections;
  2988. #endif
  2989. }
  2990. // -----------------------------------------------------------------------
  2991. CARLA_BACKEND_END_NAMESPACE