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.

3477 lines
118KB

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