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.

3327 lines
112KB

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