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.

3568 lines
122KB

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