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.

3417 lines
116KB

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