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.

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