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.

3459 lines
117KB

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