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.

3176 lines
105KB

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