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.

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