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.

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