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.

3414 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. newPlugin->loadStateSave(plugin->getStateSave());
  767. return true;
  768. }
  769. bool CarlaEngine::replacePlugin(const uint id) noexcept
  770. {
  771. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  772. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  773. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount != 0, "Invalid engine internal data");
  774. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  775. carla_debug("CarlaEngine::replacePlugin(%i)", id);
  776. // might use this to reset
  777. if (id == pData->maxPluginNumber)
  778. {
  779. pData->nextPluginId = pData->maxPluginNumber;
  780. return true;
  781. }
  782. CARLA_SAFE_ASSERT_RETURN_ERR(id < pData->curPluginCount, "Invalid plugin Id");
  783. const CarlaPluginPtr plugin = pData->plugins[id].plugin;
  784. CARLA_SAFE_ASSERT_RETURN_ERR(plugin.get() != nullptr, "Could not find plugin to replace");
  785. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  786. pData->nextPluginId = id;
  787. return true;
  788. }
  789. bool CarlaEngine::switchPlugins(const uint idA, const uint idB) noexcept
  790. {
  791. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  792. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  793. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount >= 2, "Invalid engine internal data");
  794. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  795. CARLA_SAFE_ASSERT_RETURN_ERR(idA != idB, "Invalid operation, cannot switch plugin with itself");
  796. CARLA_SAFE_ASSERT_RETURN_ERR(idA < pData->curPluginCount, "Invalid plugin Id");
  797. CARLA_SAFE_ASSERT_RETURN_ERR(idB < pData->curPluginCount, "Invalid plugin Id");
  798. carla_debug("CarlaEngine::switchPlugins(%i)", idA, idB);
  799. const CarlaPluginPtr pluginA = pData->plugins[idA].plugin;
  800. const CarlaPluginPtr pluginB = pData->plugins[idB].plugin;
  801. CARLA_SAFE_ASSERT_RETURN_ERR(pluginA.get() != nullptr, "Could not find plugin to switch");
  802. CARLA_SAFE_ASSERT_RETURN_ERR(pluginB.get() != nullptr, "Could not find plugin to switch");
  803. CARLA_SAFE_ASSERT_RETURN_ERR(pluginA->getId() == idA, "Invalid engine internal data");
  804. CARLA_SAFE_ASSERT_RETURN_ERR(pluginB->getId() == idB, "Invalid engine internal data");
  805. const ScopedThreadStopper sts(this);
  806. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  807. pData->graph.replacePlugin(pluginA, pluginB);
  808. const ScopedActionLock sal(this, kEnginePostActionSwitchPlugins, idA, idB);
  809. // TODO
  810. /*
  811. pluginA->updateOscURL();
  812. pluginB->updateOscURL();
  813. if (isOscControlRegistered())
  814. oscSend_control_switch_plugins(idA, idB);
  815. */
  816. return true;
  817. }
  818. #endif
  819. void CarlaEngine::touchPluginParameter(const uint, const uint32_t, const bool) noexcept
  820. {
  821. }
  822. CarlaPluginPtr CarlaEngine::getPlugin(const uint id) const noexcept
  823. {
  824. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  825. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->plugins != nullptr, "Invalid engine internal data");
  826. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->curPluginCount != 0, "Invalid engine internal data");
  827. #endif
  828. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  829. CARLA_SAFE_ASSERT_RETURN_ERRN(id < pData->curPluginCount, "Invalid plugin Id");
  830. return pData->plugins[id].plugin;
  831. }
  832. CarlaPluginPtr CarlaEngine::getPluginUnchecked(const uint id) const noexcept
  833. {
  834. return pData->plugins[id].plugin;
  835. }
  836. const char* CarlaEngine::getUniquePluginName(const char* const name) const
  837. {
  838. CARLA_SAFE_ASSERT_RETURN(pData->nextAction.opcode == kEnginePostActionNull, nullptr);
  839. CARLA_SAFE_ASSERT_RETURN(name != nullptr && name[0] != '\0', nullptr);
  840. carla_debug("CarlaEngine::getUniquePluginName(\"%s\")", name);
  841. CarlaString sname;
  842. sname = name;
  843. if (sname.isEmpty())
  844. {
  845. sname = "(No name)";
  846. return sname.dup();
  847. }
  848. const std::size_t maxNameSize(carla_minConstrained<uint>(getMaxClientNameSize(), 0xff, 6U) - 6); // 6 = strlen(" (10)") + 1
  849. if (maxNameSize == 0 || ! isRunning())
  850. return sname.dup();
  851. sname.truncate(maxNameSize);
  852. sname.replace(':', '.'); // ':' is used in JACK1 to split client/port names
  853. sname.replace('/', '.'); // '/' is used by us for client name prefix
  854. for (uint i=0; i < pData->curPluginCount; ++i)
  855. {
  856. const CarlaPluginPtr plugin = pData->plugins[i].plugin;
  857. CARLA_SAFE_ASSERT_BREAK(plugin.use_count() > 0);
  858. // Check if unique name doesn't exist
  859. if (const char* const pluginName = plugin->getName())
  860. {
  861. if (sname != pluginName)
  862. continue;
  863. }
  864. // Check if string has already been modified
  865. {
  866. const std::size_t len(sname.length());
  867. // 1 digit, ex: " (2)"
  868. if (sname[len-4] == ' ' && sname[len-3] == '(' && sname.isDigit(len-2) && sname[len-1] == ')')
  869. {
  870. const int number = sname[len-2] - '0';
  871. if (number == 9)
  872. {
  873. // next number is 10, 2 digits
  874. sname.truncate(len-4);
  875. sname += " (10)";
  876. //sname.replace(" (9)", " (10)");
  877. }
  878. else
  879. sname[len-2] = char('0' + number + 1);
  880. continue;
  881. }
  882. // 2 digits, ex: " (11)"
  883. if (sname[len-5] == ' ' && sname[len-4] == '(' && sname.isDigit(len-3) && sname.isDigit(len-2) && sname[len-1] == ')')
  884. {
  885. char n2 = sname[len-2];
  886. char n3 = sname[len-3];
  887. if (n2 == '9')
  888. {
  889. n2 = '0';
  890. n3 = static_cast<char>(n3 + 1);
  891. }
  892. else
  893. n2 = static_cast<char>(n2 + 1);
  894. sname[len-2] = n2;
  895. sname[len-3] = n3;
  896. continue;
  897. }
  898. }
  899. // Modify string if not
  900. sname += " (2)";
  901. }
  902. return sname.dup();
  903. }
  904. // -----------------------------------------------------------------------
  905. // Project management
  906. bool CarlaEngine::loadFile(const char* const filename)
  907. {
  908. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  909. CARLA_SAFE_ASSERT_RETURN_ERR(filename != nullptr && filename[0] != '\0', "Invalid filename");
  910. carla_debug("CarlaEngine::loadFile(\"%s\")", filename);
  911. const String jfilename = String(CharPointer_UTF8(filename));
  912. File file(jfilename);
  913. CARLA_SAFE_ASSERT_RETURN_ERR(file.exists(), "Requested file does not exist or is not a readable");
  914. CarlaString baseName(file.getFileNameWithoutExtension().toRawUTF8());
  915. CarlaString extension(file.getFileExtension().replace(".","").toLowerCase().toRawUTF8());
  916. const uint curPluginId(pData->nextPluginId < pData->curPluginCount ? pData->nextPluginId : pData->curPluginCount);
  917. // -------------------------------------------------------------------
  918. // NOTE: please keep in sync with carla_get_supported_file_extensions!!
  919. if (extension == "carxp" || extension == "carxs")
  920. return loadProject(filename, false);
  921. // -------------------------------------------------------------------
  922. if (extension == "dls")
  923. return addPlugin(PLUGIN_DLS, filename, baseName, baseName, 0, nullptr);
  924. if (extension == "gig")
  925. return addPlugin(PLUGIN_GIG, filename, baseName, baseName, 0, nullptr);
  926. if (extension == "sf2" || extension == "sf3")
  927. return addPlugin(PLUGIN_SF2, filename, baseName, baseName, 0, nullptr);
  928. if (extension == "sfz")
  929. return addPlugin(PLUGIN_SFZ, filename, baseName, baseName, 0, nullptr);
  930. // -------------------------------------------------------------------
  931. if (
  932. #ifdef HAVE_SNDFILE
  933. extension == "aif" ||
  934. extension == "aifc" ||
  935. extension == "aiff" ||
  936. extension == "au" ||
  937. extension == "bwf" ||
  938. extension == "flac" ||
  939. extension == "htk" ||
  940. extension == "iff" ||
  941. extension == "mat4" ||
  942. extension == "mat5" ||
  943. extension == "oga" ||
  944. extension == "ogg" ||
  945. extension == "paf" ||
  946. extension == "pvf" ||
  947. extension == "pvf5" ||
  948. extension == "sd2" ||
  949. extension == "sf" ||
  950. extension == "snd" ||
  951. extension == "svx" ||
  952. extension == "vcc" ||
  953. extension == "w64" ||
  954. extension == "wav" ||
  955. extension == "xi" ||
  956. #endif
  957. #ifdef HAVE_FFMPEG
  958. extension == "3g2" ||
  959. extension == "3gp" ||
  960. extension == "aac" ||
  961. extension == "ac3" ||
  962. extension == "amr" ||
  963. extension == "ape" ||
  964. extension == "mp2" ||
  965. extension == "mp3" ||
  966. extension == "mpc" ||
  967. extension == "wma" ||
  968. # ifndef HAVE_SNDFILE
  969. // FFmpeg without sndfile
  970. extension == "flac" ||
  971. extension == "oga" ||
  972. extension == "ogg" ||
  973. extension == "w64" ||
  974. extension == "wav" ||
  975. # endif
  976. #endif
  977. false
  978. )
  979. {
  980. if (addPlugin(PLUGIN_INTERNAL, nullptr, baseName, "audiofile", 0, nullptr))
  981. {
  982. if (const CarlaPluginPtr plugin = getPlugin(curPluginId))
  983. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "file", filename, true);
  984. return true;
  985. }
  986. return false;
  987. }
  988. // -------------------------------------------------------------------
  989. if (extension == "mid" || extension == "midi")
  990. {
  991. if (addPlugin(PLUGIN_INTERNAL, nullptr, baseName, "midifile", 0, nullptr))
  992. {
  993. if (const CarlaPluginPtr plugin = getPlugin(curPluginId))
  994. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "file", filename, true);
  995. return true;
  996. }
  997. return false;
  998. }
  999. // -------------------------------------------------------------------
  1000. // ZynAddSubFX
  1001. if (extension == "xmz" || extension == "xiz")
  1002. {
  1003. #ifdef HAVE_ZYN_DEPS
  1004. CarlaString nicerName("Zyn - ");
  1005. const std::size_t sep(baseName.find('-')+1);
  1006. if (sep < baseName.length())
  1007. nicerName += baseName.buffer()+sep;
  1008. else
  1009. nicerName += baseName;
  1010. if (addPlugin(PLUGIN_INTERNAL, nullptr, nicerName, "zynaddsubfx", 0, nullptr))
  1011. {
  1012. callback(true, true, ENGINE_CALLBACK_UI_STATE_CHANGED, curPluginId, 0, 0, 0, 0.0f, nullptr);
  1013. if (const CarlaPluginPtr plugin = getPlugin(curPluginId))
  1014. {
  1015. const char* const ext = (extension == "xmz") ? "CarlaAlternateFile1" : "CarlaAlternateFile2";
  1016. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, ext, filename, true);
  1017. }
  1018. return true;
  1019. }
  1020. return false;
  1021. #else
  1022. setLastError("This Carla build does not have ZynAddSubFX support");
  1023. return false;
  1024. #endif
  1025. }
  1026. // -------------------------------------------------------------------
  1027. // Direct plugin binaries
  1028. #ifdef CARLA_OS_MAC
  1029. if (extension == "vst")
  1030. return addPlugin(PLUGIN_VST2, filename, nullptr, nullptr, 0, nullptr);
  1031. #else
  1032. if (extension == "dll" || extension == "so")
  1033. return addPlugin(getBinaryTypeFromFile(filename), PLUGIN_VST2, filename, nullptr, nullptr, 0, nullptr);
  1034. #endif
  1035. #ifdef USING_JUCE
  1036. if (extension == "vst3")
  1037. return addPlugin(getBinaryTypeFromFile(filename), PLUGIN_VST3, filename, nullptr, nullptr, 0, nullptr);
  1038. #endif
  1039. // -------------------------------------------------------------------
  1040. setLastError("Unknown file extension");
  1041. return false;
  1042. }
  1043. bool CarlaEngine::loadProject(const char* const filename, const bool setAsCurrentProject)
  1044. {
  1045. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  1046. CARLA_SAFE_ASSERT_RETURN_ERR(filename != nullptr && filename[0] != '\0', "Invalid filename");
  1047. carla_debug("CarlaEngine::loadProject(\"%s\")", filename);
  1048. const String jfilename = String(CharPointer_UTF8(filename));
  1049. const File file(jfilename);
  1050. CARLA_SAFE_ASSERT_RETURN_ERR(file.existsAsFile(), "Requested file does not exist or is not a readable file");
  1051. if (setAsCurrentProject)
  1052. {
  1053. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1054. if (pData->currentProjectFilename != filename)
  1055. {
  1056. pData->currentProjectFilename = filename;
  1057. bool found;
  1058. const size_t r = pData->currentProjectFilename.rfind(CARLA_OS_SEP, &found);
  1059. if (found)
  1060. {
  1061. pData->currentProjectFolder = filename;
  1062. pData->currentProjectFolder[r] = '\0';
  1063. }
  1064. else
  1065. {
  1066. pData->currentProjectFolder.clear();
  1067. }
  1068. }
  1069. #endif
  1070. }
  1071. XmlDocument xml(file);
  1072. return loadProjectInternal(xml, !setAsCurrentProject);
  1073. }
  1074. bool CarlaEngine::saveProject(const char* const filename, const bool setAsCurrentProject)
  1075. {
  1076. CARLA_SAFE_ASSERT_RETURN_ERR(filename != nullptr && filename[0] != '\0', "Invalid filename");
  1077. carla_debug("CarlaEngine::saveProject(\"%s\")", filename);
  1078. MemoryOutputStream out;
  1079. saveProjectInternal(out);
  1080. const String jfilename = String(CharPointer_UTF8(filename));
  1081. File file(jfilename);
  1082. if (setAsCurrentProject)
  1083. {
  1084. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1085. if (pData->currentProjectFilename != filename)
  1086. {
  1087. pData->currentProjectFilename = filename;
  1088. bool found;
  1089. const size_t r = pData->currentProjectFilename.rfind(CARLA_OS_SEP, &found);
  1090. if (found)
  1091. {
  1092. pData->currentProjectFolder = filename;
  1093. pData->currentProjectFolder[r] = '\0';
  1094. }
  1095. else
  1096. {
  1097. pData->currentProjectFolder.clear();
  1098. }
  1099. }
  1100. #endif
  1101. }
  1102. if (file.replaceWithData(out.getData(), out.getDataSize()))
  1103. return true;
  1104. setLastError("Failed to write file");
  1105. return false;
  1106. }
  1107. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1108. const char* CarlaEngine::getCurrentProjectFolder() const noexcept
  1109. {
  1110. return pData->currentProjectFolder;
  1111. }
  1112. const char* CarlaEngine::getCurrentProjectFilename() const noexcept
  1113. {
  1114. return pData->currentProjectFilename;
  1115. }
  1116. void CarlaEngine::clearCurrentProjectFilename() noexcept
  1117. {
  1118. pData->currentProjectFilename.clear();
  1119. pData->currentProjectFolder.clear();
  1120. }
  1121. #endif
  1122. // -----------------------------------------------------------------------
  1123. // Information (base)
  1124. uint32_t CarlaEngine::getBufferSize() const noexcept
  1125. {
  1126. return pData->bufferSize;
  1127. }
  1128. double CarlaEngine::getSampleRate() const noexcept
  1129. {
  1130. return pData->sampleRate;
  1131. }
  1132. const char* CarlaEngine::getName() const noexcept
  1133. {
  1134. return pData->name;
  1135. }
  1136. EngineProcessMode CarlaEngine::getProccessMode() const noexcept
  1137. {
  1138. return pData->options.processMode;
  1139. }
  1140. const EngineOptions& CarlaEngine::getOptions() const noexcept
  1141. {
  1142. return pData->options;
  1143. }
  1144. EngineTimeInfo CarlaEngine::getTimeInfo() const noexcept
  1145. {
  1146. return pData->timeInfo;
  1147. }
  1148. // -----------------------------------------------------------------------
  1149. // Information (peaks)
  1150. const float* CarlaEngine::getPeaks(const uint pluginId) const noexcept
  1151. {
  1152. static const float kFallback[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
  1153. if (pluginId == MAIN_CARLA_PLUGIN_ID)
  1154. {
  1155. // get peak from first plugin, if available
  1156. if (const uint count = pData->curPluginCount)
  1157. {
  1158. pData->peaks[0] = pData->plugins[0].peaks[0];
  1159. pData->peaks[1] = pData->plugins[0].peaks[1];
  1160. pData->peaks[2] = pData->plugins[count-1].peaks[2];
  1161. pData->peaks[3] = pData->plugins[count-1].peaks[3];
  1162. }
  1163. else
  1164. {
  1165. carla_zeroFloats(pData->peaks, 4);
  1166. }
  1167. return pData->peaks;
  1168. }
  1169. CARLA_SAFE_ASSERT_RETURN(pluginId < pData->curPluginCount, kFallback);
  1170. return pData->plugins[pluginId].peaks;
  1171. }
  1172. float CarlaEngine::getInputPeak(const uint pluginId, const bool isLeft) const noexcept
  1173. {
  1174. if (pluginId == MAIN_CARLA_PLUGIN_ID)
  1175. {
  1176. // get peak from first plugin, if available
  1177. if (pData->curPluginCount > 0)
  1178. return pData->plugins[0].peaks[isLeft ? 0 : 1];
  1179. return 0.0f;
  1180. }
  1181. CARLA_SAFE_ASSERT_RETURN(pluginId < pData->curPluginCount, 0.0f);
  1182. return pData->plugins[pluginId].peaks[isLeft ? 0 : 1];
  1183. }
  1184. float CarlaEngine::getOutputPeak(const uint pluginId, const bool isLeft) const noexcept
  1185. {
  1186. if (pluginId == MAIN_CARLA_PLUGIN_ID)
  1187. {
  1188. // get peak from last plugin, if available
  1189. if (pData->curPluginCount > 0)
  1190. return pData->plugins[pData->curPluginCount-1].peaks[isLeft ? 2 : 3];
  1191. return 0.0f;
  1192. }
  1193. CARLA_SAFE_ASSERT_RETURN(pluginId < pData->curPluginCount, 0.0f);
  1194. return pData->plugins[pluginId].peaks[isLeft ? 2 : 3];
  1195. }
  1196. // -----------------------------------------------------------------------
  1197. // Callback
  1198. void CarlaEngine::callback(const bool sendHost, const bool sendOSC,
  1199. const EngineCallbackOpcode action, const uint pluginId,
  1200. const int value1, const int value2, const int value3,
  1201. const float valuef, const char* const valueStr) noexcept
  1202. {
  1203. #ifdef DEBUG
  1204. if (pData->isIdling)
  1205. carla_stdout("CarlaEngine::callback [while idling] (%s, %s, %i:%s, %i, %i, %i, %i, %f, \"%s\")",
  1206. bool2str(sendHost), bool2str(sendOSC),
  1207. action, EngineCallbackOpcode2Str(action), pluginId, value1, value2, value3,
  1208. static_cast<double>(valuef), valueStr);
  1209. else if (action != ENGINE_CALLBACK_IDLE && action != ENGINE_CALLBACK_NOTE_ON && action != ENGINE_CALLBACK_NOTE_OFF)
  1210. carla_debug("CarlaEngine::callback(%s, %s, %i:%s, %i, %i, %i, %i, %f, \"%s\")",
  1211. bool2str(sendHost), bool2str(sendOSC),
  1212. action, EngineCallbackOpcode2Str(action), pluginId, value1, value2, value3,
  1213. static_cast<double>(valuef), valueStr);
  1214. #endif
  1215. if (sendHost && pData->callback != nullptr)
  1216. {
  1217. if (action == ENGINE_CALLBACK_IDLE)
  1218. ++pData->isIdling;
  1219. try {
  1220. pData->callback(pData->callbackPtr, action, pluginId, value1, value2, value3, valuef, valueStr);
  1221. } CARLA_SAFE_EXCEPTION("callback")
  1222. if (action == ENGINE_CALLBACK_IDLE)
  1223. --pData->isIdling;
  1224. }
  1225. if (sendOSC)
  1226. {
  1227. #if defined(HAVE_LIBLO) && ! defined(BUILD_BRIDGE)
  1228. if (pData->osc.isControlRegisteredForTCP())
  1229. {
  1230. switch (action)
  1231. {
  1232. case ENGINE_CALLBACK_RELOAD_INFO:
  1233. {
  1234. CarlaPluginPtr plugin = pData->plugins[pluginId].plugin;
  1235. CARLA_SAFE_ASSERT_BREAK(plugin != nullptr);
  1236. pData->osc.sendPluginInfo(plugin);
  1237. break;
  1238. }
  1239. case ENGINE_CALLBACK_RELOAD_PARAMETERS:
  1240. {
  1241. CarlaPluginPtr plugin = pData->plugins[pluginId].plugin;
  1242. CARLA_SAFE_ASSERT_BREAK(plugin != nullptr);
  1243. pData->osc.sendPluginPortCount(plugin);
  1244. if (const uint32_t count = plugin->getParameterCount())
  1245. {
  1246. for (uint32_t i=0; i<count; ++i)
  1247. pData->osc.sendPluginParameterInfo(plugin, i);
  1248. }
  1249. break;
  1250. }
  1251. case ENGINE_CALLBACK_RELOAD_PROGRAMS:
  1252. {
  1253. CarlaPluginPtr plugin = pData->plugins[pluginId].plugin;
  1254. CARLA_SAFE_ASSERT_BREAK(plugin != nullptr);
  1255. pData->osc.sendPluginProgramCount(plugin);
  1256. if (const uint32_t count = plugin->getProgramCount())
  1257. {
  1258. for (uint32_t i=0; i<count; ++i)
  1259. pData->osc.sendPluginProgram(plugin, i);
  1260. }
  1261. if (const uint32_t count = plugin->getMidiProgramCount())
  1262. {
  1263. for (uint32_t i=0; i<count; ++i)
  1264. pData->osc.sendPluginMidiProgram(plugin, i);
  1265. }
  1266. break;
  1267. }
  1268. case ENGINE_CALLBACK_PLUGIN_ADDED:
  1269. case ENGINE_CALLBACK_RELOAD_ALL:
  1270. {
  1271. CarlaPluginPtr plugin = pData->plugins[pluginId].plugin;
  1272. CARLA_SAFE_ASSERT_BREAK(plugin != nullptr);
  1273. pData->osc.sendPluginInfo(plugin);
  1274. pData->osc.sendPluginPortCount(plugin);
  1275. pData->osc.sendPluginDataCount(plugin);
  1276. if (const uint32_t count = plugin->getParameterCount())
  1277. {
  1278. for (uint32_t i=0; i<count; ++i)
  1279. pData->osc.sendPluginParameterInfo(plugin, i);
  1280. }
  1281. if (const uint32_t count = plugin->getProgramCount())
  1282. {
  1283. for (uint32_t i=0; i<count; ++i)
  1284. pData->osc.sendPluginProgram(plugin, i);
  1285. }
  1286. if (const uint32_t count = plugin->getMidiProgramCount())
  1287. {
  1288. for (uint32_t i=0; i<count; ++i)
  1289. pData->osc.sendPluginMidiProgram(plugin, i);
  1290. }
  1291. if (const uint32_t count = plugin->getCustomDataCount())
  1292. {
  1293. for (uint32_t i=0; i<count; ++i)
  1294. pData->osc.sendPluginCustomData(plugin, i);
  1295. }
  1296. pData->osc.sendPluginInternalParameterValues(plugin);
  1297. break;
  1298. }
  1299. case ENGINE_CALLBACK_IDLE:
  1300. return;
  1301. default:
  1302. break;
  1303. }
  1304. pData->osc.sendCallback(action, pluginId, value1, value2, value3, valuef, valueStr);
  1305. }
  1306. #endif
  1307. }
  1308. }
  1309. void CarlaEngine::setCallback(const EngineCallbackFunc func, void* const ptr) noexcept
  1310. {
  1311. carla_debug("CarlaEngine::setCallback(%p, %p)", func, ptr);
  1312. pData->callback = func;
  1313. pData->callbackPtr = ptr;
  1314. }
  1315. // -----------------------------------------------------------------------
  1316. // File Callback
  1317. const char* CarlaEngine::runFileCallback(const FileCallbackOpcode action, const bool isDir, const char* const title, const char* const filter) noexcept
  1318. {
  1319. CARLA_SAFE_ASSERT_RETURN(title != nullptr && title[0] != '\0', nullptr);
  1320. CARLA_SAFE_ASSERT_RETURN(filter != nullptr, nullptr);
  1321. carla_debug("CarlaEngine::runFileCallback(%i:%s, %s, \"%s\", \"%s\")", action, FileCallbackOpcode2Str(action), bool2str(isDir), title, filter);
  1322. const char* ret = nullptr;
  1323. if (pData->fileCallback != nullptr)
  1324. {
  1325. try {
  1326. ret = pData->fileCallback(pData->fileCallbackPtr, action, isDir, title, filter);
  1327. } CARLA_SAFE_EXCEPTION("runFileCallback");
  1328. }
  1329. return ret;
  1330. }
  1331. void CarlaEngine::setFileCallback(const FileCallbackFunc func, void* const ptr) noexcept
  1332. {
  1333. carla_debug("CarlaEngine::setFileCallback(%p, %p)", func, ptr);
  1334. pData->fileCallback = func;
  1335. pData->fileCallbackPtr = ptr;
  1336. }
  1337. // -----------------------------------------------------------------------
  1338. // Transport
  1339. void CarlaEngine::transportPlay() noexcept
  1340. {
  1341. pData->timeInfo.playing = true;
  1342. pData->time.setNeedsReset();
  1343. }
  1344. void CarlaEngine::transportPause() noexcept
  1345. {
  1346. if (pData->timeInfo.playing)
  1347. pData->time.pause();
  1348. else
  1349. pData->time.setNeedsReset();
  1350. }
  1351. void CarlaEngine::transportBPM(const double bpm) noexcept
  1352. {
  1353. CARLA_SAFE_ASSERT_RETURN(bpm >= 20.0,)
  1354. try {
  1355. pData->time.setBPM(bpm);
  1356. } CARLA_SAFE_EXCEPTION("CarlaEngine::transportBPM");
  1357. }
  1358. void CarlaEngine::transportRelocate(const uint64_t frame) noexcept
  1359. {
  1360. pData->time.relocate(frame);
  1361. }
  1362. // -----------------------------------------------------------------------
  1363. // Error handling
  1364. const char* CarlaEngine::getLastError() const noexcept
  1365. {
  1366. return pData->lastError;
  1367. }
  1368. void CarlaEngine::setLastError(const char* const error) const noexcept
  1369. {
  1370. pData->lastError = error;
  1371. }
  1372. // -----------------------------------------------------------------------
  1373. // Misc
  1374. bool CarlaEngine::isAboutToClose() const noexcept
  1375. {
  1376. return pData->aboutToClose;
  1377. }
  1378. bool CarlaEngine::setAboutToClose() noexcept
  1379. {
  1380. carla_debug("CarlaEngine::setAboutToClose()");
  1381. pData->aboutToClose = true;
  1382. return (pData->isIdling == 0);
  1383. }
  1384. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1385. bool CarlaEngine::isLoadingProject() const noexcept
  1386. {
  1387. return pData->loadingProject;
  1388. }
  1389. #endif
  1390. void CarlaEngine::setActionCanceled(const bool canceled) noexcept
  1391. {
  1392. pData->actionCanceled = canceled;
  1393. }
  1394. bool CarlaEngine::wasActionCanceled() const noexcept
  1395. {
  1396. return pData->actionCanceled;
  1397. }
  1398. // -----------------------------------------------------------------------
  1399. // Global options
  1400. void CarlaEngine::setOption(const EngineOption option, const int value, const char* const valueStr) noexcept
  1401. {
  1402. carla_debug("CarlaEngine::setOption(%i:%s, %i, \"%s\")", option, EngineOption2Str(option), value, valueStr);
  1403. if (isRunning())
  1404. {
  1405. switch (option)
  1406. {
  1407. case ENGINE_OPTION_PROCESS_MODE:
  1408. case ENGINE_OPTION_AUDIO_TRIPLE_BUFFER:
  1409. case ENGINE_OPTION_AUDIO_DRIVER:
  1410. case ENGINE_OPTION_AUDIO_DEVICE:
  1411. return carla_stderr("CarlaEngine::setOption(%i:%s, %i, \"%s\") - Cannot set this option while engine is running!",
  1412. option, EngineOption2Str(option), value, valueStr);
  1413. default:
  1414. break;
  1415. }
  1416. }
  1417. // do not un-force stereo for rack mode
  1418. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK && option == ENGINE_OPTION_FORCE_STEREO && value != 0)
  1419. return;
  1420. switch (option)
  1421. {
  1422. case ENGINE_OPTION_DEBUG:
  1423. break;
  1424. case ENGINE_OPTION_PROCESS_MODE:
  1425. CARLA_SAFE_ASSERT_RETURN(value >= ENGINE_PROCESS_MODE_SINGLE_CLIENT && value <= ENGINE_PROCESS_MODE_BRIDGE,);
  1426. pData->options.processMode = static_cast<EngineProcessMode>(value);
  1427. break;
  1428. case ENGINE_OPTION_TRANSPORT_MODE:
  1429. CARLA_SAFE_ASSERT_RETURN(value >= ENGINE_TRANSPORT_MODE_DISABLED && value <= ENGINE_TRANSPORT_MODE_BRIDGE,);
  1430. CARLA_SAFE_ASSERT_RETURN(getType() == kEngineTypeJack || value != ENGINE_TRANSPORT_MODE_JACK,);
  1431. pData->options.transportMode = static_cast<EngineTransportMode>(value);
  1432. delete[] pData->options.transportExtra;
  1433. if (value >= ENGINE_TRANSPORT_MODE_DISABLED && valueStr != nullptr)
  1434. pData->options.transportExtra = carla_strdup_safe(valueStr);
  1435. else
  1436. pData->options.transportExtra = nullptr;
  1437. pData->time.setNeedsReset();
  1438. #if defined(HAVE_HYLIA) && !defined(BUILD_BRIDGE)
  1439. // enable link now if needed
  1440. {
  1441. const bool linkEnabled = pData->options.transportExtra != nullptr && std::strstr(pData->options.transportExtra, ":link:") != nullptr;
  1442. pData->time.enableLink(linkEnabled);
  1443. }
  1444. #endif
  1445. break;
  1446. case ENGINE_OPTION_FORCE_STEREO:
  1447. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1448. pData->options.forceStereo = (value != 0);
  1449. break;
  1450. case ENGINE_OPTION_PREFER_PLUGIN_BRIDGES:
  1451. #ifdef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1452. CARLA_SAFE_ASSERT_RETURN(value == 0,);
  1453. #else
  1454. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1455. #endif
  1456. pData->options.preferPluginBridges = (value != 0);
  1457. break;
  1458. case ENGINE_OPTION_PREFER_UI_BRIDGES:
  1459. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1460. pData->options.preferUiBridges = (value != 0);
  1461. break;
  1462. case ENGINE_OPTION_UIS_ALWAYS_ON_TOP:
  1463. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1464. pData->options.uisAlwaysOnTop = (value != 0);
  1465. break;
  1466. case ENGINE_OPTION_MAX_PARAMETERS:
  1467. CARLA_SAFE_ASSERT_RETURN(value >= 0,);
  1468. pData->options.maxParameters = static_cast<uint>(value);
  1469. break;
  1470. case ENGINE_OPTION_RESET_XRUNS:
  1471. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1472. pData->options.resetXruns = (value != 0);
  1473. break;
  1474. case ENGINE_OPTION_UI_BRIDGES_TIMEOUT:
  1475. CARLA_SAFE_ASSERT_RETURN(value >= 0,);
  1476. pData->options.uiBridgesTimeout = static_cast<uint>(value);
  1477. break;
  1478. case ENGINE_OPTION_AUDIO_BUFFER_SIZE:
  1479. CARLA_SAFE_ASSERT_RETURN(value >= 8,);
  1480. pData->options.audioBufferSize = static_cast<uint>(value);
  1481. break;
  1482. case ENGINE_OPTION_AUDIO_SAMPLE_RATE:
  1483. CARLA_SAFE_ASSERT_RETURN(value >= 22050,);
  1484. pData->options.audioSampleRate = static_cast<uint>(value);
  1485. break;
  1486. case ENGINE_OPTION_AUDIO_TRIPLE_BUFFER:
  1487. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1488. pData->options.audioTripleBuffer = (value != 0);
  1489. break;
  1490. case ENGINE_OPTION_AUDIO_DRIVER:
  1491. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr,);
  1492. if (pData->options.audioDriver != nullptr)
  1493. delete[] pData->options.audioDriver;
  1494. pData->options.audioDriver = carla_strdup_safe(valueStr);
  1495. break;
  1496. case ENGINE_OPTION_AUDIO_DEVICE:
  1497. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr,);
  1498. if (pData->options.audioDevice != nullptr)
  1499. delete[] pData->options.audioDevice;
  1500. pData->options.audioDevice = carla_strdup_safe(valueStr);
  1501. break;
  1502. case ENGINE_OPTION_OSC_ENABLED:
  1503. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1504. #ifndef BUILD_BRIDGE
  1505. pData->options.oscEnabled = (value != 0);
  1506. #endif
  1507. break;
  1508. case ENGINE_OPTION_OSC_PORT_TCP:
  1509. CARLA_SAFE_ASSERT_RETURN(value <= 0 || value >= 1024,);
  1510. #ifndef BUILD_BRIDGE
  1511. pData->options.oscPortTCP = value;
  1512. #endif
  1513. break;
  1514. case ENGINE_OPTION_OSC_PORT_UDP:
  1515. CARLA_SAFE_ASSERT_RETURN(value <= 0 || value >= 1024,);
  1516. #ifndef BUILD_BRIDGE
  1517. pData->options.oscPortUDP = value;
  1518. #endif
  1519. break;
  1520. case ENGINE_OPTION_FILE_PATH:
  1521. CARLA_SAFE_ASSERT_RETURN(value > FILE_NONE,);
  1522. CARLA_SAFE_ASSERT_RETURN(value <= FILE_MIDI,);
  1523. switch (value)
  1524. {
  1525. case FILE_AUDIO:
  1526. if (pData->options.pathAudio != nullptr)
  1527. delete[] pData->options.pathAudio;
  1528. if (valueStr != nullptr)
  1529. pData->options.pathAudio = carla_strdup_safe(valueStr);
  1530. else
  1531. pData->options.pathAudio = nullptr;
  1532. break;
  1533. case FILE_MIDI:
  1534. if (pData->options.pathMIDI != nullptr)
  1535. delete[] pData->options.pathMIDI;
  1536. if (valueStr != nullptr)
  1537. pData->options.pathMIDI = carla_strdup_safe(valueStr);
  1538. else
  1539. pData->options.pathMIDI = nullptr;
  1540. break;
  1541. default:
  1542. return carla_stderr("CarlaEngine::setOption(%i:%s, %i, \"%s\") - Invalid file type",
  1543. option, EngineOption2Str(option), value, valueStr);
  1544. break;
  1545. }
  1546. break;
  1547. case ENGINE_OPTION_PLUGIN_PATH:
  1548. CARLA_SAFE_ASSERT_RETURN(value > PLUGIN_NONE,);
  1549. CARLA_SAFE_ASSERT_RETURN(value <= PLUGIN_SFZ,);
  1550. switch (value)
  1551. {
  1552. case PLUGIN_LADSPA:
  1553. if (pData->options.pathLADSPA != nullptr)
  1554. delete[] pData->options.pathLADSPA;
  1555. if (valueStr != nullptr)
  1556. pData->options.pathLADSPA = carla_strdup_safe(valueStr);
  1557. else
  1558. pData->options.pathLADSPA = nullptr;
  1559. break;
  1560. case PLUGIN_DSSI:
  1561. if (pData->options.pathDSSI != nullptr)
  1562. delete[] pData->options.pathDSSI;
  1563. if (valueStr != nullptr)
  1564. pData->options.pathDSSI = carla_strdup_safe(valueStr);
  1565. else
  1566. pData->options.pathDSSI = nullptr;
  1567. break;
  1568. case PLUGIN_LV2:
  1569. if (pData->options.pathLV2 != nullptr)
  1570. delete[] pData->options.pathLV2;
  1571. if (valueStr != nullptr)
  1572. pData->options.pathLV2 = carla_strdup_safe(valueStr);
  1573. else
  1574. pData->options.pathLV2 = nullptr;
  1575. break;
  1576. case PLUGIN_VST2:
  1577. if (pData->options.pathVST2 != nullptr)
  1578. delete[] pData->options.pathVST2;
  1579. if (valueStr != nullptr)
  1580. pData->options.pathVST2 = carla_strdup_safe(valueStr);
  1581. else
  1582. pData->options.pathVST2 = nullptr;
  1583. break;
  1584. case PLUGIN_VST3:
  1585. if (pData->options.pathVST3 != nullptr)
  1586. delete[] pData->options.pathVST3;
  1587. if (valueStr != nullptr)
  1588. pData->options.pathVST3 = carla_strdup_safe(valueStr);
  1589. else
  1590. pData->options.pathVST3 = nullptr;
  1591. break;
  1592. case PLUGIN_SF2:
  1593. if (pData->options.pathSF2 != nullptr)
  1594. delete[] pData->options.pathSF2;
  1595. if (valueStr != nullptr)
  1596. pData->options.pathSF2 = carla_strdup_safe(valueStr);
  1597. else
  1598. pData->options.pathSF2 = nullptr;
  1599. break;
  1600. case PLUGIN_SFZ:
  1601. if (pData->options.pathSFZ != nullptr)
  1602. delete[] pData->options.pathSFZ;
  1603. if (valueStr != nullptr)
  1604. pData->options.pathSFZ = carla_strdup_safe(valueStr);
  1605. else
  1606. pData->options.pathSFZ = nullptr;
  1607. break;
  1608. default:
  1609. return carla_stderr("CarlaEngine::setOption(%i:%s, %i, \"%s\") - Invalid plugin type",
  1610. option, EngineOption2Str(option), value, valueStr);
  1611. break;
  1612. }
  1613. break;
  1614. case ENGINE_OPTION_PATH_BINARIES:
  1615. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1616. if (pData->options.binaryDir != nullptr)
  1617. delete[] pData->options.binaryDir;
  1618. pData->options.binaryDir = carla_strdup_safe(valueStr);
  1619. break;
  1620. case ENGINE_OPTION_PATH_RESOURCES:
  1621. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1622. if (pData->options.resourceDir != nullptr)
  1623. delete[] pData->options.resourceDir;
  1624. pData->options.resourceDir = carla_strdup_safe(valueStr);
  1625. break;
  1626. case ENGINE_OPTION_PREVENT_BAD_BEHAVIOUR: {
  1627. CARLA_SAFE_ASSERT_RETURN(pData->options.binaryDir != nullptr && pData->options.binaryDir[0] != '\0',);
  1628. #ifdef CARLA_OS_LINUX
  1629. const ScopedEngineEnvironmentLocker _seel(this);
  1630. if (value != 0)
  1631. {
  1632. CarlaString interposerPath(CarlaString(pData->options.binaryDir) + "/libcarla_interposer-safe.so");
  1633. ::setenv("LD_PRELOAD", interposerPath.buffer(), 1);
  1634. }
  1635. else
  1636. {
  1637. ::unsetenv("LD_PRELOAD");
  1638. }
  1639. #endif
  1640. } break;
  1641. case ENGINE_OPTION_FRONTEND_BACKGROUND_COLOR:
  1642. pData->options.bgColor = static_cast<uint>(value);
  1643. break;
  1644. case ENGINE_OPTION_FRONTEND_FOREGROUND_COLOR:
  1645. pData->options.fgColor = static_cast<uint>(value);
  1646. break;
  1647. case ENGINE_OPTION_FRONTEND_UI_SCALE:
  1648. CARLA_SAFE_ASSERT_RETURN(value > 0,);
  1649. pData->options.uiScale = static_cast<float>(value) / 1000;
  1650. break;
  1651. case ENGINE_OPTION_FRONTEND_WIN_ID: {
  1652. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1653. const long long winId(std::strtoll(valueStr, nullptr, 16));
  1654. CARLA_SAFE_ASSERT_RETURN(winId >= 0,);
  1655. pData->options.frontendWinId = static_cast<uintptr_t>(winId);
  1656. } break;
  1657. #if !defined(BUILD_BRIDGE_ALTERNATIVE_ARCH) && !defined(CARLA_OS_WIN)
  1658. case ENGINE_OPTION_WINE_EXECUTABLE:
  1659. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1660. if (pData->options.wine.executable != nullptr)
  1661. delete[] pData->options.wine.executable;
  1662. pData->options.wine.executable = carla_strdup_safe(valueStr);
  1663. break;
  1664. case ENGINE_OPTION_WINE_AUTO_PREFIX:
  1665. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1666. pData->options.wine.autoPrefix = (value != 0);
  1667. break;
  1668. case ENGINE_OPTION_WINE_FALLBACK_PREFIX:
  1669. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1670. if (pData->options.wine.fallbackPrefix != nullptr)
  1671. delete[] pData->options.wine.fallbackPrefix;
  1672. pData->options.wine.fallbackPrefix = carla_strdup_safe(valueStr);
  1673. break;
  1674. case ENGINE_OPTION_WINE_RT_PRIO_ENABLED:
  1675. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1676. pData->options.wine.rtPrio = (value != 0);
  1677. break;
  1678. case ENGINE_OPTION_WINE_BASE_RT_PRIO:
  1679. CARLA_SAFE_ASSERT_RETURN(value >= 1 && value <= 89,);
  1680. pData->options.wine.baseRtPrio = value;
  1681. break;
  1682. case ENGINE_OPTION_WINE_SERVER_RT_PRIO:
  1683. CARLA_SAFE_ASSERT_RETURN(value >= 1 && value <= 99,);
  1684. pData->options.wine.serverRtPrio = value;
  1685. break;
  1686. #endif
  1687. case ENGINE_OPTION_DEBUG_CONSOLE_OUTPUT:
  1688. break;
  1689. case ENGINE_OPTION_CLIENT_NAME_PREFIX:
  1690. if (pData->options.clientNamePrefix != nullptr)
  1691. delete[] pData->options.clientNamePrefix;
  1692. pData->options.clientNamePrefix = valueStr != nullptr && valueStr[0] != '\0'
  1693. ? carla_strdup_safe(valueStr)
  1694. : nullptr;
  1695. break;
  1696. }
  1697. }
  1698. #ifndef BUILD_BRIDGE
  1699. // -----------------------------------------------------------------------
  1700. // OSC Stuff
  1701. bool CarlaEngine::isOscControlRegistered() const noexcept
  1702. {
  1703. # ifdef HAVE_LIBLO
  1704. return pData->osc.isControlRegisteredForTCP();
  1705. # else
  1706. return false;
  1707. # endif
  1708. }
  1709. const char* CarlaEngine::getOscServerPathTCP() const noexcept
  1710. {
  1711. # ifdef HAVE_LIBLO
  1712. return pData->osc.getServerPathTCP();
  1713. # else
  1714. return nullptr;
  1715. # endif
  1716. }
  1717. const char* CarlaEngine::getOscServerPathUDP() const noexcept
  1718. {
  1719. # ifdef HAVE_LIBLO
  1720. return pData->osc.getServerPathUDP();
  1721. # else
  1722. return nullptr;
  1723. # endif
  1724. }
  1725. #endif
  1726. // -----------------------------------------------------------------------
  1727. // Internal stuff
  1728. void CarlaEngine::bufferSizeChanged(const uint32_t newBufferSize)
  1729. {
  1730. carla_debug("CarlaEngine::bufferSizeChanged(%i)", newBufferSize);
  1731. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1732. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1733. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1734. {
  1735. pData->graph.setBufferSize(newBufferSize);
  1736. }
  1737. #endif
  1738. pData->time.updateAudioValues(newBufferSize, pData->sampleRate);
  1739. for (uint i=0; i < pData->curPluginCount; ++i)
  1740. {
  1741. if (const CarlaPluginPtr plugin = pData->plugins[i].plugin)
  1742. {
  1743. if (plugin->isEnabled() && plugin->tryLock(true))
  1744. {
  1745. plugin->bufferSizeChanged(newBufferSize);
  1746. plugin->unlock();
  1747. }
  1748. }
  1749. }
  1750. callback(true, true, ENGINE_CALLBACK_BUFFER_SIZE_CHANGED, 0, static_cast<int>(newBufferSize), 0, 0, 0.0f, nullptr);
  1751. }
  1752. void CarlaEngine::sampleRateChanged(const double newSampleRate)
  1753. {
  1754. carla_debug("CarlaEngine::sampleRateChanged(%g)", newSampleRate);
  1755. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1756. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1757. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1758. {
  1759. pData->graph.setSampleRate(newSampleRate);
  1760. }
  1761. #endif
  1762. pData->time.updateAudioValues(pData->bufferSize, newSampleRate);
  1763. for (uint i=0; i < pData->curPluginCount; ++i)
  1764. {
  1765. if (const CarlaPluginPtr plugin = pData->plugins[i].plugin)
  1766. {
  1767. if (plugin->isEnabled() && plugin->tryLock(true))
  1768. {
  1769. plugin->sampleRateChanged(newSampleRate);
  1770. plugin->unlock();
  1771. }
  1772. }
  1773. }
  1774. callback(true, true, ENGINE_CALLBACK_SAMPLE_RATE_CHANGED, 0, 0, 0, 0, static_cast<float>(newSampleRate), nullptr);
  1775. }
  1776. void CarlaEngine::offlineModeChanged(const bool isOfflineNow)
  1777. {
  1778. carla_debug("CarlaEngine::offlineModeChanged(%s)", bool2str(isOfflineNow));
  1779. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1780. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1781. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1782. {
  1783. pData->graph.setOffline(isOfflineNow);
  1784. }
  1785. #endif
  1786. for (uint i=0; i < pData->curPluginCount; ++i)
  1787. {
  1788. if (const CarlaPluginPtr plugin = pData->plugins[i].plugin)
  1789. if (plugin->isEnabled())
  1790. plugin->offlineModeChanged(isOfflineNow);
  1791. }
  1792. }
  1793. void CarlaEngine::setPluginPeaksRT(const uint pluginId, float const inPeaks[2], float const outPeaks[2]) noexcept
  1794. {
  1795. EnginePluginData& pluginData(pData->plugins[pluginId]);
  1796. pluginData.peaks[0] = inPeaks[0];
  1797. pluginData.peaks[1] = inPeaks[1];
  1798. pluginData.peaks[2] = outPeaks[0];
  1799. pluginData.peaks[3] = outPeaks[1];
  1800. }
  1801. void CarlaEngine::saveProjectInternal(water::MemoryOutputStream& outStream) const
  1802. {
  1803. // send initial prepareForSave first, giving time for bridges to act
  1804. for (uint i=0; i < pData->curPluginCount; ++i)
  1805. {
  1806. if (const CarlaPluginPtr plugin = pData->plugins[i].plugin)
  1807. {
  1808. if (plugin->isEnabled())
  1809. {
  1810. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1811. // deactivate bridge client-side ping check, since some plugins block during save
  1812. if (plugin->getHints() & PLUGIN_IS_BRIDGE)
  1813. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "false", false);
  1814. #endif
  1815. plugin->prepareForSave(false);
  1816. }
  1817. }
  1818. }
  1819. outStream << "<?xml version='1.0' encoding='UTF-8'?>\n";
  1820. outStream << "<!DOCTYPE CARLA-PROJECT>\n";
  1821. outStream << "<CARLA-PROJECT VERSION='2.2'";
  1822. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1823. if (pData->ignoreClientPrefix)
  1824. outStream << " IgnoreClientPrefix='true'";
  1825. #endif
  1826. outStream << ">\n";
  1827. const bool isPlugin(getType() == kEngineTypePlugin);
  1828. const EngineOptions& options(pData->options);
  1829. {
  1830. MemoryOutputStream outSettings(1024);
  1831. outSettings << " <EngineSettings>\n";
  1832. outSettings << " <ForceStereo>" << bool2str(options.forceStereo) << "</ForceStereo>\n";
  1833. outSettings << " <PreferPluginBridges>" << bool2str(options.preferPluginBridges) << "</PreferPluginBridges>\n";
  1834. outSettings << " <PreferUiBridges>" << bool2str(options.preferUiBridges) << "</PreferUiBridges>\n";
  1835. outSettings << " <UIsAlwaysOnTop>" << bool2str(options.uisAlwaysOnTop) << "</UIsAlwaysOnTop>\n";
  1836. outSettings << " <MaxParameters>" << String(options.maxParameters) << "</MaxParameters>\n";
  1837. outSettings << " <UIBridgesTimeout>" << String(options.uiBridgesTimeout) << "</UIBridgesTimeout>\n";
  1838. if (isPlugin)
  1839. {
  1840. outSettings << " <LADSPA_PATH>" << xmlSafeString(options.pathLADSPA, true) << "</LADSPA_PATH>\n";
  1841. outSettings << " <DSSI_PATH>" << xmlSafeString(options.pathDSSI, true) << "</DSSI_PATH>\n";
  1842. outSettings << " <LV2_PATH>" << xmlSafeString(options.pathLV2, true) << "</LV2_PATH>\n";
  1843. outSettings << " <VST2_PATH>" << xmlSafeString(options.pathVST2, true) << "</VST2_PATH>\n";
  1844. outSettings << " <VST3_PATH>" << xmlSafeString(options.pathVST3, true) << "</VST3_PATH>\n";
  1845. outSettings << " <SF2_PATH>" << xmlSafeString(options.pathSF2, true) << "</SF2_PATH>\n";
  1846. outSettings << " <SFZ_PATH>" << xmlSafeString(options.pathSFZ, true) << "</SFZ_PATH>\n";
  1847. }
  1848. outSettings << " </EngineSettings>\n";
  1849. outStream << outSettings;
  1850. }
  1851. if (pData->timeInfo.bbt.valid && ! isPlugin)
  1852. {
  1853. MemoryOutputStream outTransport(128);
  1854. outTransport << "\n <Transport>\n";
  1855. // outTransport << " <BeatsPerBar>" << pData->timeInfo.bbt.beatsPerBar << "</BeatsPerBar>\n";
  1856. outTransport << " <BeatsPerMinute>" << pData->timeInfo.bbt.beatsPerMinute << "</BeatsPerMinute>\n";
  1857. outTransport << " </Transport>\n";
  1858. outStream << outTransport;
  1859. }
  1860. char strBuf[STR_MAX+1];
  1861. carla_zeroChars(strBuf, STR_MAX+1);
  1862. for (uint i=0; i < pData->curPluginCount; ++i)
  1863. {
  1864. if (const CarlaPluginPtr plugin = pData->plugins[i].plugin)
  1865. {
  1866. if (plugin->isEnabled())
  1867. {
  1868. MemoryOutputStream outPlugin(4096), streamPlugin;
  1869. plugin->getStateSave(false).dumpToMemoryStream(streamPlugin);
  1870. outPlugin << "\n";
  1871. if (plugin->getRealName(strBuf))
  1872. outPlugin << " <!-- " << xmlSafeString(strBuf, true) << " -->\n";
  1873. outPlugin << " <Plugin>\n";
  1874. outPlugin << streamPlugin;
  1875. outPlugin << " </Plugin>\n";
  1876. outStream << outPlugin;
  1877. }
  1878. }
  1879. }
  1880. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1881. // tell bridges we're done saving
  1882. for (uint i=0; i < pData->curPluginCount; ++i)
  1883. {
  1884. if (const CarlaPluginPtr plugin = pData->plugins[i].plugin)
  1885. if (plugin->isEnabled() && (plugin->getHints() & PLUGIN_IS_BRIDGE) != 0)
  1886. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "true", false);
  1887. }
  1888. // save internal connections
  1889. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1890. {
  1891. uint posCount = 0;
  1892. const char* const* const patchbayConns = getPatchbayConnections(false);
  1893. const PatchbayPosition* const patchbayPos = getPatchbayPositions(false, posCount);
  1894. if (patchbayConns != nullptr || patchbayPos != nullptr)
  1895. {
  1896. MemoryOutputStream outPatchbay(2048);
  1897. outPatchbay << "\n <Patchbay>\n";
  1898. if (patchbayConns != nullptr)
  1899. {
  1900. for (int i=0; patchbayConns[i] != nullptr && patchbayConns[i+1] != nullptr; ++i, ++i)
  1901. {
  1902. const char* const connSource(patchbayConns[i]);
  1903. const char* const connTarget(patchbayConns[i+1]);
  1904. CARLA_SAFE_ASSERT_CONTINUE(connSource != nullptr && connSource[0] != '\0');
  1905. CARLA_SAFE_ASSERT_CONTINUE(connTarget != nullptr && connTarget[0] != '\0');
  1906. outPatchbay << " <Connection>\n";
  1907. outPatchbay << " <Source>" << xmlSafeString(connSource, true) << "</Source>\n";
  1908. outPatchbay << " <Target>" << xmlSafeString(connTarget, true) << "</Target>\n";
  1909. outPatchbay << " </Connection>\n";
  1910. }
  1911. }
  1912. if (patchbayPos != nullptr && posCount != 0)
  1913. {
  1914. outPatchbay << " <Positions>\n";
  1915. for (uint i=0; i<posCount; ++i)
  1916. {
  1917. const PatchbayPosition& ppos(patchbayPos[i]);
  1918. CARLA_SAFE_ASSERT_CONTINUE(ppos.name != nullptr && ppos.name[0] != '\0');
  1919. outPatchbay << " <Position x1=\"" << ppos.x1 << "\" y1=\"" << ppos.y1;
  1920. if (ppos.x2 != 0 || ppos.y2 != 0)
  1921. outPatchbay << "\" x2=\"" << ppos.x2 << "\" y2=\"" << ppos.y2;
  1922. if (ppos.pluginId >= 0)
  1923. outPatchbay << "\" pluginId=\"" << ppos.pluginId;
  1924. outPatchbay << "\">\n";
  1925. outPatchbay << " <Name>" << xmlSafeString(ppos.name, true) << "</Name>\n";
  1926. outPatchbay << " </Position>\n";
  1927. if (ppos.dealloc)
  1928. delete[] ppos.name;
  1929. }
  1930. outPatchbay << " </Positions>\n";
  1931. }
  1932. outPatchbay << " </Patchbay>\n";
  1933. outStream << outPatchbay;
  1934. delete[] patchbayPos;
  1935. }
  1936. }
  1937. // if we're running inside some session-manager (and using JACK), let them handle the connections
  1938. bool saveExternalConnections, saveExternalPositions = true;
  1939. /**/ if (isPlugin)
  1940. {
  1941. saveExternalConnections = false;
  1942. saveExternalPositions = false;
  1943. }
  1944. else if (std::strcmp(getCurrentDriverName(), "JACK") != 0)
  1945. {
  1946. saveExternalConnections = true;
  1947. }
  1948. else if (std::getenv("CARLA_DONT_MANAGE_CONNECTIONS") != nullptr)
  1949. {
  1950. saveExternalConnections = false;
  1951. }
  1952. else
  1953. {
  1954. saveExternalConnections = true;
  1955. }
  1956. if (saveExternalConnections || saveExternalPositions)
  1957. {
  1958. uint posCount = 0;
  1959. const char* const* const patchbayConns = saveExternalConnections
  1960. ? getPatchbayConnections(true)
  1961. : nullptr;
  1962. const PatchbayPosition* const patchbayPos = saveExternalPositions
  1963. ? getPatchbayPositions(true, posCount)
  1964. : nullptr;
  1965. if (patchbayConns != nullptr || patchbayPos != nullptr)
  1966. {
  1967. MemoryOutputStream outPatchbay(2048);
  1968. outPatchbay << "\n <ExternalPatchbay>\n";
  1969. if (patchbayConns != nullptr)
  1970. {
  1971. for (int i=0; patchbayConns[i] != nullptr && patchbayConns[i+1] != nullptr; ++i, ++i )
  1972. {
  1973. const char* const connSource(patchbayConns[i]);
  1974. const char* const connTarget(patchbayConns[i+1]);
  1975. CARLA_SAFE_ASSERT_CONTINUE(connSource != nullptr && connSource[0] != '\0');
  1976. CARLA_SAFE_ASSERT_CONTINUE(connTarget != nullptr && connTarget[0] != '\0');
  1977. outPatchbay << " <Connection>\n";
  1978. outPatchbay << " <Source>" << xmlSafeString(connSource, true) << "</Source>\n";
  1979. outPatchbay << " <Target>" << xmlSafeString(connTarget, true) << "</Target>\n";
  1980. outPatchbay << " </Connection>\n";
  1981. }
  1982. }
  1983. if (patchbayPos != nullptr && posCount != 0)
  1984. {
  1985. outPatchbay << " <Positions>\n";
  1986. for (uint i=0; i<posCount; ++i)
  1987. {
  1988. const PatchbayPosition& ppos(patchbayPos[i]);
  1989. CARLA_SAFE_ASSERT_CONTINUE(ppos.name != nullptr && ppos.name[0] != '\0');
  1990. outPatchbay << " <Position x1=\"" << ppos.x1 << "\" y1=\"" << ppos.y1;
  1991. if (ppos.x2 != 0 || ppos.y2 != 0)
  1992. outPatchbay << "\" x2=\"" << ppos.x2 << "\" y2=\"" << ppos.y2;
  1993. if (ppos.pluginId >= 0)
  1994. outPatchbay << "\" pluginId=\"" << ppos.pluginId;
  1995. outPatchbay << "\">\n";
  1996. outPatchbay << " <Name>" << xmlSafeString(ppos.name, true) << "</Name>\n";
  1997. outPatchbay << " </Position>\n";
  1998. if (ppos.dealloc)
  1999. delete[] ppos.name;
  2000. }
  2001. outPatchbay << " </Positions>\n";
  2002. }
  2003. outPatchbay << " </ExternalPatchbay>\n";
  2004. outStream << outPatchbay;
  2005. }
  2006. }
  2007. #endif
  2008. outStream << "</CARLA-PROJECT>\n";
  2009. }
  2010. static String findBinaryInCustomPath(const char* const searchPath, const char* const binary)
  2011. {
  2012. const StringArray searchPaths(StringArray::fromTokens(searchPath, CARLA_OS_SPLIT_STR, ""));
  2013. // try direct filename first
  2014. String jbinary(binary);
  2015. // adjust for current platform
  2016. #ifdef CARLA_OS_WIN
  2017. if (jbinary[0] == '/')
  2018. jbinary = "C:" + jbinary.replaceCharacter('/', '\\');
  2019. #else
  2020. if (jbinary[1] == ':' && (jbinary[2] == '\\' || jbinary[2] == '/'))
  2021. jbinary = jbinary.substring(2).replaceCharacter('\\', '/');
  2022. #endif
  2023. String filename = File(jbinary).getFileName();
  2024. int searchFlags = File::findFiles|File::ignoreHiddenFiles;
  2025. #ifdef CARLA_OS_MAC
  2026. if (filename.endsWithIgnoreCase(".vst") || filename.endsWithIgnoreCase(".vst3"))
  2027. searchFlags |= File::findDirectories;
  2028. #endif
  2029. Array<File> results;
  2030. for (const String *it=searchPaths.begin(), *end=searchPaths.end(); it != end; ++it)
  2031. {
  2032. const File path(*it);
  2033. results.clear();
  2034. path.findChildFiles(results, searchFlags, true, filename);
  2035. if (results.size() > 0)
  2036. return results.getFirst().getFullPathName();
  2037. }
  2038. // try changing extension
  2039. #if defined(CARLA_OS_MAC)
  2040. if (filename.endsWithIgnoreCase(".dll") || filename.endsWithIgnoreCase(".so"))
  2041. filename = File(jbinary).getFileNameWithoutExtension() + ".dylib";
  2042. #elif defined(CARLA_OS_WIN)
  2043. if (filename.endsWithIgnoreCase(".dylib") || filename.endsWithIgnoreCase(".so"))
  2044. filename = File(jbinary).getFileNameWithoutExtension() + ".dll";
  2045. #else
  2046. if (filename.endsWithIgnoreCase(".dll") || filename.endsWithIgnoreCase(".dylib"))
  2047. filename = File(jbinary).getFileNameWithoutExtension() + ".so";
  2048. #endif
  2049. else
  2050. return String();
  2051. for (const String *it=searchPaths.begin(), *end=searchPaths.end(); it != end; ++it)
  2052. {
  2053. const File path(*it);
  2054. results.clear();
  2055. path.findChildFiles(results, searchFlags, true, filename);
  2056. if (results.size() > 0)
  2057. return results.getFirst().getFullPathName();
  2058. }
  2059. return String();
  2060. }
  2061. bool CarlaEngine::loadProjectInternal(water::XmlDocument& xmlDoc, const bool alwaysLoadConnections)
  2062. {
  2063. carla_debug("CarlaEngine::loadProjectInternal(%p, %s) - START", &xmlDoc, bool2str(alwaysLoadConnections));
  2064. CarlaScopedPointer<XmlElement> xmlElement(xmlDoc.getDocumentElement(true));
  2065. CARLA_SAFE_ASSERT_RETURN_ERR(xmlElement != nullptr, "Failed to parse project file");
  2066. const String& xmlType(xmlElement->getTagName());
  2067. const bool isPreset(xmlType.equalsIgnoreCase("carla-preset"));
  2068. if (! (xmlType.equalsIgnoreCase("carla-project") || isPreset))
  2069. {
  2070. callback(true, true, ENGINE_CALLBACK_PROJECT_LOAD_FINISHED, 0, 0, 0, 0, 0.0f, nullptr);
  2071. setLastError("Not a valid Carla project or preset file");
  2072. return false;
  2073. }
  2074. pData->actionCanceled = false;
  2075. callback(true, true, ENGINE_CALLBACK_CANCELABLE_ACTION, 0, 1, 0, 0, 0.0f, "Loading project");
  2076. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2077. if (pData->options.clientNamePrefix != nullptr)
  2078. {
  2079. if (carla_isEqual(xmlElement->getDoubleAttribute("VERSION", 0.0), 2.0) ||
  2080. xmlElement->getBoolAttribute("IgnoreClientPrefix", false))
  2081. {
  2082. carla_stdout("Loading project in compatibility mode, will ignore client name prefix");
  2083. pData->ignoreClientPrefix = true;
  2084. setOption(ENGINE_OPTION_CLIENT_NAME_PREFIX, 0, "");
  2085. }
  2086. }
  2087. const CarlaScopedValueSetter<bool> csvs(pData->loadingProject, true, false);
  2088. #endif
  2089. // completely load file
  2090. xmlElement = xmlDoc.getDocumentElement(false);
  2091. CARLA_SAFE_ASSERT_RETURN_ERR(xmlElement != nullptr, "Failed to completely parse project file");
  2092. if (pData->aboutToClose)
  2093. return true;
  2094. if (pData->actionCanceled)
  2095. {
  2096. setLastError("Project load canceled");
  2097. return false;
  2098. }
  2099. callback(true, false, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  2100. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2101. const bool isMultiClient = pData->options.processMode == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS;
  2102. const bool isPatchbay = pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY;
  2103. #endif
  2104. const bool isPlugin = getType() == kEngineTypePlugin;
  2105. // load engine settings first of all
  2106. if (XmlElement* const elem = isPreset ? nullptr : xmlElement->getChildByName("EngineSettings"))
  2107. {
  2108. for (XmlElement* settElem = elem->getFirstChildElement(); settElem != nullptr; settElem = settElem->getNextElement())
  2109. {
  2110. const String& tag(settElem->getTagName());
  2111. const String text(settElem->getAllSubText().trim());
  2112. /** some settings might be incorrect or require extra work,
  2113. so we call setOption rather than modifying them direly */
  2114. int option = -1;
  2115. int value = 0;
  2116. const char* valueStr = nullptr;
  2117. /**/ if (tag == "ForceStereo")
  2118. {
  2119. option = ENGINE_OPTION_FORCE_STEREO;
  2120. value = text == "true" ? 1 : 0;
  2121. }
  2122. else if (tag == "PreferPluginBridges")
  2123. {
  2124. option = ENGINE_OPTION_PREFER_PLUGIN_BRIDGES;
  2125. value = text == "true" ? 1 : 0;
  2126. }
  2127. else if (tag == "PreferUiBridges")
  2128. {
  2129. option = ENGINE_OPTION_PREFER_UI_BRIDGES;
  2130. value = text == "true" ? 1 : 0;
  2131. }
  2132. else if (tag == "UIsAlwaysOnTop")
  2133. {
  2134. option = ENGINE_OPTION_UIS_ALWAYS_ON_TOP;
  2135. value = text == "true" ? 1 : 0;
  2136. }
  2137. else if (tag == "MaxParameters")
  2138. {
  2139. option = ENGINE_OPTION_MAX_PARAMETERS;
  2140. value = text.getIntValue();
  2141. }
  2142. else if (tag == "UIBridgesTimeout")
  2143. {
  2144. option = ENGINE_OPTION_UI_BRIDGES_TIMEOUT;
  2145. value = text.getIntValue();
  2146. }
  2147. else if (isPlugin)
  2148. {
  2149. /**/ if (tag == "LADSPA_PATH")
  2150. {
  2151. option = ENGINE_OPTION_PLUGIN_PATH;
  2152. value = PLUGIN_LADSPA;
  2153. valueStr = text.toRawUTF8();
  2154. }
  2155. else if (tag == "DSSI_PATH")
  2156. {
  2157. option = ENGINE_OPTION_PLUGIN_PATH;
  2158. value = PLUGIN_DSSI;
  2159. valueStr = text.toRawUTF8();
  2160. }
  2161. else if (tag == "LV2_PATH")
  2162. {
  2163. option = ENGINE_OPTION_PLUGIN_PATH;
  2164. value = PLUGIN_LV2;
  2165. valueStr = text.toRawUTF8();
  2166. }
  2167. else if (tag == "VST2_PATH")
  2168. {
  2169. option = ENGINE_OPTION_PLUGIN_PATH;
  2170. value = PLUGIN_VST2;
  2171. valueStr = text.toRawUTF8();
  2172. }
  2173. else if (tag.equalsIgnoreCase("VST3_PATH"))
  2174. {
  2175. option = ENGINE_OPTION_PLUGIN_PATH;
  2176. value = PLUGIN_VST3;
  2177. valueStr = text.toRawUTF8();
  2178. }
  2179. else if (tag == "SF2_PATH")
  2180. {
  2181. option = ENGINE_OPTION_PLUGIN_PATH;
  2182. value = PLUGIN_SF2;
  2183. valueStr = text.toRawUTF8();
  2184. }
  2185. else if (tag == "SFZ_PATH")
  2186. {
  2187. option = ENGINE_OPTION_PLUGIN_PATH;
  2188. value = PLUGIN_SFZ;
  2189. valueStr = text.toRawUTF8();
  2190. }
  2191. }
  2192. if (option == -1)
  2193. {
  2194. // check old stuff, unhandled now
  2195. if (tag == "GIG_PATH")
  2196. continue;
  2197. // ignored tags
  2198. if (tag == "LADSPA_PATH" || tag == "DSSI_PATH" || tag == "LV2_PATH" || tag == "VST2_PATH")
  2199. continue;
  2200. if (tag == "VST3_PATH" || tag == "AU_PATH")
  2201. continue;
  2202. if (tag == "SF2_PATH" || tag == "SFZ_PATH")
  2203. continue;
  2204. // hmm something is wrong..
  2205. carla_stderr2("CarlaEngine::loadProjectInternal() - Unhandled option '%s'", tag.toRawUTF8());
  2206. continue;
  2207. }
  2208. setOption(static_cast<EngineOption>(option), value, valueStr);
  2209. }
  2210. if (pData->aboutToClose)
  2211. return true;
  2212. if (pData->actionCanceled)
  2213. {
  2214. setLastError("Project load canceled");
  2215. return false;
  2216. }
  2217. }
  2218. // now setup transport
  2219. if (XmlElement* const elem = (isPreset || isPlugin) ? nullptr : xmlElement->getChildByName("Transport"))
  2220. {
  2221. if (XmlElement* const bpmElem = elem->getChildByName("BeatsPerMinute"))
  2222. {
  2223. const String bpmText(bpmElem->getAllSubText().trim());
  2224. const double bpm = bpmText.getDoubleValue();
  2225. // some sane limits
  2226. if (bpm >= 20.0 && bpm < 400.0)
  2227. pData->time.setBPM(bpm);
  2228. if (pData->aboutToClose)
  2229. return true;
  2230. if (pData->actionCanceled)
  2231. {
  2232. setLastError("Project load canceled");
  2233. return false;
  2234. }
  2235. }
  2236. }
  2237. // and we handle plugins
  2238. for (XmlElement* elem = xmlElement->getFirstChildElement(); elem != nullptr; elem = elem->getNextElement())
  2239. {
  2240. const String& tagName(elem->getTagName());
  2241. if (isPreset || tagName == "Plugin")
  2242. {
  2243. CarlaStateSave stateSave;
  2244. stateSave.fillFromXmlElement(isPreset ? xmlElement.get() : elem);
  2245. if (pData->aboutToClose)
  2246. return true;
  2247. if (pData->actionCanceled)
  2248. {
  2249. setLastError("Project load canceled");
  2250. return false;
  2251. }
  2252. CARLA_SAFE_ASSERT_CONTINUE(stateSave.type != nullptr);
  2253. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2254. // compatibility code to load projects with GIG files
  2255. // FIXME Remove on 2.1 release
  2256. if (std::strcmp(stateSave.type, "GIG") == 0)
  2257. {
  2258. if (addPlugin(PLUGIN_LV2, "", stateSave.name, "http://linuxsampler.org/plugins/linuxsampler", 0, nullptr))
  2259. {
  2260. const uint pluginId = pData->curPluginCount;
  2261. if (const CarlaPluginPtr plugin = pData->plugins[pluginId].plugin)
  2262. {
  2263. if (pData->aboutToClose)
  2264. return true;
  2265. if (pData->actionCanceled)
  2266. {
  2267. setLastError("Project load canceled");
  2268. return false;
  2269. }
  2270. String lsState;
  2271. lsState << "0.35\n";
  2272. lsState << "18 0 Chromatic\n";
  2273. lsState << "18 1 Drum Kits\n";
  2274. lsState << "20 0\n";
  2275. lsState << "0 1 " << stateSave.binary << "\n";
  2276. lsState << "0 0 0 0 1 0 GIG\n";
  2277. plugin->setCustomData(LV2_ATOM__String, "http://linuxsampler.org/schema#state-string", lsState.toRawUTF8(), true);
  2278. plugin->restoreLV2State(true);
  2279. plugin->setDryWet(stateSave.dryWet, true, true);
  2280. plugin->setVolume(stateSave.volume, true, true);
  2281. plugin->setBalanceLeft(stateSave.balanceLeft, true, true);
  2282. plugin->setBalanceRight(stateSave.balanceRight, true, true);
  2283. plugin->setPanning(stateSave.panning, true, true);
  2284. plugin->setCtrlChannel(stateSave.ctrlChannel, true, true);
  2285. plugin->setActive(stateSave.active, true, true);
  2286. plugin->setEnabled(true);
  2287. ++pData->curPluginCount;
  2288. callback(true, true, ENGINE_CALLBACK_PLUGIN_ADDED, pluginId, 0, 0, 0, 0.0f, plugin->getName());
  2289. if (isPatchbay)
  2290. pData->graph.addPlugin(plugin);
  2291. }
  2292. else
  2293. {
  2294. carla_stderr2("Failed to get new plugin, state will not be restored correctly\n");
  2295. }
  2296. }
  2297. else
  2298. {
  2299. carla_stderr2("Failed to load a linuxsampler LV2 plugin, GIG file won't be loaded");
  2300. }
  2301. callback(true, true, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  2302. continue;
  2303. }
  2304. # ifdef SFZ_FILES_USING_SFIZZ
  2305. if (std::strcmp(stateSave.type, "SFZ") == 0)
  2306. {
  2307. if (addPlugin(PLUGIN_LV2, "", stateSave.name, "http://sfztools.github.io/sfizz", 0, nullptr))
  2308. {
  2309. const uint pluginId = pData->curPluginCount;
  2310. if (const CarlaPluginPtr plugin = pData->plugins[pluginId].plugin)
  2311. {
  2312. if (pData->aboutToClose)
  2313. return true;
  2314. if (pData->actionCanceled)
  2315. {
  2316. setLastError("Project load canceled");
  2317. return false;
  2318. }
  2319. plugin->setCustomData(LV2_ATOM__Path,
  2320. "http://sfztools.github.io/sfizz:sfzfile",
  2321. stateSave.binary,
  2322. false);
  2323. plugin->restoreLV2State(true);
  2324. plugin->setDryWet(stateSave.dryWet, true, true);
  2325. plugin->setVolume(stateSave.volume, true, true);
  2326. plugin->setBalanceLeft(stateSave.balanceLeft, true, true);
  2327. plugin->setBalanceRight(stateSave.balanceRight, true, true);
  2328. plugin->setPanning(stateSave.panning, true, true);
  2329. plugin->setCtrlChannel(stateSave.ctrlChannel, true, true);
  2330. plugin->setActive(stateSave.active, true, true);
  2331. plugin->setEnabled(true);
  2332. ++pData->curPluginCount;
  2333. callback(true, true, ENGINE_CALLBACK_PLUGIN_ADDED, pluginId, 0, 0, 0, 0.0f, plugin->getName());
  2334. if (isPatchbay)
  2335. pData->graph.addPlugin(plugin);
  2336. }
  2337. else
  2338. {
  2339. carla_stderr2("Failed to get new plugin, state will not be restored correctly\n");
  2340. }
  2341. }
  2342. else
  2343. {
  2344. carla_stderr2("Failed to load a sfizz LV2 plugin, SFZ file won't be loaded");
  2345. }
  2346. callback(true, true, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  2347. continue;
  2348. }
  2349. # endif
  2350. #endif
  2351. const void* extraStuff = nullptr;
  2352. static const char kTrue[] = "true";
  2353. const PluginType ptype(getPluginTypeFromString(stateSave.type));
  2354. switch (ptype)
  2355. {
  2356. case PLUGIN_SF2:
  2357. if (CarlaString(stateSave.label).endsWith(" (16 outs)"))
  2358. extraStuff = kTrue;
  2359. // fall through
  2360. case PLUGIN_LADSPA:
  2361. case PLUGIN_DSSI:
  2362. case PLUGIN_VST2:
  2363. case PLUGIN_VST3:
  2364. case PLUGIN_SFZ:
  2365. if (stateSave.binary != nullptr && stateSave.binary[0] != '\0' &&
  2366. ! (File::isAbsolutePath(stateSave.binary) && File(stateSave.binary).exists()))
  2367. {
  2368. const char* searchPath;
  2369. switch (ptype)
  2370. {
  2371. case PLUGIN_LADSPA: searchPath = pData->options.pathLADSPA; break;
  2372. case PLUGIN_DSSI: searchPath = pData->options.pathDSSI; break;
  2373. case PLUGIN_VST2: searchPath = pData->options.pathVST2; break;
  2374. case PLUGIN_VST3: searchPath = pData->options.pathVST3; break;
  2375. case PLUGIN_SF2: searchPath = pData->options.pathSF2; break;
  2376. case PLUGIN_SFZ: searchPath = pData->options.pathSFZ; break;
  2377. default: searchPath = nullptr; break;
  2378. }
  2379. if (searchPath != nullptr && searchPath[0] != '\0')
  2380. {
  2381. carla_stderr("Plugin binary '%s' doesn't exist on this filesystem, let's look for it...",
  2382. stateSave.binary);
  2383. String result = findBinaryInCustomPath(searchPath, stateSave.binary);
  2384. if (result.isEmpty())
  2385. {
  2386. switch (ptype)
  2387. {
  2388. case PLUGIN_LADSPA: searchPath = std::getenv("LADSPA_PATH"); break;
  2389. case PLUGIN_DSSI: searchPath = std::getenv("DSSI_PATH"); break;
  2390. case PLUGIN_VST2: searchPath = std::getenv("VST_PATH"); break;
  2391. case PLUGIN_VST3: searchPath = std::getenv("VST3_PATH"); break;
  2392. case PLUGIN_SF2: searchPath = std::getenv("SF2_PATH"); break;
  2393. case PLUGIN_SFZ: searchPath = std::getenv("SFZ_PATH"); break;
  2394. default: searchPath = nullptr; break;
  2395. }
  2396. if (searchPath != nullptr && searchPath[0] != '\0')
  2397. result = findBinaryInCustomPath(searchPath, stateSave.binary);
  2398. }
  2399. if (result.isNotEmpty())
  2400. {
  2401. delete[] stateSave.binary;
  2402. stateSave.binary = carla_strdup(result.toRawUTF8());
  2403. carla_stderr("Found it! :)");
  2404. }
  2405. else
  2406. {
  2407. carla_stderr("Damn, we failed... :(");
  2408. }
  2409. callback(true, true, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  2410. }
  2411. }
  2412. break;
  2413. default:
  2414. break;
  2415. }
  2416. BinaryType btype;
  2417. switch (ptype)
  2418. {
  2419. case PLUGIN_LADSPA:
  2420. case PLUGIN_DSSI:
  2421. case PLUGIN_LV2:
  2422. case PLUGIN_VST2:
  2423. btype = getBinaryTypeFromFile(stateSave.binary);
  2424. break;
  2425. default:
  2426. btype = BINARY_NATIVE;
  2427. break;
  2428. }
  2429. if (addPlugin(btype, ptype, stateSave.binary,
  2430. stateSave.name, stateSave.label, stateSave.uniqueId, extraStuff, stateSave.options))
  2431. {
  2432. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2433. const uint pluginId = pData->curPluginCount;
  2434. #else
  2435. const uint pluginId = 0;
  2436. #endif
  2437. if (const CarlaPluginPtr plugin = pData->plugins[pluginId].plugin)
  2438. {
  2439. if (pData->aboutToClose)
  2440. return true;
  2441. if (pData->actionCanceled)
  2442. {
  2443. setLastError("Project load canceled");
  2444. return false;
  2445. }
  2446. // deactivate bridge client-side ping check, since some plugins block during load
  2447. if ((plugin->getHints() & PLUGIN_IS_BRIDGE) != 0 && ! isPreset)
  2448. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "false", false);
  2449. plugin->loadStateSave(stateSave);
  2450. /* NOTE: The following code is the same as the end of addPlugin().
  2451. * When project is loading we do not enable the plugin right away,
  2452. * as we want to load state first.
  2453. */
  2454. plugin->setEnabled(true);
  2455. ++pData->curPluginCount;
  2456. callback(true, true, ENGINE_CALLBACK_PLUGIN_ADDED, pluginId, 0, 0, 0, 0.0f, plugin->getName());
  2457. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2458. if (isPatchbay)
  2459. pData->graph.addPlugin(plugin);
  2460. #endif
  2461. }
  2462. else
  2463. {
  2464. carla_stderr2("Failed to get new plugin, state will not be restored correctly\n");
  2465. }
  2466. }
  2467. else
  2468. {
  2469. carla_stderr2("Failed to load a plugin '%s', error was:\n%s", stateSave.name, getLastError());
  2470. }
  2471. if (! isPreset)
  2472. callback(true, true, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  2473. }
  2474. if (isPreset)
  2475. {
  2476. callback(true, true, ENGINE_CALLBACK_PROJECT_LOAD_FINISHED, 0, 0, 0, 0, 0.0f, nullptr);
  2477. callback(true, true, ENGINE_CALLBACK_CANCELABLE_ACTION, 0, 0, 0, 0, 0.0f, "Loading project");
  2478. return true;
  2479. }
  2480. }
  2481. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2482. // tell bridges we're done loading
  2483. for (uint i=0; i < pData->curPluginCount; ++i)
  2484. {
  2485. if (const CarlaPluginPtr plugin = pData->plugins[i].plugin)
  2486. if (plugin->isEnabled() && (plugin->getHints() & PLUGIN_IS_BRIDGE) != 0)
  2487. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "true", false);
  2488. }
  2489. if (pData->aboutToClose)
  2490. return true;
  2491. if (pData->actionCanceled)
  2492. {
  2493. setLastError("Project load canceled");
  2494. return false;
  2495. }
  2496. // now we handle positions
  2497. bool loadingAsExternal;
  2498. std::map<water::String, water::String> mapGroupNamesInternal, mapGroupNamesExternal;
  2499. bool hasInternalPositions = false;
  2500. if (XmlElement* const elemPatchbay = xmlElement->getChildByName("Patchbay"))
  2501. {
  2502. hasInternalPositions = true;
  2503. if (XmlElement* const elemPositions = elemPatchbay->getChildByName("Positions"))
  2504. {
  2505. String name;
  2506. PatchbayPosition ppos = { nullptr, -1, 0, 0, 0, 0, false };
  2507. for (XmlElement* patchElem = elemPositions->getFirstChildElement(); patchElem != nullptr; patchElem = patchElem->getNextElement())
  2508. {
  2509. const String& patchTag(patchElem->getTagName());
  2510. if (patchTag != "Position")
  2511. continue;
  2512. XmlElement* const patchName = patchElem->getChildByName("Name");
  2513. CARLA_SAFE_ASSERT_CONTINUE(patchName != nullptr);
  2514. const String nameText(patchName->getAllSubText().trim());
  2515. name = xmlSafeString(nameText, false);
  2516. ppos.name = name.toRawUTF8();
  2517. ppos.x1 = patchElem->getIntAttribute("x1");
  2518. ppos.y1 = patchElem->getIntAttribute("y1");
  2519. ppos.x2 = patchElem->getIntAttribute("x2");
  2520. ppos.y2 = patchElem->getIntAttribute("y2");
  2521. ppos.pluginId = patchElem->getIntAttribute("pluginId", -1);
  2522. ppos.dealloc = false;
  2523. loadingAsExternal = ppos.pluginId >= 0 && isMultiClient;
  2524. if (name.isNotEmpty() && restorePatchbayGroupPosition(loadingAsExternal, ppos))
  2525. {
  2526. if (name != ppos.name)
  2527. {
  2528. carla_stdout("Converted client name '%s' to '%s' for this session",
  2529. name.toRawUTF8(), ppos.name);
  2530. if (loadingAsExternal)
  2531. mapGroupNamesExternal[name] = ppos.name;
  2532. else
  2533. mapGroupNamesInternal[name] = ppos.name;
  2534. }
  2535. if (ppos.dealloc)
  2536. std::free(const_cast<char*>(ppos.name));
  2537. }
  2538. }
  2539. if (pData->aboutToClose)
  2540. return true;
  2541. if (pData->actionCanceled)
  2542. {
  2543. setLastError("Project load canceled");
  2544. return false;
  2545. }
  2546. }
  2547. }
  2548. if (XmlElement* const elemPatchbay = xmlElement->getChildByName("ExternalPatchbay"))
  2549. {
  2550. if (XmlElement* const elemPositions = elemPatchbay->getChildByName("Positions"))
  2551. {
  2552. String name;
  2553. PatchbayPosition ppos = { nullptr, -1, 0, 0, 0, 0, false };
  2554. for (XmlElement* patchElem = elemPositions->getFirstChildElement(); patchElem != nullptr; patchElem = patchElem->getNextElement())
  2555. {
  2556. const String& patchTag(patchElem->getTagName());
  2557. if (patchTag != "Position")
  2558. continue;
  2559. XmlElement* const patchName = patchElem->getChildByName("Name");
  2560. CARLA_SAFE_ASSERT_CONTINUE(patchName != nullptr);
  2561. const String nameText(patchName->getAllSubText().trim());
  2562. name = xmlSafeString(nameText, false);
  2563. ppos.name = name.toRawUTF8();
  2564. ppos.x1 = patchElem->getIntAttribute("x1");
  2565. ppos.y1 = patchElem->getIntAttribute("y1");
  2566. ppos.x2 = patchElem->getIntAttribute("x2");
  2567. ppos.y2 = patchElem->getIntAttribute("y2");
  2568. ppos.pluginId = patchElem->getIntAttribute("pluginId", -1);
  2569. ppos.dealloc = false;
  2570. loadingAsExternal = ppos.pluginId < 0 || hasInternalPositions || !isPatchbay;
  2571. carla_debug("loadingAsExternal: %i because %i %i %i",
  2572. loadingAsExternal, ppos.pluginId < 0, hasInternalPositions, !isPatchbay);
  2573. if (name.isNotEmpty() && restorePatchbayGroupPosition(loadingAsExternal, ppos))
  2574. {
  2575. if (name != ppos.name)
  2576. {
  2577. carla_stdout("Converted client name '%s' to '%s' for this session",
  2578. name.toRawUTF8(), ppos.name);
  2579. if (loadingAsExternal)
  2580. mapGroupNamesExternal[name] = ppos.name;
  2581. else
  2582. mapGroupNamesInternal[name] = ppos.name;
  2583. }
  2584. if (ppos.dealloc)
  2585. std::free(const_cast<char*>(ppos.name));
  2586. }
  2587. }
  2588. if (pData->aboutToClose)
  2589. return true;
  2590. if (pData->actionCanceled)
  2591. {
  2592. setLastError("Project load canceled");
  2593. return false;
  2594. }
  2595. }
  2596. }
  2597. bool hasInternalConnections = false;
  2598. // and now we handle connections (internal)
  2599. if (XmlElement* const elem = xmlElement->getChildByName("Patchbay"))
  2600. {
  2601. hasInternalConnections = true;
  2602. if (isPatchbay)
  2603. {
  2604. water::String sourcePort, targetPort;
  2605. for (XmlElement* patchElem = elem->getFirstChildElement(); patchElem != nullptr; patchElem = patchElem->getNextElement())
  2606. {
  2607. const String& patchTag(patchElem->getTagName());
  2608. if (patchTag != "Connection")
  2609. continue;
  2610. sourcePort.clear();
  2611. targetPort.clear();
  2612. for (XmlElement* connElem = patchElem->getFirstChildElement(); connElem != nullptr; connElem = connElem->getNextElement())
  2613. {
  2614. const String& tag(connElem->getTagName());
  2615. const String text(connElem->getAllSubText().trim());
  2616. /**/ if (tag == "Source")
  2617. sourcePort = xmlSafeString(text, false);
  2618. else if (tag == "Target")
  2619. targetPort = xmlSafeString(text, false);
  2620. }
  2621. if (sourcePort.isNotEmpty() && targetPort.isNotEmpty())
  2622. {
  2623. std::map<water::String, water::String>& map(mapGroupNamesInternal);
  2624. std::map<water::String, water::String>::iterator it;
  2625. if ((it = map.find(sourcePort.upToFirstOccurrenceOf(":", false, false))) != map.end())
  2626. sourcePort = it->second + sourcePort.fromFirstOccurrenceOf(":", true, false);
  2627. if ((it = map.find(targetPort.upToFirstOccurrenceOf(":", false, false))) != map.end())
  2628. targetPort = it->second + targetPort.fromFirstOccurrenceOf(":", true, false);
  2629. restorePatchbayConnection(false, sourcePort.toRawUTF8(), targetPort.toRawUTF8());
  2630. }
  2631. }
  2632. if (pData->aboutToClose)
  2633. return true;
  2634. if (pData->actionCanceled)
  2635. {
  2636. setLastError("Project load canceled");
  2637. return false;
  2638. }
  2639. }
  2640. }
  2641. // if we're running inside some session-manager (and using JACK), let them handle the external connections
  2642. bool loadExternalConnections;
  2643. if (alwaysLoadConnections)
  2644. {
  2645. loadExternalConnections = true;
  2646. }
  2647. else
  2648. {
  2649. /**/ if (std::strcmp(getCurrentDriverName(), "JACK") != 0)
  2650. loadExternalConnections = true;
  2651. else if (std::getenv("CARLA_DONT_MANAGE_CONNECTIONS") != nullptr)
  2652. loadExternalConnections = false;
  2653. else if (std::getenv("LADISH_APP_NAME") != nullptr)
  2654. loadExternalConnections = false;
  2655. else if (std::getenv("NSM_URL") != nullptr)
  2656. loadExternalConnections = false;
  2657. else
  2658. loadExternalConnections = true;
  2659. }
  2660. // plus external connections too
  2661. if (loadExternalConnections)
  2662. {
  2663. bool isExternal;
  2664. loadingAsExternal = hasInternalConnections &&
  2665. (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK || isPatchbay);
  2666. for (XmlElement* elem = xmlElement->getFirstChildElement(); elem != nullptr; elem = elem->getNextElement())
  2667. {
  2668. const String& tagName(elem->getTagName());
  2669. // check if we want to load patchbay-mode connections into an external (multi-client) graph
  2670. if (tagName == "Patchbay")
  2671. {
  2672. if (isPatchbay)
  2673. continue;
  2674. isExternal = false;
  2675. loadingAsExternal = true;
  2676. }
  2677. // or load external patchbay connections
  2678. else if (tagName == "ExternalPatchbay")
  2679. {
  2680. if (! isPatchbay)
  2681. loadingAsExternal = true;
  2682. isExternal = true;
  2683. }
  2684. else
  2685. {
  2686. continue;
  2687. }
  2688. water::String sourcePort, targetPort;
  2689. for (XmlElement* patchElem = elem->getFirstChildElement(); patchElem != nullptr; patchElem = patchElem->getNextElement())
  2690. {
  2691. const String& patchTag(patchElem->getTagName());
  2692. if (patchTag != "Connection")
  2693. continue;
  2694. sourcePort.clear();
  2695. targetPort.clear();
  2696. for (XmlElement* connElem = patchElem->getFirstChildElement(); connElem != nullptr; connElem = connElem->getNextElement())
  2697. {
  2698. const String& tag(connElem->getTagName());
  2699. const String text(connElem->getAllSubText().trim());
  2700. /**/ if (tag == "Source")
  2701. sourcePort = xmlSafeString(text, false);
  2702. else if (tag == "Target")
  2703. targetPort = xmlSafeString(text, false);
  2704. }
  2705. if (sourcePort.isNotEmpty() && targetPort.isNotEmpty())
  2706. {
  2707. std::map<water::String, water::String>& map(loadingAsExternal ? mapGroupNamesExternal
  2708. : mapGroupNamesInternal);
  2709. std::map<water::String, water::String>::iterator it;
  2710. if (isExternal && isPatchbay && !loadingAsExternal && sourcePort.startsWith("system:capture_"))
  2711. {
  2712. water::String internalPort = sourcePort.trimCharactersAtStart("system:capture_");
  2713. if (pData->graph.getNumAudioOuts() < 3)
  2714. {
  2715. /**/ if (internalPort == "1")
  2716. internalPort = "Audio Input:Left";
  2717. else if (internalPort == "2")
  2718. internalPort = "Audio Input:Right";
  2719. else if (internalPort == "3")
  2720. internalPort = "Audio Input:Sidechain";
  2721. else
  2722. continue;
  2723. }
  2724. else
  2725. {
  2726. internalPort = "Audio Input:Capture " + internalPort;
  2727. }
  2728. carla_stdout("Converted port name '%s' to '%s' for this session",
  2729. sourcePort.toRawUTF8(), internalPort.toRawUTF8());
  2730. sourcePort = internalPort;
  2731. }
  2732. else if (!isExternal && isMultiClient && sourcePort.startsWith("Audio Input:"))
  2733. {
  2734. water::String externalPort = sourcePort.trimCharactersAtStart("Audio Input:");
  2735. /**/ if (externalPort == "Left")
  2736. externalPort = "system:capture_1";
  2737. else if (externalPort == "Right")
  2738. externalPort = "system:capture_2";
  2739. else if (externalPort == "Sidechain")
  2740. externalPort = "system:capture_3";
  2741. else
  2742. externalPort = "system:capture_ " + externalPort.trimCharactersAtStart("Capture ");
  2743. carla_stdout("Converted port name '%s' to '%s' for this session",
  2744. sourcePort.toRawUTF8(), externalPort.toRawUTF8());
  2745. sourcePort = externalPort;
  2746. }
  2747. else if ((it = map.find(sourcePort.upToFirstOccurrenceOf(":", false, false))) != map.end())
  2748. {
  2749. sourcePort = it->second + sourcePort.fromFirstOccurrenceOf(":", true, false);
  2750. }
  2751. if (isExternal && isPatchbay && !loadingAsExternal && targetPort.startsWith("system:playback_"))
  2752. {
  2753. water::String internalPort = targetPort.trimCharactersAtStart("system:playback_");
  2754. if (pData->graph.getNumAudioOuts() < 3)
  2755. {
  2756. /**/ if (internalPort == "1")
  2757. internalPort = "Audio Output:Left";
  2758. else if (internalPort == "2")
  2759. internalPort = "Audio Output:Right";
  2760. else
  2761. continue;
  2762. }
  2763. else
  2764. {
  2765. internalPort = "Audio Input:Playback " + internalPort;
  2766. }
  2767. carla_stdout("Converted port name '%s' to '%s' for this session",
  2768. targetPort.toRawUTF8(), internalPort.toRawUTF8());
  2769. targetPort = internalPort;
  2770. }
  2771. else if (!isExternal && isMultiClient && targetPort.startsWith("Audio Output:"))
  2772. {
  2773. water::String externalPort = targetPort.trimCharactersAtStart("Audio Output:");
  2774. /**/ if (externalPort == "Left")
  2775. externalPort = "system:playback_1";
  2776. else if (externalPort == "Right")
  2777. externalPort = "system:playback_2";
  2778. else
  2779. externalPort = "system:playback_ " + externalPort.trimCharactersAtStart("Playback ");
  2780. carla_stdout("Converted port name '%s' to '%s' for this session",
  2781. targetPort.toRawUTF8(), externalPort.toRawUTF8());
  2782. targetPort = externalPort;
  2783. }
  2784. else if ((it = map.find(targetPort.upToFirstOccurrenceOf(":", false, false))) != map.end())
  2785. {
  2786. targetPort = it->second + targetPort.fromFirstOccurrenceOf(":", true, false);
  2787. }
  2788. restorePatchbayConnection(loadingAsExternal, sourcePort.toRawUTF8(), targetPort.toRawUTF8());
  2789. }
  2790. }
  2791. break;
  2792. }
  2793. }
  2794. #endif
  2795. if (pData->options.resetXruns)
  2796. clearXruns();
  2797. callback(true, true, ENGINE_CALLBACK_PROJECT_LOAD_FINISHED, 0, 0, 0, 0, 0.0f, nullptr);
  2798. callback(true, true, ENGINE_CALLBACK_CANCELABLE_ACTION, 0, 0, 0, 0, 0.0f, "Loading project");
  2799. carla_debug("CarlaEngine::loadProjectInternal(%p, %s) - END", &xmlDoc, bool2str(alwaysLoadConnections));
  2800. return true;
  2801. #ifdef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2802. // unused
  2803. (void)alwaysLoadConnections;
  2804. #endif
  2805. }
  2806. // -----------------------------------------------------------------------
  2807. CARLA_BACKEND_END_NAMESPACE