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.

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