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.

2554 lines
85KB

  1. /*
  2. * Carla Plugin Host
  3. * Copyright (C) 2011-2018 Filipe Coelho <falktx@falktx.com>
  4. *
  5. * This program is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU General Public License as
  7. * published by the Free Software Foundation; either version 2 of
  8. * the License, or any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * For a full copy of the GNU General Public License see the doc/GPL.txt file.
  16. */
  17. /* TODO:
  18. * - complete processRack(): carefully add to input, sorted events
  19. * - implement processPatchbay()
  20. * - implement oscSend_control_switch_plugins()
  21. * - something about the peaks?
  22. */
  23. #include "CarlaEngineInternal.hpp"
  24. #include "CarlaPlugin.hpp"
  25. #include "CarlaBackendUtils.hpp"
  26. #include "CarlaBinaryUtils.hpp"
  27. #include "CarlaEngineUtils.hpp"
  28. #include "CarlaMathUtils.hpp"
  29. #include "CarlaPipeUtils.hpp"
  30. #include "CarlaStateUtils.hpp"
  31. #include "CarlaMIDI.h"
  32. #include "jackbridge/JackBridge.hpp"
  33. #include "water/files/File.h"
  34. #include "water/streams/MemoryOutputStream.h"
  35. #include "water/xml/XmlDocument.h"
  36. #include "water/xml/XmlElement.h"
  37. // FIXME Remove on 2.1 release
  38. #include "lv2/atom.h"
  39. using water::Array;
  40. using water::CharPointer_UTF8;
  41. using water::File;
  42. using water::MemoryOutputStream;
  43. using water::String;
  44. using water::StringArray;
  45. using water::XmlDocument;
  46. using water::XmlElement;
  47. CARLA_BACKEND_START_NAMESPACE
  48. // -----------------------------------------------------------------------
  49. // Carla Engine
  50. CarlaEngine::CarlaEngine()
  51. : pData(new ProtectedData(this))
  52. {
  53. carla_debug("CarlaEngine::CarlaEngine()");
  54. }
  55. CarlaEngine::~CarlaEngine()
  56. {
  57. carla_debug("CarlaEngine::~CarlaEngine()");
  58. delete pData;
  59. }
  60. // -----------------------------------------------------------------------
  61. // Static calls
  62. uint CarlaEngine::getDriverCount()
  63. {
  64. carla_debug("CarlaEngine::getDriverCount()");
  65. uint count = 0;
  66. if (jackbridge_is_ok())
  67. count += 1;
  68. #ifndef BUILD_BRIDGE
  69. # ifdef USING_JUCE
  70. count += getJuceApiCount();
  71. # else
  72. count += getRtAudioApiCount();
  73. # endif
  74. #endif
  75. return count;
  76. }
  77. const char* CarlaEngine::getDriverName(const uint index2)
  78. {
  79. carla_debug("CarlaEngine::getDriverName(%i)", index2);
  80. uint index = index2;
  81. if (jackbridge_is_ok() && index-- == 0)
  82. return "JACK";
  83. #ifndef BUILD_BRIDGE
  84. # ifdef USING_JUCE
  85. if (const uint count = getJuceApiCount())
  86. {
  87. if (index < count)
  88. return getJuceApiName(index);
  89. index -= count;
  90. }
  91. # else
  92. if (const uint count = getRtAudioApiCount())
  93. {
  94. if (index < count)
  95. return getRtAudioApiName(index);
  96. }
  97. # endif
  98. #endif
  99. carla_stderr("CarlaEngine::getDriverName(%i) - invalid index", index2);
  100. return nullptr;
  101. }
  102. const char* const* CarlaEngine::getDriverDeviceNames(const uint index2)
  103. {
  104. carla_debug("CarlaEngine::getDriverDeviceNames(%i)", index2);
  105. uint index = index2;
  106. if (jackbridge_is_ok() && index-- == 0)
  107. {
  108. static const char* ret[3] = { "Auto-Connect ON", "Auto-Connect OFF", nullptr };
  109. return ret;
  110. }
  111. #ifndef BUILD_BRIDGE
  112. # ifdef USING_JUCE
  113. if (const uint count = getJuceApiCount())
  114. {
  115. if (index < count)
  116. return getJuceApiDeviceNames(index);
  117. index -= count;
  118. }
  119. # else
  120. if (const uint count = getRtAudioApiCount())
  121. {
  122. if (index < count)
  123. return getRtAudioApiDeviceNames(index);
  124. }
  125. # endif
  126. #endif
  127. carla_stderr("CarlaEngine::getDriverDeviceNames(%i) - invalid index", index2);
  128. return nullptr;
  129. }
  130. const EngineDriverDeviceInfo* CarlaEngine::getDriverDeviceInfo(const uint index2, const char* const deviceName)
  131. {
  132. carla_debug("CarlaEngine::getDriverDeviceInfo(%i, \"%s\")", index2, deviceName);
  133. uint index = index2;
  134. if (jackbridge_is_ok() && index-- == 0)
  135. {
  136. static EngineDriverDeviceInfo devInfo;
  137. devInfo.hints = ENGINE_DRIVER_DEVICE_VARIABLE_BUFFER_SIZE;
  138. devInfo.bufferSizes = nullptr;
  139. devInfo.sampleRates = nullptr;
  140. return &devInfo;
  141. }
  142. #ifndef BUILD_BRIDGE
  143. # ifdef USING_JUCE
  144. if (const uint count = getJuceApiCount())
  145. {
  146. if (index < count)
  147. return getJuceDeviceInfo(index, deviceName);
  148. index -= count;
  149. }
  150. # else
  151. if (const uint count = getRtAudioApiCount())
  152. {
  153. if (index < count)
  154. return getRtAudioDeviceInfo(index, deviceName);
  155. }
  156. # endif
  157. #endif
  158. carla_stderr("CarlaEngine::getDriverDeviceNames(%i, \"%s\") - invalid index", index2, deviceName);
  159. return nullptr;
  160. }
  161. CarlaEngine* CarlaEngine::newDriverByName(const char* const driverName)
  162. {
  163. CARLA_SAFE_ASSERT_RETURN(driverName != nullptr && driverName[0] != '\0', nullptr);
  164. carla_debug("CarlaEngine::newDriverByName(\"%s\")", driverName);
  165. if (std::strcmp(driverName, "JACK") == 0)
  166. return newJack();
  167. #ifndef BUILD_BRIDGE
  168. # ifdef USING_JUCE
  169. // -------------------------------------------------------------------
  170. // linux
  171. if (std::strcmp(driverName, "ALSA") == 0)
  172. return newJuce(AUDIO_API_ALSA);
  173. // -------------------------------------------------------------------
  174. // macos
  175. if (std::strcmp(driverName, "CoreAudio") == 0)
  176. return newJuce(AUDIO_API_COREAUDIO);
  177. // -------------------------------------------------------------------
  178. // windows
  179. if (std::strcmp(driverName, "ASIO") == 0)
  180. return newJuce(AUDIO_API_ASIO);
  181. if (std::strcmp(driverName, "DirectSound") == 0)
  182. return newJuce(AUDIO_API_DIRECTSOUND);
  183. # else
  184. // -------------------------------------------------------------------
  185. // common
  186. if (std::strcmp(driverName, "Dummy") == 0)
  187. return newRtAudio(AUDIO_API_NULL);
  188. if (std::strncmp(driverName, "JACK ", 5) == 0)
  189. return newRtAudio(AUDIO_API_JACK);
  190. if (std::strcmp(driverName, "OSS") == 0)
  191. return newRtAudio(AUDIO_API_OSS);
  192. // -------------------------------------------------------------------
  193. // linux
  194. if (std::strcmp(driverName, "ALSA") == 0)
  195. return newRtAudio(AUDIO_API_ALSA);
  196. if (std::strcmp(driverName, "PulseAudio") == 0)
  197. return newRtAudio(AUDIO_API_PULSEAUDIO);
  198. // -------------------------------------------------------------------
  199. // macos
  200. if (std::strcmp(driverName, "CoreAudio") == 0)
  201. return newRtAudio(AUDIO_API_COREAUDIO);
  202. // -------------------------------------------------------------------
  203. // windows
  204. if (std::strcmp(driverName, "ASIO") == 0)
  205. return newRtAudio(AUDIO_API_ASIO);
  206. if (std::strcmp(driverName, "DirectSound") == 0)
  207. return newRtAudio(AUDIO_API_DIRECTSOUND);
  208. if (std::strcmp(driverName, "WASAPI") == 0)
  209. return newRtAudio(AUDIO_API_WASAPI);
  210. # endif
  211. #endif
  212. carla_stderr("CarlaEngine::newDriverByName(\"%s\") - invalid driver name", driverName);
  213. return nullptr;
  214. }
  215. // -----------------------------------------------------------------------
  216. // Constant values
  217. uint CarlaEngine::getMaxClientNameSize() const noexcept
  218. {
  219. return STR_MAX/2;
  220. }
  221. uint CarlaEngine::getMaxPortNameSize() const noexcept
  222. {
  223. return STR_MAX;
  224. }
  225. uint CarlaEngine::getCurrentPluginCount() const noexcept
  226. {
  227. return pData->curPluginCount;
  228. }
  229. uint CarlaEngine::getMaxPluginNumber() const noexcept
  230. {
  231. return pData->maxPluginNumber;
  232. }
  233. // -----------------------------------------------------------------------
  234. // Virtual, per-engine type calls
  235. bool CarlaEngine::close()
  236. {
  237. carla_debug("CarlaEngine::close()");
  238. if (pData->curPluginCount != 0)
  239. {
  240. pData->aboutToClose = true;
  241. removeAllPlugins();
  242. }
  243. #if defined(HAVE_LIBLO) && ! defined(BUILD_BRIDGE)
  244. if (pData->osc.isControlRegistered())
  245. oscSend_control_exit();
  246. #endif
  247. pData->close();
  248. callback(ENGINE_CALLBACK_ENGINE_STOPPED, 0, 0, 0, 0.0f, nullptr);
  249. return true;
  250. }
  251. bool CarlaEngine::usesConstantBufferSize() const noexcept
  252. {
  253. return true;
  254. }
  255. void CarlaEngine::idle() noexcept
  256. {
  257. CARLA_SAFE_ASSERT_RETURN(pData->nextAction.opcode == kEnginePostActionNull,);
  258. CARLA_SAFE_ASSERT_RETURN(pData->nextPluginId == pData->maxPluginNumber,);
  259. CARLA_SAFE_ASSERT_RETURN(getType() != kEngineTypePlugin,);
  260. for (uint i=0; i < pData->curPluginCount; ++i)
  261. {
  262. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  263. if (plugin != nullptr && plugin->isEnabled())
  264. {
  265. const uint hints(plugin->getHints());
  266. if ((hints & PLUGIN_HAS_CUSTOM_UI) != 0 && (hints & PLUGIN_NEEDS_UI_MAIN_THREAD) != 0)
  267. {
  268. try {
  269. plugin->uiIdle();
  270. } CARLA_SAFE_EXCEPTION_CONTINUE("Plugin uiIdle");
  271. }
  272. }
  273. }
  274. #if defined(HAVE_LIBLO) && !defined(BUILD_BRIDGE)
  275. pData->osc.idle();
  276. #endif
  277. }
  278. CarlaEngineClient* CarlaEngine::addClient(CarlaPlugin* const)
  279. {
  280. return new CarlaEngineClient(*this);
  281. }
  282. // -----------------------------------------------------------------------
  283. // Plugin management
  284. bool CarlaEngine::addPlugin(const BinaryType btype, const PluginType ptype,
  285. const char* const filename, const char* const name, const char* const label, const int64_t uniqueId,
  286. const void* const extra, const uint options)
  287. {
  288. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  289. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  290. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  291. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextPluginId <= pData->maxPluginNumber, "Invalid engine internal data");
  292. #endif
  293. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  294. CARLA_SAFE_ASSERT_RETURN_ERR(btype != BINARY_NONE, "Invalid plugin binary mode");
  295. CARLA_SAFE_ASSERT_RETURN_ERR(ptype != PLUGIN_NONE, "Invalid plugin type");
  296. CARLA_SAFE_ASSERT_RETURN_ERR((filename != nullptr && filename[0] != '\0') || (label != nullptr && label[0] != '\0'), "Invalid plugin filename and label");
  297. carla_debug("CarlaEngine::addPlugin(%i:%s, %i:%s, \"%s\", \"%s\", \"%s\", " P_INT64 ", %p, %u)", btype, BinaryType2Str(btype), ptype, PluginType2Str(ptype), filename, name, label, uniqueId, extra, options);
  298. #ifndef CARLA_OS_WIN
  299. if (filename != nullptr && filename[0] != '\0') {
  300. CARLA_SAFE_ASSERT_RETURN_ERR(filename[0] == CARLA_OS_SEP || filename[0] == '.' || filename[0] == '~', "Invalid plugin filename");
  301. }
  302. #endif
  303. uint id;
  304. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  305. CarlaPlugin* oldPlugin = nullptr;
  306. if (pData->nextPluginId < pData->curPluginCount)
  307. {
  308. id = pData->nextPluginId;
  309. pData->nextPluginId = pData->maxPluginNumber;
  310. oldPlugin = pData->plugins[id].plugin;
  311. CARLA_SAFE_ASSERT_RETURN_ERR(oldPlugin != nullptr, "Invalid replace plugin Id");
  312. }
  313. else
  314. #endif
  315. {
  316. id = pData->curPluginCount;
  317. if (id == pData->maxPluginNumber)
  318. {
  319. setLastError("Maximum number of plugins reached");
  320. return false;
  321. }
  322. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  323. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins[id].plugin == nullptr, "Invalid engine internal data");
  324. #endif
  325. }
  326. CarlaPlugin::Initializer initializer = {
  327. this,
  328. id,
  329. filename,
  330. name,
  331. label,
  332. uniqueId,
  333. options
  334. };
  335. CarlaPlugin* plugin = nullptr;
  336. CarlaString bridgeBinary(pData->options.binaryDir);
  337. if (bridgeBinary.isNotEmpty())
  338. {
  339. #ifndef CARLA_OS_WIN
  340. if (btype == BINARY_NATIVE)
  341. {
  342. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-native";
  343. }
  344. else
  345. #endif
  346. {
  347. switch (btype)
  348. {
  349. case BINARY_POSIX32:
  350. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-posix32";
  351. break;
  352. case BINARY_POSIX64:
  353. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-posix64";
  354. break;
  355. case BINARY_WIN32:
  356. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-win32.exe";
  357. break;
  358. case BINARY_WIN64:
  359. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-win64.exe";
  360. break;
  361. default:
  362. bridgeBinary.clear();
  363. break;
  364. }
  365. }
  366. if (! File(bridgeBinary.buffer()).existsAsFile())
  367. bridgeBinary.clear();
  368. }
  369. // Prefer bridges for some specific plugins
  370. const bool preferBridges = pData->options.preferPluginBridges;
  371. #if 0 // ndef BUILD_BRIDGE
  372. if (! preferBridges)
  373. {
  374. if (ptype == PLUGIN_LV2 && label != nullptr)
  375. {
  376. if (std::strncmp(label, "http://calf.sourceforge.net/plugins/", 36) == 0 ||
  377. std::strcmp(label, "http://factorial.hu/plugins/lv2/ir") == 0 ||
  378. std::strstr(label, "v1.sourceforge.net/lv2") != nullptr)
  379. {
  380. preferBridges = true;
  381. }
  382. }
  383. }
  384. #endif // ! BUILD_BRIDGE
  385. const bool canBeBridged = ptype != PLUGIN_INTERNAL
  386. && ptype != PLUGIN_SF2
  387. && ptype != PLUGIN_SFZ
  388. && ptype != PLUGIN_JACK;
  389. if (canBeBridged && (btype != BINARY_NATIVE || (preferBridges && bridgeBinary.isNotEmpty())))
  390. {
  391. if (bridgeBinary.isNotEmpty())
  392. {
  393. plugin = CarlaPlugin::newBridge(initializer, btype, ptype, bridgeBinary);
  394. }
  395. else
  396. {
  397. setLastError("This Carla build cannot handle this binary");
  398. return false;
  399. }
  400. }
  401. else
  402. {
  403. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  404. bool use16Outs;
  405. #endif
  406. setLastError("Invalid or unsupported plugin type");
  407. switch (ptype)
  408. {
  409. case PLUGIN_NONE:
  410. break;
  411. case PLUGIN_LADSPA:
  412. plugin = CarlaPlugin::newLADSPA(initializer, (const LADSPA_RDF_Descriptor*)extra);
  413. break;
  414. case PLUGIN_DSSI:
  415. plugin = CarlaPlugin::newDSSI(initializer);
  416. break;
  417. case PLUGIN_LV2:
  418. plugin = CarlaPlugin::newLV2(initializer);
  419. break;
  420. case PLUGIN_VST2:
  421. plugin = CarlaPlugin::newVST2(initializer);
  422. break;
  423. case PLUGIN_VST3:
  424. plugin = CarlaPlugin::newVST3(initializer);
  425. break;
  426. case PLUGIN_AU:
  427. plugin = CarlaPlugin::newAU(initializer);
  428. break;
  429. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  430. case PLUGIN_INTERNAL:
  431. plugin = CarlaPlugin::newNative(initializer);
  432. break;
  433. case PLUGIN_SF2:
  434. use16Outs = (extra != nullptr && std::strcmp((const char*)extra, "true") == 0);
  435. plugin = CarlaPlugin::newFluidSynth(initializer, use16Outs);
  436. break;
  437. case PLUGIN_SFZ:
  438. plugin = CarlaPlugin::newSFZero(initializer);
  439. break;
  440. case PLUGIN_JACK:
  441. plugin = CarlaPlugin::newJackApp(initializer);
  442. break;
  443. #else
  444. case PLUGIN_INTERNAL:
  445. case PLUGIN_SF2:
  446. case PLUGIN_SFZ:
  447. case PLUGIN_JACK:
  448. setLastError("Plugin bridges cannot handle this binary");
  449. break;
  450. #endif
  451. }
  452. }
  453. if (plugin == nullptr)
  454. return false;
  455. plugin->reload();
  456. bool canRun = true;
  457. /**/ if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  458. {
  459. if (plugin->getCVInCount() > 0 || plugin->getCVInCount() > 0)
  460. {
  461. setLastError("Carla's rack mode cannot work with plugins that have CV ports, sorry!");
  462. canRun = false;
  463. }
  464. }
  465. else if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  466. {
  467. /**/ if (plugin->getMidiInCount() > 1 || plugin->getMidiOutCount() > 1)
  468. {
  469. setLastError("Carla's patchbay mode cannot work with plugins that have multiple MIDI ports, sorry!");
  470. canRun = false;
  471. }
  472. else if (plugin->getCVInCount() > 0 || plugin->getCVInCount() > 0)
  473. {
  474. setLastError("CV ports in patchbay mode is still TODO");
  475. canRun = false;
  476. }
  477. }
  478. if (! canRun)
  479. {
  480. delete plugin;
  481. return false;
  482. }
  483. EnginePluginData& pluginData(pData->plugins[id]);
  484. pluginData.plugin = plugin;
  485. carla_zeroFloats(pluginData.peaks, 4);
  486. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  487. if (oldPlugin != nullptr)
  488. {
  489. CARLA_SAFE_ASSERT(! pData->loadingProject);
  490. const ScopedThreadStopper sts(this);
  491. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  492. pData->graph.replacePlugin(oldPlugin, plugin);
  493. const bool wasActive = oldPlugin->getInternalParameterValue(PARAMETER_ACTIVE) >= 0.5f;
  494. const float oldDryWet = oldPlugin->getInternalParameterValue(PARAMETER_DRYWET);
  495. const float oldVolume = oldPlugin->getInternalParameterValue(PARAMETER_VOLUME);
  496. delete oldPlugin;
  497. if (plugin->getHints() & PLUGIN_CAN_DRYWET)
  498. plugin->setDryWet(oldDryWet, true, true);
  499. if (plugin->getHints() & PLUGIN_CAN_VOLUME)
  500. plugin->setVolume(oldVolume, true, true);
  501. plugin->setActive(wasActive, true, true);
  502. plugin->setEnabled(true);
  503. callback(ENGINE_CALLBACK_RELOAD_ALL, id, 0, 0, 0.0f, nullptr);
  504. }
  505. else if (! pData->loadingProject)
  506. #endif
  507. {
  508. plugin->setEnabled(true);
  509. ++pData->curPluginCount;
  510. callback(ENGINE_CALLBACK_PLUGIN_ADDED, id, 0, 0, 0.0f, plugin->getName());
  511. if (getType() != kEngineTypeBridge)
  512. plugin->setActive(true, false, true);
  513. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  514. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  515. pData->graph.addPlugin(plugin);
  516. #endif
  517. }
  518. #if defined(HAVE_LIBLO) && ! defined(BUILD_BRIDGE)
  519. plugin->registerToOscClient();
  520. #endif
  521. return true;
  522. }
  523. bool CarlaEngine::addPlugin(const PluginType ptype, const char* const filename, const char* const name, const char* const label, const int64_t uniqueId, const void* const extra)
  524. {
  525. return addPlugin(BINARY_NATIVE, ptype, filename, name, label, uniqueId, extra, 0x0);
  526. }
  527. bool CarlaEngine::removePlugin(const uint id)
  528. {
  529. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  530. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  531. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  532. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount != 0, "Invalid engine internal data");
  533. #endif
  534. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  535. CARLA_SAFE_ASSERT_RETURN_ERR(id < pData->curPluginCount, "Invalid plugin Id");
  536. carla_debug("CarlaEngine::removePlugin(%i)", id);
  537. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  538. CARLA_SAFE_ASSERT_RETURN_ERR(plugin != nullptr, "Could not find plugin to remove");
  539. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  540. const ScopedThreadStopper sts(this);
  541. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  542. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  543. pData->graph.removePlugin(plugin);
  544. const ScopedActionLock sal(this, kEnginePostActionRemovePlugin, id, 0);
  545. /*
  546. for (uint i=id; i < pData->curPluginCount; ++i)
  547. {
  548. CarlaPlugin* const plugin2(pData->plugins[i].plugin);
  549. CARLA_SAFE_ASSERT_BREAK(plugin2 != nullptr);
  550. plugin2->updateOscURL();
  551. }
  552. */
  553. # if defined(HAVE_LIBLO) && !defined(BUILD_BRIDGE)
  554. if (isOscControlRegistered())
  555. oscSend_control_remove_plugin(id);
  556. # endif
  557. #else
  558. pData->curPluginCount = 0;
  559. carla_zeroStructs(pData->plugins, 1);
  560. #endif
  561. delete plugin;
  562. callback(ENGINE_CALLBACK_PLUGIN_REMOVED, id, 0, 0, 0.0f, nullptr);
  563. return true;
  564. }
  565. bool CarlaEngine::removeAllPlugins()
  566. {
  567. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  568. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  569. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  570. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextPluginId == pData->maxPluginNumber, "Invalid engine internal data");
  571. #endif
  572. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  573. carla_debug("CarlaEngine::removeAllPlugins()");
  574. if (pData->curPluginCount == 0)
  575. return true;
  576. const ScopedThreadStopper sts(this);
  577. const uint curPluginCount(pData->curPluginCount);
  578. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  579. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  580. pData->graph.removeAllPlugins();
  581. # if defined(HAVE_LIBLO) && !defined(BUILD_BRIDGE)
  582. if (isOscControlRegistered())
  583. {
  584. for (uint i=0; i < curPluginCount; ++i)
  585. oscSend_control_remove_plugin(curPluginCount-i-1);
  586. }
  587. # endif
  588. #endif
  589. const ScopedActionLock sal(this, kEnginePostActionZeroCount, 0, 0);
  590. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  591. for (uint i=0; i < curPluginCount; ++i)
  592. {
  593. EnginePluginData& pluginData(pData->plugins[i]);
  594. if (pluginData.plugin != nullptr)
  595. {
  596. delete pluginData.plugin;
  597. pluginData.plugin = nullptr;
  598. }
  599. carla_zeroFloats(pluginData.peaks, 4);
  600. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  601. }
  602. return true;
  603. }
  604. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  605. const char* CarlaEngine::renamePlugin(const uint id, const char* const newName)
  606. {
  607. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  608. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->plugins != nullptr, "Invalid engine internal data");
  609. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->curPluginCount != 0, "Invalid engine internal data");
  610. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  611. CARLA_SAFE_ASSERT_RETURN_ERRN(id < pData->curPluginCount, "Invalid plugin Id");
  612. CARLA_SAFE_ASSERT_RETURN_ERRN(newName != nullptr && newName[0] != '\0', "Invalid plugin name");
  613. carla_debug("CarlaEngine::renamePlugin(%i, \"%s\")", id, newName);
  614. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  615. CARLA_SAFE_ASSERT_RETURN_ERRN(plugin != nullptr, "Could not find plugin to rename");
  616. CARLA_SAFE_ASSERT_RETURN_ERRN(plugin->getId() == id, "Invalid engine internal data");
  617. const char* const uniqueName(getUniquePluginName(newName));
  618. CARLA_SAFE_ASSERT_RETURN_ERRN(uniqueName != nullptr, "Unable to get new unique plugin name");
  619. plugin->setName(uniqueName);
  620. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  621. pData->graph.renamePlugin(plugin, uniqueName);
  622. delete[] uniqueName;
  623. return plugin->getName();
  624. }
  625. bool CarlaEngine::clonePlugin(const uint id)
  626. {
  627. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  628. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  629. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount != 0, "Invalid engine internal data");
  630. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  631. CARLA_SAFE_ASSERT_RETURN_ERR(id < pData->curPluginCount, "Invalid plugin Id");
  632. carla_debug("CarlaEngine::clonePlugin(%i)", id);
  633. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  634. CARLA_SAFE_ASSERT_RETURN_ERR(plugin != nullptr, "Could not find plugin to clone");
  635. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  636. char label[STR_MAX+1];
  637. carla_zeroChars(label, STR_MAX+1);
  638. plugin->getLabel(label);
  639. const uint pluginCountBefore(pData->curPluginCount);
  640. if (! addPlugin(plugin->getBinaryType(), plugin->getType(),
  641. plugin->getFilename(), plugin->getName(), label, plugin->getUniqueId(),
  642. plugin->getExtraStuff(), plugin->getOptionsEnabled()))
  643. return false;
  644. CARLA_SAFE_ASSERT_RETURN_ERR(pluginCountBefore+1 == pData->curPluginCount, "No new plugin found");
  645. if (CarlaPlugin* const newPlugin = pData->plugins[pluginCountBefore].plugin)
  646. newPlugin->loadStateSave(plugin->getStateSave());
  647. return true;
  648. }
  649. bool CarlaEngine::replacePlugin(const uint id) noexcept
  650. {
  651. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  652. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  653. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount != 0, "Invalid engine internal data");
  654. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  655. carla_debug("CarlaEngine::replacePlugin(%i)", id);
  656. // might use this to reset
  657. if (id == pData->maxPluginNumber)
  658. {
  659. pData->nextPluginId = pData->maxPluginNumber;
  660. return true;
  661. }
  662. CARLA_SAFE_ASSERT_RETURN_ERR(id < pData->curPluginCount, "Invalid plugin Id");
  663. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  664. CARLA_SAFE_ASSERT_RETURN_ERR(plugin != nullptr, "Could not find plugin to replace");
  665. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  666. pData->nextPluginId = id;
  667. return true;
  668. }
  669. bool CarlaEngine::switchPlugins(const uint idA, const uint idB) noexcept
  670. {
  671. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  672. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  673. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount >= 2, "Invalid engine internal data");
  674. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  675. CARLA_SAFE_ASSERT_RETURN_ERR(idA != idB, "Invalid operation, cannot switch plugin with itself");
  676. CARLA_SAFE_ASSERT_RETURN_ERR(idA < pData->curPluginCount, "Invalid plugin Id");
  677. CARLA_SAFE_ASSERT_RETURN_ERR(idB < pData->curPluginCount, "Invalid plugin Id");
  678. carla_debug("CarlaEngine::switchPlugins(%i)", idA, idB);
  679. CarlaPlugin* const pluginA(pData->plugins[idA].plugin);
  680. CarlaPlugin* const pluginB(pData->plugins[idB].plugin);
  681. CARLA_SAFE_ASSERT_RETURN_ERR(pluginA != nullptr, "Could not find plugin to switch");
  682. CARLA_SAFE_ASSERT_RETURN_ERR(pluginA != nullptr, "Could not find plugin to switch");
  683. CARLA_SAFE_ASSERT_RETURN_ERR(pluginA->getId() == idA, "Invalid engine internal data");
  684. CARLA_SAFE_ASSERT_RETURN_ERR(pluginB->getId() == idB, "Invalid engine internal data");
  685. const ScopedThreadStopper sts(this);
  686. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  687. pData->graph.replacePlugin(pluginA, pluginB);
  688. const ScopedActionLock sal(this, kEnginePostActionSwitchPlugins, idA, idB);
  689. // TODO
  690. /*
  691. pluginA->updateOscURL();
  692. pluginB->updateOscURL();
  693. if (isOscControlRegistered())
  694. oscSend_control_switch_plugins(idA, idB);
  695. */
  696. return true;
  697. }
  698. #endif
  699. CarlaPlugin* CarlaEngine::getPlugin(const uint id) const noexcept
  700. {
  701. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  702. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->plugins != nullptr, "Invalid engine internal data");
  703. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->curPluginCount != 0, "Invalid engine internal data");
  704. #endif
  705. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  706. CARLA_SAFE_ASSERT_RETURN_ERRN(id < pData->curPluginCount, "Invalid plugin Id");
  707. return pData->plugins[id].plugin;
  708. }
  709. CarlaPlugin* CarlaEngine::getPluginUnchecked(const uint id) const noexcept
  710. {
  711. return pData->plugins[id].plugin;
  712. }
  713. const char* CarlaEngine::getUniquePluginName(const char* const name) const
  714. {
  715. CARLA_SAFE_ASSERT_RETURN(pData->nextAction.opcode == kEnginePostActionNull, nullptr);
  716. CARLA_SAFE_ASSERT_RETURN(name != nullptr && name[0] != '\0', nullptr);
  717. carla_debug("CarlaEngine::getUniquePluginName(\"%s\")", name);
  718. CarlaString sname;
  719. sname = name;
  720. if (sname.isEmpty())
  721. {
  722. sname = "(No name)";
  723. return sname.dup();
  724. }
  725. const std::size_t maxNameSize(carla_minConstrained<uint>(getMaxClientNameSize(), 0xff, 6U) - 6); // 6 = strlen(" (10)") + 1
  726. if (maxNameSize == 0 || ! isRunning())
  727. return sname.dup();
  728. sname.truncate(maxNameSize);
  729. sname.replace(':', '.'); // ':' is used in JACK1 to split client/port names
  730. for (uint i=0; i < pData->curPluginCount; ++i)
  731. {
  732. CARLA_SAFE_ASSERT_BREAK(pData->plugins[i].plugin != nullptr);
  733. // Check if unique name doesn't exist
  734. if (const char* const pluginName = pData->plugins[i].plugin->getName())
  735. {
  736. if (sname != pluginName)
  737. continue;
  738. }
  739. // Check if string has already been modified
  740. {
  741. const std::size_t len(sname.length());
  742. // 1 digit, ex: " (2)"
  743. if (sname[len-4] == ' ' && sname[len-3] == '(' && sname.isDigit(len-2) && sname[len-1] == ')')
  744. {
  745. const int number = sname[len-2] - '0';
  746. if (number == 9)
  747. {
  748. // next number is 10, 2 digits
  749. sname.truncate(len-4);
  750. sname += " (10)";
  751. //sname.replace(" (9)", " (10)");
  752. }
  753. else
  754. sname[len-2] = char('0' + number + 1);
  755. continue;
  756. }
  757. // 2 digits, ex: " (11)"
  758. if (sname[len-5] == ' ' && sname[len-4] == '(' && sname.isDigit(len-3) && sname.isDigit(len-2) && sname[len-1] == ')')
  759. {
  760. char n2 = sname[len-2];
  761. char n3 = sname[len-3];
  762. if (n2 == '9')
  763. {
  764. n2 = '0';
  765. n3 = static_cast<char>(n3 + 1);
  766. }
  767. else
  768. n2 = static_cast<char>(n2 + 1);
  769. sname[len-2] = n2;
  770. sname[len-3] = n3;
  771. continue;
  772. }
  773. }
  774. // Modify string if not
  775. sname += " (2)";
  776. }
  777. return sname.dup();
  778. }
  779. // -----------------------------------------------------------------------
  780. // Project management
  781. bool CarlaEngine::loadFile(const char* const filename)
  782. {
  783. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  784. CARLA_SAFE_ASSERT_RETURN_ERR(filename != nullptr && filename[0] != '\0', "Invalid filename");
  785. carla_debug("CarlaEngine::loadFile(\"%s\")", filename);
  786. const String jfilename = String(CharPointer_UTF8(filename));
  787. File file(jfilename);
  788. CARLA_SAFE_ASSERT_RETURN_ERR(file.exists(), "Requested file does not exist or is not a readable");
  789. CarlaString baseName(file.getFileNameWithoutExtension().toRawUTF8());
  790. CarlaString extension(file.getFileExtension().replace(".","").toLowerCase().toRawUTF8());
  791. const uint curPluginId(pData->nextPluginId < pData->curPluginCount ? pData->nextPluginId : pData->curPluginCount);
  792. // -------------------------------------------------------------------
  793. // NOTE: please keep in sync with carla_get_supported_file_extensions!!
  794. if (extension == "carxp" || extension == "carxs")
  795. return loadProject(filename);
  796. // -------------------------------------------------------------------
  797. if (extension == "sf2" || extension == "sf3")
  798. return addPlugin(PLUGIN_SF2, filename, baseName, baseName, 0, nullptr);
  799. if (extension == "sfz")
  800. return addPlugin(PLUGIN_SFZ, filename, baseName, baseName, 0, nullptr);
  801. // -------------------------------------------------------------------
  802. if (
  803. #ifdef HAVE_SNDFILE
  804. extension == "aif" ||
  805. extension == "aifc" ||
  806. extension == "aiff" ||
  807. extension == "au" ||
  808. extension == "bwf" ||
  809. extension == "flac" ||
  810. extension == "htk" ||
  811. extension == "iff" ||
  812. extension == "mat4" ||
  813. extension == "mat5" ||
  814. extension == "oga" ||
  815. extension == "ogg" ||
  816. extension == "paf" ||
  817. extension == "pvf" ||
  818. extension == "pvf5" ||
  819. extension == "sd2" ||
  820. extension == "sf" ||
  821. extension == "snd" ||
  822. extension == "svx" ||
  823. extension == "vcc" ||
  824. extension == "w64" ||
  825. extension == "wav" ||
  826. extension == "xi" ||
  827. #endif
  828. #ifdef HAVE_FFMPEG
  829. extension == "3g2" ||
  830. extension == "3gp" ||
  831. extension == "aac" ||
  832. extension == "ac3" ||
  833. extension == "amr" ||
  834. extension == "ape" ||
  835. extension == "mp2" ||
  836. extension == "mp3" ||
  837. extension == "mpc" ||
  838. extension == "wma" ||
  839. # ifdef HAVE_SNDFILE
  840. // FFmpeg without sndfile
  841. extension == "flac" ||
  842. extension == "oga" ||
  843. extension == "ogg" ||
  844. extension == "w64" ||
  845. extension == "wav" ||
  846. # endif
  847. #endif
  848. false
  849. )
  850. {
  851. if (addPlugin(PLUGIN_INTERNAL, nullptr, baseName, "audiofile", 0, nullptr))
  852. {
  853. if (CarlaPlugin* const plugin = getPlugin(curPluginId))
  854. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "file", filename, true);
  855. return true;
  856. }
  857. return false;
  858. }
  859. // -------------------------------------------------------------------
  860. if (extension == "mid" || extension == "midi")
  861. {
  862. if (addPlugin(PLUGIN_INTERNAL, nullptr, baseName, "midifile", 0, nullptr))
  863. {
  864. if (CarlaPlugin* const plugin = getPlugin(curPluginId))
  865. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "file", filename, true);
  866. return true;
  867. }
  868. return false;
  869. }
  870. // -------------------------------------------------------------------
  871. // ZynAddSubFX
  872. if (extension == "xmz" || extension == "xiz")
  873. {
  874. #ifdef HAVE_ZYN_DEPS
  875. CarlaString nicerName("Zyn - ");
  876. const std::size_t sep(baseName.find('-')+1);
  877. if (sep < baseName.length())
  878. nicerName += baseName.buffer()+sep;
  879. else
  880. nicerName += baseName;
  881. //nicerName
  882. if (addPlugin(PLUGIN_INTERNAL, nullptr, nicerName, "zynaddsubfx", 0, nullptr))
  883. {
  884. callback(ENGINE_CALLBACK_UI_STATE_CHANGED, curPluginId, 0, 0, 0.0f, nullptr);
  885. if (CarlaPlugin* const plugin = getPlugin(curPluginId))
  886. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, (extension == "xmz") ? "CarlaAlternateFile1" : "CarlaAlternateFile2", filename, true);
  887. return true;
  888. }
  889. return false;
  890. #else
  891. setLastError("This Carla build does not have ZynAddSubFX support");
  892. return false;
  893. #endif
  894. }
  895. // -------------------------------------------------------------------
  896. // Direct plugin binaries
  897. #ifdef CARLA_OS_MAC
  898. if (extension == "vst")
  899. return addPlugin(PLUGIN_VST2, filename, nullptr, nullptr, 0, nullptr);
  900. #else
  901. if (extension == "dll" || extension == "so")
  902. return addPlugin(getBinaryTypeFromFile(filename), PLUGIN_VST2, filename, nullptr, nullptr, 0, nullptr, 0x0);
  903. #endif
  904. #ifdef USING_JUCE
  905. if (extension == "vst3")
  906. return addPlugin(getBinaryTypeFromFile(filename), PLUGIN_VST3, filename, nullptr, nullptr, 0, nullptr, 0x0);
  907. #endif
  908. // -------------------------------------------------------------------
  909. setLastError("Unknown file extension");
  910. return false;
  911. }
  912. bool CarlaEngine::loadProject(const char* const filename)
  913. {
  914. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  915. CARLA_SAFE_ASSERT_RETURN_ERR(filename != nullptr && filename[0] != '\0', "Invalid filename");
  916. carla_debug("CarlaEngine::loadProject(\"%s\")", filename);
  917. const String jfilename = String(CharPointer_UTF8(filename));
  918. File file(jfilename);
  919. CARLA_SAFE_ASSERT_RETURN_ERR(file.existsAsFile(), "Requested file does not exist or is not a readable file");
  920. XmlDocument xml(file);
  921. return loadProjectInternal(xml);
  922. }
  923. bool CarlaEngine::saveProject(const char* const filename)
  924. {
  925. CARLA_SAFE_ASSERT_RETURN_ERR(filename != nullptr && filename[0] != '\0', "Invalid filename");
  926. carla_debug("CarlaEngine::saveProject(\"%s\")", filename);
  927. MemoryOutputStream out;
  928. saveProjectInternal(out);
  929. const String jfilename = String(CharPointer_UTF8(filename));
  930. File file(jfilename);
  931. if (file.replaceWithData(out.getData(), out.getDataSize()))
  932. return true;
  933. setLastError("Failed to write file");
  934. return false;
  935. }
  936. // -----------------------------------------------------------------------
  937. // Information (base)
  938. uint CarlaEngine::getHints() const noexcept
  939. {
  940. return pData->hints;
  941. }
  942. uint32_t CarlaEngine::getBufferSize() const noexcept
  943. {
  944. return pData->bufferSize;
  945. }
  946. double CarlaEngine::getSampleRate() const noexcept
  947. {
  948. return pData->sampleRate;
  949. }
  950. const char* CarlaEngine::getName() const noexcept
  951. {
  952. return pData->name;
  953. }
  954. EngineProcessMode CarlaEngine::getProccessMode() const noexcept
  955. {
  956. return pData->options.processMode;
  957. }
  958. const EngineOptions& CarlaEngine::getOptions() const noexcept
  959. {
  960. return pData->options;
  961. }
  962. EngineTimeInfo CarlaEngine::getTimeInfo() const noexcept
  963. {
  964. return pData->timeInfo;
  965. }
  966. // -----------------------------------------------------------------------
  967. // Information (peaks)
  968. float* CarlaEngine::getPeaks(const uint pluginId) const noexcept
  969. {
  970. carla_zeroFloats(pData->peaks, 4);
  971. if (pluginId == MAIN_CARLA_PLUGIN_ID)
  972. {
  973. // get peak from first plugin, if available
  974. if (const uint count = pData->curPluginCount)
  975. {
  976. pData->peaks[0] = pData->plugins[0].peaks[0];
  977. pData->peaks[1] = pData->plugins[0].peaks[1];
  978. pData->peaks[2] = pData->plugins[count-1].peaks[2];
  979. pData->peaks[3] = pData->plugins[count-1].peaks[3];
  980. }
  981. return pData->peaks;
  982. }
  983. CARLA_SAFE_ASSERT_RETURN(pluginId < pData->curPluginCount, pData->peaks);
  984. return pData->plugins[pluginId].peaks;
  985. }
  986. float CarlaEngine::getInputPeak(const uint pluginId, const bool isLeft) const noexcept
  987. {
  988. if (pluginId == MAIN_CARLA_PLUGIN_ID)
  989. {
  990. // get peak from first plugin, if available
  991. if (pData->curPluginCount > 0)
  992. return pData->plugins[0].peaks[isLeft ? 0 : 1];
  993. return 0.0f;
  994. }
  995. CARLA_SAFE_ASSERT_RETURN(pluginId < pData->curPluginCount, 0.0f);
  996. return pData->plugins[pluginId].peaks[isLeft ? 0 : 1];
  997. }
  998. float CarlaEngine::getOutputPeak(const uint pluginId, const bool isLeft) const noexcept
  999. {
  1000. if (pluginId == MAIN_CARLA_PLUGIN_ID)
  1001. {
  1002. // get peak from last plugin, if available
  1003. if (pData->curPluginCount > 0)
  1004. return pData->plugins[pData->curPluginCount-1].peaks[isLeft ? 2 : 3];
  1005. return 0.0f;
  1006. }
  1007. CARLA_SAFE_ASSERT_RETURN(pluginId < pData->curPluginCount, 0.0f);
  1008. return pData->plugins[pluginId].peaks[isLeft ? 2 : 3];
  1009. }
  1010. // -----------------------------------------------------------------------
  1011. // Callback
  1012. void CarlaEngine::callback(const EngineCallbackOpcode action, const uint pluginId, const int value1, const int value2, const float value3, const char* const valueStr) noexcept
  1013. {
  1014. #ifdef DEBUG
  1015. if (pData->isIdling)
  1016. carla_stdout("CarlaEngine::callback [while idling] (%i:%s, %i, %i, %i, %f, \"%s\")",
  1017. action, EngineCallbackOpcode2Str(action), pluginId, value1, value2, value3, valueStr);
  1018. else if (action != ENGINE_CALLBACK_IDLE && action != ENGINE_CALLBACK_NOTE_ON && action != ENGINE_CALLBACK_NOTE_OFF)
  1019. carla_debug("CarlaEngine::callback(%i:%s, %i, %i, %i, %f, \"%s\")",
  1020. action, EngineCallbackOpcode2Str(action), pluginId, value1, value2, value3, valueStr);
  1021. #endif
  1022. if (pData->callback != nullptr)
  1023. {
  1024. if (action == ENGINE_CALLBACK_IDLE)
  1025. ++pData->isIdling;
  1026. try {
  1027. pData->callback(pData->callbackPtr, action, pluginId, value1, value2, value3, valueStr);
  1028. #if defined(CARLA_OS_LINUX) && defined(__arm__)
  1029. } catch (__cxxabiv1::__forced_unwind&) {
  1030. carla_stderr2("Caught forced unwind exception in callback");
  1031. throw;
  1032. #endif
  1033. } catch (...) {
  1034. carla_safe_exception("callback", __FILE__, __LINE__);
  1035. }
  1036. if (action == ENGINE_CALLBACK_IDLE)
  1037. --pData->isIdling;
  1038. }
  1039. }
  1040. void CarlaEngine::setCallback(const EngineCallbackFunc func, void* const ptr) noexcept
  1041. {
  1042. carla_debug("CarlaEngine::setCallback(%p, %p)", func, ptr);
  1043. pData->callback = func;
  1044. pData->callbackPtr = ptr;
  1045. }
  1046. // -----------------------------------------------------------------------
  1047. // File Callback
  1048. const char* CarlaEngine::runFileCallback(const FileCallbackOpcode action, const bool isDir, const char* const title, const char* const filter) noexcept
  1049. {
  1050. CARLA_SAFE_ASSERT_RETURN(title != nullptr && title[0] != '\0', nullptr);
  1051. CARLA_SAFE_ASSERT_RETURN(filter != nullptr, nullptr);
  1052. carla_debug("CarlaEngine::runFileCallback(%i:%s, %s, \"%s\", \"%s\")", action, FileCallbackOpcode2Str(action), bool2str(isDir), title, filter);
  1053. const char* ret = nullptr;
  1054. if (pData->fileCallback != nullptr)
  1055. {
  1056. try {
  1057. ret = pData->fileCallback(pData->fileCallbackPtr, action, isDir, title, filter);
  1058. } CARLA_SAFE_EXCEPTION("runFileCallback");
  1059. }
  1060. return ret;
  1061. }
  1062. void CarlaEngine::setFileCallback(const FileCallbackFunc func, void* const ptr) noexcept
  1063. {
  1064. carla_debug("CarlaEngine::setFileCallback(%p, %p)", func, ptr);
  1065. pData->fileCallback = func;
  1066. pData->fileCallbackPtr = ptr;
  1067. }
  1068. // -----------------------------------------------------------------------
  1069. // Transport
  1070. void CarlaEngine::transportPlay() noexcept
  1071. {
  1072. pData->timeInfo.playing = true;
  1073. pData->time.setNeedsReset();
  1074. }
  1075. void CarlaEngine::transportPause() noexcept
  1076. {
  1077. if (pData->timeInfo.playing)
  1078. pData->time.pause();
  1079. else
  1080. pData->time.setNeedsReset();
  1081. }
  1082. void CarlaEngine::transportBPM(const double bpm) noexcept
  1083. {
  1084. try {
  1085. pData->time.setBPM(bpm);
  1086. } CARLA_SAFE_EXCEPTION("CarlaEngine::transportBPM");
  1087. }
  1088. void CarlaEngine::transportRelocate(const uint64_t frame) noexcept
  1089. {
  1090. pData->time.relocate(frame);
  1091. }
  1092. // -----------------------------------------------------------------------
  1093. // Error handling
  1094. const char* CarlaEngine::getLastError() const noexcept
  1095. {
  1096. return pData->lastError;
  1097. }
  1098. void CarlaEngine::setLastError(const char* const error) const noexcept
  1099. {
  1100. pData->lastError = error;
  1101. }
  1102. // -----------------------------------------------------------------------
  1103. // Misc
  1104. bool CarlaEngine::isAboutToClose() const noexcept
  1105. {
  1106. return pData->aboutToClose;
  1107. }
  1108. bool CarlaEngine::setAboutToClose() noexcept
  1109. {
  1110. carla_debug("CarlaEngine::setAboutToClose()");
  1111. pData->aboutToClose = true;
  1112. return (pData->isIdling == 0);
  1113. }
  1114. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1115. bool CarlaEngine::isLoadingProject() const noexcept
  1116. {
  1117. return pData->loadingProject;
  1118. }
  1119. #endif
  1120. // -----------------------------------------------------------------------
  1121. // Global options
  1122. void CarlaEngine::setOption(const EngineOption option, const int value, const char* const valueStr) noexcept
  1123. {
  1124. carla_debug("CarlaEngine::setOption(%i:%s, %i, \"%s\")", option, EngineOption2Str(option), value, valueStr);
  1125. if (isRunning())
  1126. {
  1127. switch (option)
  1128. {
  1129. case ENGINE_OPTION_PROCESS_MODE:
  1130. case ENGINE_OPTION_AUDIO_TRIPLE_BUFFER:
  1131. case ENGINE_OPTION_AUDIO_DEVICE:
  1132. return carla_stderr("CarlaEngine::setOption(%i:%s, %i, \"%s\") - Cannot set this option while engine is running!",
  1133. option, EngineOption2Str(option), value, valueStr);
  1134. default:
  1135. break;
  1136. }
  1137. }
  1138. // do not un-force stereo for rack mode
  1139. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK && option == ENGINE_OPTION_FORCE_STEREO && value != 0)
  1140. return;
  1141. switch (option)
  1142. {
  1143. case ENGINE_OPTION_DEBUG:
  1144. break;
  1145. case ENGINE_OPTION_PROCESS_MODE:
  1146. CARLA_SAFE_ASSERT_RETURN(value >= ENGINE_PROCESS_MODE_SINGLE_CLIENT && value <= ENGINE_PROCESS_MODE_BRIDGE,);
  1147. pData->options.processMode = static_cast<EngineProcessMode>(value);
  1148. break;
  1149. case ENGINE_OPTION_TRANSPORT_MODE:
  1150. CARLA_SAFE_ASSERT_RETURN(value >= ENGINE_TRANSPORT_MODE_DISABLED && value <= ENGINE_TRANSPORT_MODE_BRIDGE,);
  1151. CARLA_SAFE_ASSERT_RETURN(getType() == kEngineTypeJack || value != ENGINE_TRANSPORT_MODE_JACK,);
  1152. pData->options.transportMode = static_cast<EngineTransportMode>(value);
  1153. delete[] pData->options.transportExtra;
  1154. if (value >= ENGINE_TRANSPORT_MODE_DISABLED && valueStr != nullptr)
  1155. pData->options.transportExtra = carla_strdup_safe(valueStr);
  1156. else
  1157. pData->options.transportExtra = nullptr;
  1158. pData->time.setNeedsReset();
  1159. #if defined(HAVE_HYLIA) && !defined(BUILD_BRIDGE)
  1160. // enable link now if needed
  1161. {
  1162. const bool linkEnabled = pData->options.transportExtra != nullptr && std::strstr(pData->options.transportExtra, ":link:") != nullptr;
  1163. pData->time.enableLink(linkEnabled);
  1164. }
  1165. #endif
  1166. break;
  1167. case ENGINE_OPTION_FORCE_STEREO:
  1168. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1169. pData->options.forceStereo = (value != 0);
  1170. break;
  1171. case ENGINE_OPTION_PREFER_PLUGIN_BRIDGES:
  1172. #ifdef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1173. CARLA_SAFE_ASSERT_RETURN(value == 0,);
  1174. #else
  1175. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1176. #endif
  1177. pData->options.preferPluginBridges = (value != 0);
  1178. break;
  1179. case ENGINE_OPTION_PREFER_UI_BRIDGES:
  1180. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1181. pData->options.preferUiBridges = (value != 0);
  1182. break;
  1183. case ENGINE_OPTION_UIS_ALWAYS_ON_TOP:
  1184. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1185. pData->options.uisAlwaysOnTop = (value != 0);
  1186. break;
  1187. case ENGINE_OPTION_MAX_PARAMETERS:
  1188. CARLA_SAFE_ASSERT_RETURN(value >= 0,);
  1189. pData->options.maxParameters = static_cast<uint>(value);
  1190. break;
  1191. case ENGINE_OPTION_UI_BRIDGES_TIMEOUT:
  1192. CARLA_SAFE_ASSERT_RETURN(value >= 0,);
  1193. pData->options.uiBridgesTimeout = static_cast<uint>(value);
  1194. break;
  1195. case ENGINE_OPTION_AUDIO_BUFFER_SIZE:
  1196. CARLA_SAFE_ASSERT_RETURN(value >= 8,);
  1197. pData->options.audioBufferSize = static_cast<uint>(value);
  1198. break;
  1199. case ENGINE_OPTION_AUDIO_SAMPLE_RATE:
  1200. CARLA_SAFE_ASSERT_RETURN(value >= 22050,);
  1201. pData->options.audioSampleRate = static_cast<uint>(value);
  1202. break;
  1203. case ENGINE_OPTION_AUDIO_TRIPLE_BUFFER:
  1204. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1205. pData->options.audioTripleBuffer = (value != 0);
  1206. break;
  1207. case ENGINE_OPTION_AUDIO_DEVICE:
  1208. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr,);
  1209. if (pData->options.audioDevice != nullptr)
  1210. delete[] pData->options.audioDevice;
  1211. pData->options.audioDevice = carla_strdup_safe(valueStr);
  1212. break;
  1213. case ENGINE_OPTION_PLUGIN_PATH:
  1214. CARLA_SAFE_ASSERT_RETURN(value > PLUGIN_NONE,);
  1215. CARLA_SAFE_ASSERT_RETURN(value <= PLUGIN_SFZ,);
  1216. switch (value)
  1217. {
  1218. case PLUGIN_LADSPA:
  1219. if (pData->options.pathLADSPA != nullptr)
  1220. delete[] pData->options.pathLADSPA;
  1221. if (valueStr != nullptr)
  1222. pData->options.pathLADSPA = carla_strdup_safe(valueStr);
  1223. else
  1224. pData->options.pathLADSPA = nullptr;
  1225. break;
  1226. case PLUGIN_DSSI:
  1227. if (pData->options.pathDSSI != nullptr)
  1228. delete[] pData->options.pathDSSI;
  1229. if (valueStr != nullptr)
  1230. pData->options.pathDSSI = carla_strdup_safe(valueStr);
  1231. else
  1232. pData->options.pathDSSI = nullptr;
  1233. break;
  1234. case PLUGIN_LV2:
  1235. if (pData->options.pathLV2 != nullptr)
  1236. delete[] pData->options.pathLV2;
  1237. if (valueStr != nullptr)
  1238. pData->options.pathLV2 = carla_strdup_safe(valueStr);
  1239. else
  1240. pData->options.pathLV2 = nullptr;
  1241. break;
  1242. case PLUGIN_VST2:
  1243. if (pData->options.pathVST2 != nullptr)
  1244. delete[] pData->options.pathVST2;
  1245. if (valueStr != nullptr)
  1246. pData->options.pathVST2 = carla_strdup_safe(valueStr);
  1247. else
  1248. pData->options.pathVST2 = nullptr;
  1249. break;
  1250. case PLUGIN_VST3:
  1251. if (pData->options.pathVST3 != nullptr)
  1252. delete[] pData->options.pathVST3;
  1253. if (valueStr != nullptr)
  1254. pData->options.pathVST3 = carla_strdup_safe(valueStr);
  1255. else
  1256. pData->options.pathVST3 = nullptr;
  1257. break;
  1258. case PLUGIN_SF2:
  1259. if (pData->options.pathSF2 != nullptr)
  1260. delete[] pData->options.pathSF2;
  1261. if (valueStr != nullptr)
  1262. pData->options.pathSF2 = carla_strdup_safe(valueStr);
  1263. else
  1264. pData->options.pathSF2 = nullptr;
  1265. break;
  1266. case PLUGIN_SFZ:
  1267. if (pData->options.pathSFZ != nullptr)
  1268. delete[] pData->options.pathSFZ;
  1269. if (valueStr != nullptr)
  1270. pData->options.pathSFZ = carla_strdup_safe(valueStr);
  1271. else
  1272. pData->options.pathSFZ = nullptr;
  1273. break;
  1274. default:
  1275. return carla_stderr("CarlaEngine::setOption(%i:%s, %i, \"%s\") - Invalid plugin type", option, EngineOption2Str(option), value, valueStr);
  1276. break;
  1277. }
  1278. break;
  1279. case ENGINE_OPTION_PATH_BINARIES:
  1280. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1281. if (pData->options.binaryDir != nullptr)
  1282. delete[] pData->options.binaryDir;
  1283. pData->options.binaryDir = carla_strdup_safe(valueStr);
  1284. break;
  1285. case ENGINE_OPTION_PATH_RESOURCES:
  1286. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1287. if (pData->options.resourceDir != nullptr)
  1288. delete[] pData->options.resourceDir;
  1289. pData->options.resourceDir = carla_strdup_safe(valueStr);
  1290. break;
  1291. case ENGINE_OPTION_PREVENT_BAD_BEHAVIOUR: {
  1292. CARLA_SAFE_ASSERT_RETURN(pData->options.binaryDir != nullptr && pData->options.binaryDir[0] != '\0',);
  1293. #ifdef CARLA_OS_LINUX
  1294. const ScopedEngineEnvironmentLocker _seel(this);
  1295. if (value != 0)
  1296. {
  1297. CarlaString interposerPath(CarlaString(pData->options.binaryDir) + "/libcarla_interposer-safe.so");
  1298. ::setenv("LD_PRELOAD", interposerPath.buffer(), 1);
  1299. }
  1300. else
  1301. {
  1302. ::unsetenv("LD_PRELOAD");
  1303. }
  1304. #endif
  1305. } break;
  1306. case ENGINE_OPTION_FRONTEND_WIN_ID: {
  1307. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1308. const long long winId(std::strtoll(valueStr, nullptr, 16));
  1309. CARLA_SAFE_ASSERT_RETURN(winId >= 0,);
  1310. pData->options.frontendWinId = static_cast<uintptr_t>(winId);
  1311. } break;
  1312. #if !defined(BUILD_BRIDGE_ALTERNATIVE_ARCH) && !defined(CARLA_OS_WIN)
  1313. case ENGINE_OPTION_WINE_EXECUTABLE:
  1314. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1315. if (pData->options.wine.executable != nullptr)
  1316. delete[] pData->options.wine.executable;
  1317. pData->options.wine.executable = carla_strdup_safe(valueStr);
  1318. break;
  1319. case ENGINE_OPTION_WINE_AUTO_PREFIX:
  1320. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1321. pData->options.wine.autoPrefix = (value != 0);
  1322. break;
  1323. case ENGINE_OPTION_WINE_FALLBACK_PREFIX:
  1324. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1325. if (pData->options.wine.fallbackPrefix != nullptr)
  1326. delete[] pData->options.wine.fallbackPrefix;
  1327. pData->options.wine.fallbackPrefix = carla_strdup_safe(valueStr);
  1328. break;
  1329. case ENGINE_OPTION_WINE_RT_PRIO_ENABLED:
  1330. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1331. pData->options.wine.rtPrio = (value != 0);
  1332. break;
  1333. case ENGINE_OPTION_WINE_BASE_RT_PRIO:
  1334. CARLA_SAFE_ASSERT_RETURN(value >= 1 && value <= 89,);
  1335. pData->options.wine.baseRtPrio = value;
  1336. break;
  1337. case ENGINE_OPTION_WINE_SERVER_RT_PRIO:
  1338. CARLA_SAFE_ASSERT_RETURN(value >= 1 && value <= 99,);
  1339. pData->options.wine.serverRtPrio = value;
  1340. break;
  1341. #endif
  1342. case ENGINE_OPTION_DEBUG_CONSOLE_OUTPUT:
  1343. break;
  1344. }
  1345. }
  1346. #ifndef BUILD_BRIDGE
  1347. // -----------------------------------------------------------------------
  1348. // OSC Stuff
  1349. bool CarlaEngine::isOscControlRegistered() const noexcept
  1350. {
  1351. # ifdef HAVE_LIBLO
  1352. return pData->osc.isControlRegistered();
  1353. # else
  1354. return false;
  1355. # endif
  1356. }
  1357. void CarlaEngine::idleOsc() const noexcept
  1358. {
  1359. # ifdef HAVE_LIBLO
  1360. pData->osc.idle();
  1361. # endif
  1362. }
  1363. const char* CarlaEngine::getOscServerPathTCP() const noexcept
  1364. {
  1365. # ifdef HAVE_LIBLO
  1366. return pData->osc.getServerPathTCP();
  1367. # else
  1368. return nullptr;
  1369. # endif
  1370. }
  1371. const char* CarlaEngine::getOscServerPathUDP() const noexcept
  1372. {
  1373. # ifdef HAVE_LIBLO
  1374. return pData->osc.getServerPathUDP();
  1375. # else
  1376. return nullptr;
  1377. # endif
  1378. }
  1379. #endif
  1380. // -----------------------------------------------------------------------
  1381. // Helper functions
  1382. EngineEvent* CarlaEngine::getInternalEventBuffer(const bool isInput) const noexcept
  1383. {
  1384. return isInput ? pData->events.in : pData->events.out;
  1385. }
  1386. // -----------------------------------------------------------------------
  1387. // Internal stuff
  1388. void CarlaEngine::bufferSizeChanged(const uint32_t newBufferSize)
  1389. {
  1390. carla_debug("CarlaEngine::bufferSizeChanged(%i)", newBufferSize);
  1391. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1392. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1393. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1394. {
  1395. pData->graph.setBufferSize(newBufferSize);
  1396. }
  1397. #endif
  1398. pData->time.updateAudioValues(newBufferSize, pData->sampleRate);
  1399. for (uint i=0; i < pData->curPluginCount; ++i)
  1400. {
  1401. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1402. if (plugin != nullptr && plugin->isEnabled())
  1403. {
  1404. plugin->tryLock(true);
  1405. plugin->bufferSizeChanged(newBufferSize);
  1406. plugin->unlock();
  1407. }
  1408. }
  1409. callback(ENGINE_CALLBACK_BUFFER_SIZE_CHANGED, 0, static_cast<int>(newBufferSize), 0, 0.0f, nullptr);
  1410. }
  1411. void CarlaEngine::sampleRateChanged(const double newSampleRate)
  1412. {
  1413. carla_debug("CarlaEngine::sampleRateChanged(%g)", newSampleRate);
  1414. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1415. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1416. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1417. {
  1418. pData->graph.setSampleRate(newSampleRate);
  1419. }
  1420. #endif
  1421. pData->time.updateAudioValues(pData->bufferSize, newSampleRate);
  1422. for (uint i=0; i < pData->curPluginCount; ++i)
  1423. {
  1424. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1425. if (plugin != nullptr && plugin->isEnabled())
  1426. {
  1427. plugin->tryLock(true);
  1428. plugin->sampleRateChanged(newSampleRate);
  1429. plugin->unlock();
  1430. }
  1431. }
  1432. callback(ENGINE_CALLBACK_SAMPLE_RATE_CHANGED, 0, 0, 0, static_cast<float>(newSampleRate), nullptr);
  1433. }
  1434. void CarlaEngine::offlineModeChanged(const bool isOfflineNow)
  1435. {
  1436. carla_debug("CarlaEngine::offlineModeChanged(%s)", bool2str(isOfflineNow));
  1437. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1438. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1439. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1440. {
  1441. pData->graph.setOffline(isOfflineNow);
  1442. }
  1443. #endif
  1444. for (uint i=0; i < pData->curPluginCount; ++i)
  1445. {
  1446. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1447. if (plugin != nullptr && plugin->isEnabled())
  1448. plugin->offlineModeChanged(isOfflineNow);
  1449. }
  1450. }
  1451. void CarlaEngine::setPluginPeaks(const uint pluginId, float const inPeaks[2], float const outPeaks[2]) noexcept
  1452. {
  1453. EnginePluginData& pluginData(pData->plugins[pluginId]);
  1454. pluginData.peaks[0] = inPeaks[0];
  1455. pluginData.peaks[1] = inPeaks[1];
  1456. pluginData.peaks[2] = outPeaks[0];
  1457. pluginData.peaks[3] = outPeaks[1];
  1458. }
  1459. void CarlaEngine::saveProjectInternal(water::MemoryOutputStream& outStream) const
  1460. {
  1461. // send initial prepareForSave first, giving time for bridges to act
  1462. for (uint i=0; i < pData->curPluginCount; ++i)
  1463. {
  1464. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1465. if (plugin != nullptr && plugin->isEnabled())
  1466. {
  1467. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1468. // deactivate bridge client-side ping check, since some plugins block during save
  1469. if (plugin->getHints() & PLUGIN_IS_BRIDGE)
  1470. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "false", false);
  1471. #endif
  1472. plugin->prepareForSave();
  1473. }
  1474. }
  1475. outStream << "<?xml version='1.0' encoding='UTF-8'?>\n";
  1476. outStream << "<!DOCTYPE CARLA-PROJECT>\n";
  1477. outStream << "<CARLA-PROJECT VERSION='2.0'>\n";
  1478. const bool isPlugin(getType() == kEngineTypePlugin);
  1479. const EngineOptions& options(pData->options);
  1480. {
  1481. MemoryOutputStream outSettings(1024);
  1482. outSettings << " <EngineSettings>\n";
  1483. outSettings << " <ForceStereo>" << bool2str(options.forceStereo) << "</ForceStereo>\n";
  1484. outSettings << " <PreferPluginBridges>" << bool2str(options.preferPluginBridges) << "</PreferPluginBridges>\n";
  1485. outSettings << " <PreferUiBridges>" << bool2str(options.preferUiBridges) << "</PreferUiBridges>\n";
  1486. outSettings << " <UIsAlwaysOnTop>" << bool2str(options.uisAlwaysOnTop) << "</UIsAlwaysOnTop>\n";
  1487. outSettings << " <MaxParameters>" << String(options.maxParameters) << "</MaxParameters>\n";
  1488. outSettings << " <UIBridgesTimeout>" << String(options.uiBridgesTimeout) << "</UIBridgesTimeout>\n";
  1489. if (isPlugin)
  1490. {
  1491. outSettings << " <LADSPA_PATH>" << xmlSafeString(options.pathLADSPA, true) << "</LADSPA_PATH>\n";
  1492. outSettings << " <DSSI_PATH>" << xmlSafeString(options.pathDSSI, true) << "</DSSI_PATH>\n";
  1493. outSettings << " <LV2_PATH>" << xmlSafeString(options.pathLV2, true) << "</LV2_PATH>\n";
  1494. outSettings << " <VST2_PATH>" << xmlSafeString(options.pathVST2, true) << "</VST2_PATH>\n";
  1495. outSettings << " <VST3_PATH>" << xmlSafeString(options.pathVST3, true) << "</VST3_PATH>\n";
  1496. outSettings << " <SF2_PATH>" << xmlSafeString(options.pathSF2, true) << "</SF2_PATH>\n";
  1497. outSettings << " <SFZ_PATH>" << xmlSafeString(options.pathSFZ, true) << "</SFZ_PATH>\n";
  1498. }
  1499. outSettings << " </EngineSettings>\n";
  1500. outStream << outSettings;
  1501. }
  1502. if (pData->timeInfo.bbt.valid && ! isPlugin)
  1503. {
  1504. MemoryOutputStream outTransport(128);
  1505. outTransport << "\n <Transport>\n";
  1506. // outTransport << " <BeatsPerBar>" << pData->timeInfo.bbt.beatsPerBar << "</BeatsPerBar>\n";
  1507. outTransport << " <BeatsPerMinute>" << pData->timeInfo.bbt.beatsPerMinute << "</BeatsPerMinute>\n";
  1508. outTransport << " </Transport>\n";
  1509. outStream << outTransport;
  1510. }
  1511. char strBuf[STR_MAX+1];
  1512. for (uint i=0; i < pData->curPluginCount; ++i)
  1513. {
  1514. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1515. if (plugin != nullptr && plugin->isEnabled())
  1516. {
  1517. MemoryOutputStream outPlugin(4096), streamPlugin;
  1518. plugin->getStateSave(false).dumpToMemoryStream(streamPlugin);
  1519. outPlugin << "\n";
  1520. strBuf[0] = '\0';
  1521. plugin->getRealName(strBuf);
  1522. if (strBuf[0] != '\0')
  1523. outPlugin << " <!-- " << xmlSafeString(strBuf, true) << " -->\n";
  1524. outPlugin << " <Plugin>\n";
  1525. outPlugin << streamPlugin;
  1526. outPlugin << " </Plugin>\n";
  1527. outStream << outPlugin;
  1528. }
  1529. }
  1530. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1531. // tell bridges we're done saving
  1532. for (uint i=0; i < pData->curPluginCount; ++i)
  1533. {
  1534. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1535. if (plugin != nullptr && plugin->isEnabled() && (plugin->getHints() & PLUGIN_IS_BRIDGE) != 0)
  1536. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "true", false);
  1537. }
  1538. // save internal connections
  1539. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1540. {
  1541. if (const char* const* const patchbayConns = getPatchbayConnections(false))
  1542. {
  1543. MemoryOutputStream outPatchbay(2048);
  1544. outPatchbay << "\n <Patchbay>\n";
  1545. for (int i=0; patchbayConns[i] != nullptr && patchbayConns[i+1] != nullptr; ++i, ++i )
  1546. {
  1547. const char* const connSource(patchbayConns[i]);
  1548. const char* const connTarget(patchbayConns[i+1]);
  1549. CARLA_SAFE_ASSERT_CONTINUE(connSource != nullptr && connSource[0] != '\0');
  1550. CARLA_SAFE_ASSERT_CONTINUE(connTarget != nullptr && connTarget[0] != '\0');
  1551. outPatchbay << " <Connection>\n";
  1552. outPatchbay << " <Source>" << xmlSafeString(connSource, true) << "</Source>\n";
  1553. outPatchbay << " <Target>" << xmlSafeString(connTarget, true) << "</Target>\n";
  1554. outPatchbay << " </Connection>\n";
  1555. }
  1556. outPatchbay << " </Patchbay>\n";
  1557. outStream << outPatchbay;
  1558. }
  1559. }
  1560. // if we're running inside some session-manager (and using JACK), let them handle the connections
  1561. bool saveExternalConnections;
  1562. /**/ if (isPlugin)
  1563. saveExternalConnections = false;
  1564. else if (std::strcmp(getCurrentDriverName(), "JACK") != 0)
  1565. saveExternalConnections = true;
  1566. else if (std::getenv("CARLA_DONT_MANAGE_CONNECTIONS") != nullptr)
  1567. saveExternalConnections = false;
  1568. else if (std::getenv("LADISH_APP_NAME") != nullptr)
  1569. saveExternalConnections = false;
  1570. else if (std::getenv("NSM_URL") != nullptr)
  1571. saveExternalConnections = false;
  1572. else
  1573. saveExternalConnections = true;
  1574. if (saveExternalConnections)
  1575. {
  1576. if (const char* const* const patchbayConns = getPatchbayConnections(true))
  1577. {
  1578. MemoryOutputStream outPatchbay(2048);
  1579. outPatchbay << "\n <ExternalPatchbay>\n";
  1580. for (int i=0; patchbayConns[i] != nullptr && patchbayConns[i+1] != nullptr; ++i, ++i )
  1581. {
  1582. const char* const connSource(patchbayConns[i]);
  1583. const char* const connTarget(patchbayConns[i+1]);
  1584. CARLA_SAFE_ASSERT_CONTINUE(connSource != nullptr && connSource[0] != '\0');
  1585. CARLA_SAFE_ASSERT_CONTINUE(connTarget != nullptr && connTarget[0] != '\0');
  1586. outPatchbay << " <Connection>\n";
  1587. outPatchbay << " <Source>" << xmlSafeString(connSource, true) << "</Source>\n";
  1588. outPatchbay << " <Target>" << xmlSafeString(connTarget, true) << "</Target>\n";
  1589. outPatchbay << " </Connection>\n";
  1590. }
  1591. outPatchbay << " </ExternalPatchbay>\n";
  1592. outStream << outPatchbay;
  1593. }
  1594. }
  1595. #endif
  1596. outStream << "</CARLA-PROJECT>\n";
  1597. }
  1598. static String findBinaryInCustomPath(const char* const searchPath, const char* const binary)
  1599. {
  1600. const StringArray searchPaths(StringArray::fromTokens(searchPath, CARLA_OS_SPLIT_STR, ""));
  1601. // try direct filename first
  1602. String jbinary(binary);
  1603. // adjust for current platform
  1604. #ifdef CARLA_OS_WIN
  1605. if (jbinary[0] == '/')
  1606. jbinary = "C:" + jbinary.replaceCharacter('/', '\\');
  1607. #else
  1608. if (jbinary[1] == ':' && (jbinary[2] == '\\' || jbinary[2] == '/'))
  1609. jbinary = jbinary.substring(2).replaceCharacter('\\', '/');
  1610. #endif
  1611. String filename = File(jbinary).getFileName();
  1612. int searchFlags = File::findFiles|File::ignoreHiddenFiles;
  1613. #ifdef CARLA_OS_MAC
  1614. if (filename.endsWithIgnoreCase(".vst") || filename.endsWithIgnoreCase(".vst3"))
  1615. searchFlags |= File::findDirectories;
  1616. #endif
  1617. Array<File> results;
  1618. for (const String *it=searchPaths.begin(), *end=searchPaths.end(); it != end; ++it)
  1619. {
  1620. const File path(*it);
  1621. results.clear();
  1622. path.findChildFiles(results, searchFlags, true, filename);
  1623. if (results.size() > 0)
  1624. return results.getFirst().getFullPathName();
  1625. }
  1626. // try changing extension
  1627. #if defined(CARLA_OS_MAC)
  1628. if (filename.endsWithIgnoreCase(".dll") || filename.endsWithIgnoreCase(".so"))
  1629. filename = File(jbinary).getFileNameWithoutExtension() + ".dylib";
  1630. #elif defined(CARLA_OS_WIN)
  1631. if (filename.endsWithIgnoreCase(".dylib") || filename.endsWithIgnoreCase(".so"))
  1632. filename = File(jbinary).getFileNameWithoutExtension() + ".dll";
  1633. #else
  1634. if (filename.endsWithIgnoreCase(".dll") || filename.endsWithIgnoreCase(".dylib"))
  1635. filename = File(jbinary).getFileNameWithoutExtension() + ".so";
  1636. #endif
  1637. else
  1638. return String();
  1639. for (const String *it=searchPaths.begin(), *end=searchPaths.end(); it != end; ++it)
  1640. {
  1641. const File path(*it);
  1642. results.clear();
  1643. path.findChildFiles(results, searchFlags, true, filename);
  1644. if (results.size() > 0)
  1645. return results.getFirst().getFullPathName();
  1646. }
  1647. return String();
  1648. }
  1649. bool CarlaEngine::loadProjectInternal(water::XmlDocument& xmlDoc)
  1650. {
  1651. ScopedPointer<XmlElement> xmlElement(xmlDoc.getDocumentElement(true));
  1652. CARLA_SAFE_ASSERT_RETURN_ERR(xmlElement != nullptr, "Failed to parse project file");
  1653. const String& xmlType(xmlElement->getTagName());
  1654. const bool isPreset(xmlType.equalsIgnoreCase("carla-preset"));
  1655. if (! (xmlType.equalsIgnoreCase("carla-project") || isPreset))
  1656. {
  1657. callback(ENGINE_CALLBACK_PROJECT_LOAD_FINISHED, 0, 0, 0, 0.0f, nullptr);
  1658. setLastError("Not a valid Carla project or preset file");
  1659. return false;
  1660. }
  1661. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1662. const ScopedValueSetter<bool> _svs(pData->loadingProject, true, false);
  1663. #endif
  1664. // completely load file
  1665. xmlElement = xmlDoc.getDocumentElement(false);
  1666. CARLA_SAFE_ASSERT_RETURN_ERR(xmlElement != nullptr, "Failed to completely parse project file");
  1667. if (pData->aboutToClose)
  1668. return true;
  1669. const bool isPlugin(getType() == kEngineTypePlugin);
  1670. // load engine settings first of all
  1671. if (XmlElement* const elem = isPreset ? nullptr : xmlElement->getChildByName("EngineSettings"))
  1672. {
  1673. for (XmlElement* settElem = elem->getFirstChildElement(); settElem != nullptr; settElem = settElem->getNextElement())
  1674. {
  1675. const String& tag(settElem->getTagName());
  1676. const String text(settElem->getAllSubText().trim());
  1677. /** some settings might be incorrect or require extra work,
  1678. so we call setOption rather than modifying them direly */
  1679. int option = -1;
  1680. int value = 0;
  1681. const char* valueStr = nullptr;
  1682. /**/ if (tag == "ForceStereo")
  1683. {
  1684. option = ENGINE_OPTION_FORCE_STEREO;
  1685. value = text == "true" ? 1 : 0;
  1686. }
  1687. else if (tag == "PreferPluginBridges")
  1688. {
  1689. option = ENGINE_OPTION_PREFER_PLUGIN_BRIDGES;
  1690. value = text == "true" ? 1 : 0;
  1691. }
  1692. else if (tag == "PreferUiBridges")
  1693. {
  1694. option = ENGINE_OPTION_PREFER_UI_BRIDGES;
  1695. value = text == "true" ? 1 : 0;
  1696. }
  1697. else if (tag == "UIsAlwaysOnTop")
  1698. {
  1699. option = ENGINE_OPTION_UIS_ALWAYS_ON_TOP;
  1700. value = text == "true" ? 1 : 0;
  1701. }
  1702. else if (tag == "MaxParameters")
  1703. {
  1704. option = ENGINE_OPTION_MAX_PARAMETERS;
  1705. value = text.getIntValue();
  1706. }
  1707. else if (tag == "UIBridgesTimeout")
  1708. {
  1709. option = ENGINE_OPTION_UI_BRIDGES_TIMEOUT;
  1710. value = text.getIntValue();
  1711. }
  1712. else if (isPlugin)
  1713. {
  1714. /**/ if (tag == "LADSPA_PATH")
  1715. {
  1716. option = ENGINE_OPTION_PLUGIN_PATH;
  1717. value = PLUGIN_LADSPA;
  1718. valueStr = text.toRawUTF8();
  1719. }
  1720. else if (tag == "DSSI_PATH")
  1721. {
  1722. option = ENGINE_OPTION_PLUGIN_PATH;
  1723. value = PLUGIN_DSSI;
  1724. valueStr = text.toRawUTF8();
  1725. }
  1726. else if (tag == "LV2_PATH")
  1727. {
  1728. option = ENGINE_OPTION_PLUGIN_PATH;
  1729. value = PLUGIN_LV2;
  1730. valueStr = text.toRawUTF8();
  1731. }
  1732. else if (tag == "VST2_PATH")
  1733. {
  1734. option = ENGINE_OPTION_PLUGIN_PATH;
  1735. value = PLUGIN_VST2;
  1736. valueStr = text.toRawUTF8();
  1737. }
  1738. else if (tag.equalsIgnoreCase("VST3_PATH"))
  1739. {
  1740. option = ENGINE_OPTION_PLUGIN_PATH;
  1741. value = PLUGIN_VST3;
  1742. valueStr = text.toRawUTF8();
  1743. }
  1744. else if (tag == "SF2_PATH")
  1745. {
  1746. option = ENGINE_OPTION_PLUGIN_PATH;
  1747. value = PLUGIN_SF2;
  1748. valueStr = text.toRawUTF8();
  1749. }
  1750. else if (tag == "SFZ_PATH")
  1751. {
  1752. option = ENGINE_OPTION_PLUGIN_PATH;
  1753. value = PLUGIN_SFZ;
  1754. valueStr = text.toRawUTF8();
  1755. }
  1756. }
  1757. if (option == -1)
  1758. {
  1759. // check old stuff, unhandled now
  1760. if (tag == "GIG_PATH")
  1761. continue;
  1762. // ignored tags
  1763. if (tag == "LADSPA_PATH" || tag == "DSSI_PATH" || tag == "LV2_PATH" || tag == "VST2_PATH")
  1764. continue;
  1765. if (tag == "VST3_PATH" || tag == "AU_PATH")
  1766. continue;
  1767. if (tag == "SF2_PATH" || tag == "SFZ_PATH")
  1768. continue;
  1769. // hmm something is wrong..
  1770. carla_stderr2("CarlaEngine::loadProjectInternal() - Unhandled option '%s'", tag.toRawUTF8());
  1771. continue;
  1772. }
  1773. setOption(static_cast<EngineOption>(option), value, valueStr);
  1774. }
  1775. }
  1776. if (pData->aboutToClose)
  1777. return true;
  1778. // now setup transport
  1779. if (XmlElement* const elem = (isPreset || isPlugin) ? nullptr : xmlElement->getChildByName("Transport"))
  1780. {
  1781. if (XmlElement* const bpmElem = elem->getChildByName("BeatsPerMinute"))
  1782. {
  1783. const String bpmText(bpmElem->getAllSubText().trim());
  1784. const double bpm = bpmText.getDoubleValue();
  1785. // some sane limits
  1786. if (bpm >= 20.0 && bpm < 400.0)
  1787. pData->time.setBPM(bpm);
  1788. }
  1789. }
  1790. if (pData->aboutToClose)
  1791. return true;
  1792. // and we handle plugins
  1793. for (XmlElement* elem = xmlElement->getFirstChildElement(); elem != nullptr; elem = elem->getNextElement())
  1794. {
  1795. const String& tagName(elem->getTagName());
  1796. if (isPreset || tagName == "Plugin")
  1797. {
  1798. CarlaStateSave stateSave;
  1799. stateSave.fillFromXmlElement(isPreset ? xmlElement.get() : elem);
  1800. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  1801. if (pData->aboutToClose)
  1802. return true;
  1803. CARLA_SAFE_ASSERT_CONTINUE(stateSave.type != nullptr);
  1804. #ifndef BUILD_BRIDGE
  1805. // compatibility code to load projects with GIG files
  1806. // FIXME Remove on 2.1 release
  1807. if (std::strcmp(stateSave.type, "GIG") == 0)
  1808. {
  1809. if (addPlugin(PLUGIN_LV2, "", stateSave.name, "http://linuxsampler.org/plugins/linuxsampler", 0, nullptr))
  1810. {
  1811. const uint pluginId = pData->curPluginCount;
  1812. if (CarlaPlugin* const plugin = pData->plugins[pluginId].plugin)
  1813. {
  1814. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  1815. if (pData->aboutToClose)
  1816. return true;
  1817. String lsState;
  1818. lsState << "0.35\n";
  1819. lsState << "18 0 Chromatic\n";
  1820. lsState << "18 1 Drum Kits\n";
  1821. lsState << "20 0\n";
  1822. lsState << "0 1 " << stateSave.binary << "\n";
  1823. lsState << "0 0 0 0 1 0 GIG\n";
  1824. plugin->setCustomData(LV2_ATOM__String, "http://linuxsampler.org/schema#state-string", lsState.toRawUTF8(), true);
  1825. plugin->restoreLV2State();
  1826. plugin->setDryWet(stateSave.dryWet, true, true);
  1827. plugin->setVolume(stateSave.volume, true, true);
  1828. plugin->setBalanceLeft(stateSave.balanceLeft, true, true);
  1829. plugin->setBalanceRight(stateSave.balanceRight, true, true);
  1830. plugin->setPanning(stateSave.panning, true, true);
  1831. plugin->setCtrlChannel(stateSave.ctrlChannel, true, true);
  1832. plugin->setActive(stateSave.active, true, true);
  1833. ++pData->curPluginCount;
  1834. plugin->setEnabled(true);
  1835. callback(ENGINE_CALLBACK_PLUGIN_ADDED, pluginId, 0, 0, 0.0f, plugin->getName());
  1836. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1837. pData->graph.addPlugin(plugin);
  1838. }
  1839. else
  1840. {
  1841. carla_stderr2("Failed to get new plugin, state will not be restored correctly\n");
  1842. }
  1843. }
  1844. else
  1845. {
  1846. carla_stderr2("Failed to load a linuxsampler LV2 plugin, GIG file won't be loaded");
  1847. }
  1848. continue;
  1849. }
  1850. #endif
  1851. const void* extraStuff = nullptr;
  1852. static const char kTrue[] = "true";
  1853. const PluginType ptype(getPluginTypeFromString(stateSave.type));
  1854. switch (ptype)
  1855. {
  1856. case PLUGIN_SF2:
  1857. if (CarlaString(stateSave.label).endsWith(" (16 outs)"))
  1858. extraStuff = kTrue;
  1859. // fall through
  1860. case PLUGIN_LADSPA:
  1861. case PLUGIN_DSSI:
  1862. case PLUGIN_VST2:
  1863. case PLUGIN_VST3:
  1864. case PLUGIN_SFZ:
  1865. if (stateSave.binary != nullptr && stateSave.binary[0] != '\0' &&
  1866. ! (File::isAbsolutePath(stateSave.binary) && File(stateSave.binary).exists()))
  1867. {
  1868. const char* searchPath;
  1869. switch (ptype)
  1870. {
  1871. case PLUGIN_LADSPA: searchPath = pData->options.pathLADSPA; break;
  1872. case PLUGIN_DSSI: searchPath = pData->options.pathDSSI; break;
  1873. case PLUGIN_VST2: searchPath = pData->options.pathVST2; break;
  1874. case PLUGIN_VST3: searchPath = pData->options.pathVST3; break;
  1875. case PLUGIN_SF2: searchPath = pData->options.pathSF2; break;
  1876. case PLUGIN_SFZ: searchPath = pData->options.pathSFZ; break;
  1877. default: searchPath = nullptr; break;
  1878. }
  1879. if (searchPath != nullptr && searchPath[0] != '\0')
  1880. {
  1881. carla_stderr("Plugin binary '%s' doesn't exist on this filesystem, let's look for it...",
  1882. stateSave.binary);
  1883. String result = findBinaryInCustomPath(searchPath, stateSave.binary);
  1884. if (result.isEmpty())
  1885. {
  1886. switch (ptype)
  1887. {
  1888. case PLUGIN_LADSPA: searchPath = std::getenv("LADSPA_PATH"); break;
  1889. case PLUGIN_DSSI: searchPath = std::getenv("DSSI_PATH"); break;
  1890. case PLUGIN_VST2: searchPath = std::getenv("VST_PATH"); break;
  1891. case PLUGIN_VST3: searchPath = std::getenv("VST3_PATH"); break;
  1892. case PLUGIN_SF2: searchPath = std::getenv("SF2_PATH"); break;
  1893. case PLUGIN_SFZ: searchPath = std::getenv("SFZ_PATH"); break;
  1894. default: searchPath = nullptr; break;
  1895. }
  1896. if (searchPath != nullptr && searchPath[0] != '\0')
  1897. result = findBinaryInCustomPath(searchPath, stateSave.binary);
  1898. }
  1899. if (result.isNotEmpty())
  1900. {
  1901. delete[] stateSave.binary;
  1902. stateSave.binary = carla_strdup(result.toRawUTF8());
  1903. carla_stderr("Found it! :)");
  1904. }
  1905. else
  1906. {
  1907. carla_stderr("Damn, we failed... :(");
  1908. }
  1909. }
  1910. }
  1911. break;
  1912. default:
  1913. break;
  1914. }
  1915. BinaryType btype;
  1916. switch (ptype)
  1917. {
  1918. case PLUGIN_LADSPA:
  1919. case PLUGIN_DSSI:
  1920. case PLUGIN_LV2:
  1921. case PLUGIN_VST2:
  1922. btype = getBinaryTypeFromFile(stateSave.binary);
  1923. break;
  1924. default:
  1925. btype = BINARY_NATIVE;
  1926. break;
  1927. }
  1928. if (addPlugin(btype, ptype, stateSave.binary,
  1929. stateSave.name, stateSave.label, stateSave.uniqueId, extraStuff, stateSave.options))
  1930. {
  1931. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1932. const uint pluginId = pData->curPluginCount;
  1933. #else
  1934. const uint pluginId = 0;
  1935. #endif
  1936. if (CarlaPlugin* const plugin = pData->plugins[pluginId].plugin)
  1937. {
  1938. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  1939. if (pData->aboutToClose)
  1940. return true;
  1941. // deactivate bridge client-side ping check, since some plugins block during load
  1942. if ((plugin->getHints() & PLUGIN_IS_BRIDGE) != 0 && ! isPreset)
  1943. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "false", false);
  1944. plugin->loadStateSave(stateSave);
  1945. /* NOTE: The following code is the same as the end of addPlugin().
  1946. * When project is loading we do not enable the plugin right away,
  1947. * as we want to load state first.
  1948. */
  1949. plugin->setEnabled(true);
  1950. ++pData->curPluginCount;
  1951. callback(ENGINE_CALLBACK_PLUGIN_ADDED, pluginId, 0, 0, 0.0f, plugin->getName());
  1952. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1953. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1954. pData->graph.addPlugin(plugin);
  1955. #endif
  1956. }
  1957. else
  1958. {
  1959. carla_stderr2("Failed to get new plugin, state will not be restored correctly\n");
  1960. }
  1961. }
  1962. else
  1963. {
  1964. carla_stderr2("Failed to load a plugin '%s', error was:\n%s", stateSave.name, getLastError());
  1965. }
  1966. }
  1967. if (isPreset)
  1968. {
  1969. callback(ENGINE_CALLBACK_PROJECT_LOAD_FINISHED, 0, 0, 0, 0.0f, nullptr);
  1970. return true;
  1971. }
  1972. }
  1973. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1974. // tell bridges we're done loading
  1975. for (uint i=0; i < pData->curPluginCount; ++i)
  1976. {
  1977. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1978. if (plugin != nullptr && plugin->isEnabled() && (plugin->getHints() & PLUGIN_IS_BRIDGE) != 0)
  1979. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "true", false);
  1980. }
  1981. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  1982. if (pData->aboutToClose)
  1983. return true;
  1984. bool hasInternalConnections = false;
  1985. // and now we handle connections (internal)
  1986. if (XmlElement* const elem = xmlElement->getChildByName("Patchbay"))
  1987. {
  1988. hasInternalConnections = true;
  1989. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1990. {
  1991. CarlaString sourcePort, targetPort;
  1992. const bool isUsingExternal(pData->graph.isUsingExternal());
  1993. for (XmlElement* patchElem = elem->getFirstChildElement(); patchElem != nullptr; patchElem = patchElem->getNextElement())
  1994. {
  1995. const String& patchTag(patchElem->getTagName());
  1996. if (patchTag != "Connection")
  1997. continue;
  1998. sourcePort.clear();
  1999. targetPort.clear();
  2000. for (XmlElement* connElem = patchElem->getFirstChildElement(); connElem != nullptr; connElem = connElem->getNextElement())
  2001. {
  2002. const String& tag(connElem->getTagName());
  2003. const String text(connElem->getAllSubText().trim());
  2004. /**/ if (tag == "Source")
  2005. sourcePort = xmlSafeString(text, false).toRawUTF8();
  2006. else if (tag == "Target")
  2007. targetPort = xmlSafeString(text, false).toRawUTF8();
  2008. }
  2009. if (sourcePort.isNotEmpty() && targetPort.isNotEmpty())
  2010. restorePatchbayConnection(false, sourcePort, targetPort, !isUsingExternal);
  2011. }
  2012. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  2013. if (pData->aboutToClose)
  2014. return true;
  2015. }
  2016. }
  2017. // if we're running inside some session-manager (and using JACK), let them handle the external connections
  2018. bool loadExternalConnections;
  2019. /**/ if (std::strcmp(getCurrentDriverName(), "JACK") != 0)
  2020. loadExternalConnections = true;
  2021. else if (std::getenv("CARLA_DONT_MANAGE_CONNECTIONS") != nullptr)
  2022. loadExternalConnections = false;
  2023. else if (std::getenv("LADISH_APP_NAME") != nullptr)
  2024. loadExternalConnections = false;
  2025. else if (std::getenv("NSM_URL") != nullptr)
  2026. loadExternalConnections = false;
  2027. else
  2028. loadExternalConnections = true;
  2029. // plus external connections too
  2030. if (loadExternalConnections)
  2031. {
  2032. const bool isUsingExternal = pData->options.processMode != ENGINE_PROCESS_MODE_PATCHBAY ||
  2033. pData->graph.isUsingExternal();
  2034. const bool loadingAsExternal = pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY &&
  2035. hasInternalConnections;
  2036. for (XmlElement* elem = xmlElement->getFirstChildElement(); elem != nullptr; elem = elem->getNextElement())
  2037. {
  2038. const String& tagName(elem->getTagName());
  2039. // check if we want to load patchbay-mode connections into an external (multi-client) graph
  2040. if (tagName == "Patchbay")
  2041. {
  2042. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  2043. continue;
  2044. }
  2045. // or load external patchbay connections
  2046. else if (tagName != "ExternalPatchbay")
  2047. {
  2048. continue;
  2049. }
  2050. CarlaString sourcePort, targetPort;
  2051. for (XmlElement* patchElem = elem->getFirstChildElement(); patchElem != nullptr; patchElem = patchElem->getNextElement())
  2052. {
  2053. const String& patchTag(patchElem->getTagName());
  2054. if (patchTag != "Connection")
  2055. continue;
  2056. sourcePort.clear();
  2057. targetPort.clear();
  2058. for (XmlElement* connElem = patchElem->getFirstChildElement(); connElem != nullptr; connElem = connElem->getNextElement())
  2059. {
  2060. const String& tag(connElem->getTagName());
  2061. const String text(connElem->getAllSubText().trim());
  2062. /**/ if (tag == "Source")
  2063. sourcePort = xmlSafeString(text, false).toRawUTF8();
  2064. else if (tag == "Target")
  2065. targetPort = xmlSafeString(text, false).toRawUTF8();
  2066. }
  2067. if (sourcePort.isNotEmpty() && targetPort.isNotEmpty())
  2068. restorePatchbayConnection(loadingAsExternal, sourcePort, targetPort, isUsingExternal);
  2069. }
  2070. break;
  2071. }
  2072. }
  2073. #endif
  2074. callback(ENGINE_CALLBACK_PROJECT_LOAD_FINISHED, 0, 0, 0, 0.0f, nullptr);
  2075. return true;
  2076. }
  2077. // -----------------------------------------------------------------------
  2078. CARLA_BACKEND_END_NAMESPACE