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.

3569 lines
121KB

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