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.

3467 lines
118KB

  1. /*
  2. * Carla Plugin Host
  3. * Copyright (C) 2011-2020 Filipe Coelho <falktx@falktx.com>
  4. *
  5. * This program is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU General Public License as
  7. * published by the Free Software Foundation; either version 2 of
  8. * the License, or any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * For a full copy of the GNU General Public License see the doc/GPL.txt file.
  16. */
  17. /* TODO:
  18. * - complete processRack(): carefully add to input, sorted events
  19. * - implement processPatchbay()
  20. * - implement oscSend_control_switch_plugins()
  21. * - something about the peaks?
  22. */
  23. #include "CarlaEngineClient.hpp"
  24. #include "CarlaEngineInit.hpp"
  25. #include "CarlaEngineInternal.hpp"
  26. #include "CarlaPlugin.hpp"
  27. #include "CarlaBackendUtils.hpp"
  28. #include "CarlaBinaryUtils.hpp"
  29. #include "CarlaEngineUtils.hpp"
  30. #include "CarlaMathUtils.hpp"
  31. #include "CarlaPipeUtils.hpp"
  32. #include "CarlaProcessUtils.hpp"
  33. #include "CarlaScopeUtils.hpp"
  34. #include "CarlaStateUtils.hpp"
  35. #include "CarlaMIDI.h"
  36. #include "jackbridge/JackBridge.hpp"
  37. #include "water/files/File.h"
  38. #include "water/streams/MemoryOutputStream.h"
  39. #include "water/xml/XmlDocument.h"
  40. #include "water/xml/XmlElement.h"
  41. #ifdef CARLA_OS_MAC
  42. # include "CarlaMacUtils.hpp"
  43. # if defined(CARLA_OS_64BIT) && defined(HAVE_LIBMAGIC) && ! defined(BUILD_BRIDGE_ALTERNATIVE_ARCH)
  44. # define ADAPT_FOR_APPLE_SILLICON
  45. # endif
  46. #endif
  47. #include <map>
  48. // FIXME Remove on 2.1 release
  49. #include "lv2/atom.h"
  50. using water::Array;
  51. using water::CharPointer_UTF8;
  52. using water::File;
  53. using water::MemoryOutputStream;
  54. using water::String;
  55. using water::StringArray;
  56. using water::XmlDocument;
  57. using water::XmlElement;
  58. // #define SFZ_FILES_USING_SFIZZ
  59. CARLA_BACKEND_START_NAMESPACE
  60. // -----------------------------------------------------------------------
  61. // Carla Engine
  62. CarlaEngine::CarlaEngine()
  63. : pData(new ProtectedData(this))
  64. {
  65. carla_debug("CarlaEngine::CarlaEngine()");
  66. }
  67. CarlaEngine::~CarlaEngine()
  68. {
  69. carla_debug("CarlaEngine::~CarlaEngine()");
  70. delete pData;
  71. }
  72. // -----------------------------------------------------------------------
  73. // Static calls
  74. uint CarlaEngine::getDriverCount()
  75. {
  76. carla_debug("CarlaEngine::getDriverCount()");
  77. using namespace EngineInit;
  78. uint count = 0;
  79. if (jackbridge_is_ok())
  80. count += 1;
  81. #ifndef BUILD_BRIDGE
  82. # ifdef USING_JUCE_AUDIO_DEVICES
  83. count += getJuceApiCount();
  84. # else
  85. count += getRtAudioApiCount();
  86. # endif
  87. #endif
  88. return count;
  89. }
  90. const char* CarlaEngine::getDriverName(const uint index2)
  91. {
  92. carla_debug("CarlaEngine::getDriverName(%i)", index2);
  93. using namespace EngineInit;
  94. uint index = index2;
  95. if (jackbridge_is_ok() && index-- == 0)
  96. return "JACK";
  97. #ifndef BUILD_BRIDGE
  98. # ifdef USING_JUCE_AUDIO_DEVICES
  99. if (const uint count = getJuceApiCount())
  100. {
  101. if (index < count)
  102. return getJuceApiName(index);
  103. index -= count;
  104. }
  105. # else
  106. if (const uint count = getRtAudioApiCount())
  107. {
  108. if (index < count)
  109. return getRtAudioApiName(index);
  110. }
  111. # endif
  112. #endif
  113. carla_stderr("CarlaEngine::getDriverName(%i) - invalid index", index2);
  114. return nullptr;
  115. }
  116. const char* const* CarlaEngine::getDriverDeviceNames(const uint index2)
  117. {
  118. carla_debug("CarlaEngine::getDriverDeviceNames(%i)", index2);
  119. using namespace EngineInit;
  120. uint index = index2;
  121. if (jackbridge_is_ok() && index-- == 0)
  122. {
  123. static const char* ret[3] = { "Auto-Connect ON", "Auto-Connect OFF", nullptr };
  124. return ret;
  125. }
  126. #ifndef BUILD_BRIDGE
  127. # ifdef USING_JUCE_AUDIO_DEVICES
  128. if (const uint count = getJuceApiCount())
  129. {
  130. if (index < count)
  131. return getJuceApiDeviceNames(index);
  132. index -= count;
  133. }
  134. # else
  135. if (const uint count = getRtAudioApiCount())
  136. {
  137. if (index < count)
  138. return getRtAudioApiDeviceNames(index);
  139. }
  140. # endif
  141. #endif
  142. carla_stderr("CarlaEngine::getDriverDeviceNames(%i) - invalid index", index2);
  143. return nullptr;
  144. }
  145. const EngineDriverDeviceInfo* CarlaEngine::getDriverDeviceInfo(const uint index2, const char* const deviceName)
  146. {
  147. carla_debug("CarlaEngine::getDriverDeviceInfo(%i, \"%s\")", index2, deviceName);
  148. using namespace EngineInit;
  149. uint index = index2;
  150. if (jackbridge_is_ok() && index-- == 0)
  151. {
  152. static EngineDriverDeviceInfo devInfo;
  153. devInfo.hints = ENGINE_DRIVER_DEVICE_VARIABLE_BUFFER_SIZE;
  154. devInfo.bufferSizes = nullptr;
  155. devInfo.sampleRates = nullptr;
  156. return &devInfo;
  157. }
  158. #ifndef BUILD_BRIDGE
  159. # ifdef USING_JUCE_AUDIO_DEVICES
  160. if (const uint count = getJuceApiCount())
  161. {
  162. if (index < count)
  163. return getJuceDeviceInfo(index, deviceName);
  164. index -= count;
  165. }
  166. # else
  167. if (const uint count = getRtAudioApiCount())
  168. {
  169. if (index < count)
  170. return getRtAudioDeviceInfo(index, deviceName);
  171. }
  172. # endif
  173. #endif
  174. carla_stderr("CarlaEngine::getDriverDeviceNames(%i, \"%s\") - invalid index", index2, deviceName);
  175. return nullptr;
  176. }
  177. bool CarlaEngine::showDriverDeviceControlPanel(const uint index2, const char* const deviceName)
  178. {
  179. carla_debug("CarlaEngine::showDriverDeviceControlPanel(%i, \"%s\")", index2, deviceName);
  180. using namespace EngineInit;
  181. uint index = index2;
  182. if (jackbridge_is_ok() && index-- == 0)
  183. {
  184. return false;
  185. }
  186. #ifndef BUILD_BRIDGE
  187. # ifdef USING_JUCE_AUDIO_DEVICES
  188. if (const uint count = getJuceApiCount())
  189. {
  190. if (index < count)
  191. return showJuceDeviceControlPanel(index, deviceName);
  192. index -= count;
  193. }
  194. # else
  195. if (const uint count = getRtAudioApiCount())
  196. {
  197. if (index < count)
  198. return false;
  199. }
  200. # endif
  201. #endif
  202. carla_stderr("CarlaEngine::showDriverDeviceControlPanel(%i, \"%s\") - invalid index", index2, deviceName);
  203. return false;
  204. }
  205. CarlaEngine* CarlaEngine::newDriverByName(const char* const driverName)
  206. {
  207. CARLA_SAFE_ASSERT_RETURN(driverName != nullptr && driverName[0] != '\0', nullptr);
  208. carla_debug("CarlaEngine::newDriverByName(\"%s\")", driverName);
  209. using namespace EngineInit;
  210. if (std::strcmp(driverName, "JACK") == 0)
  211. return newJack();
  212. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  213. if (std::strcmp(driverName, "Dummy") == 0)
  214. return newDummy();
  215. #endif
  216. #ifndef BUILD_BRIDGE
  217. # ifdef USING_JUCE_AUDIO_DEVICES
  218. // -------------------------------------------------------------------
  219. // linux
  220. if (std::strcmp(driverName, "ALSA") == 0)
  221. return newJuce(AUDIO_API_ALSA);
  222. // -------------------------------------------------------------------
  223. // macos
  224. if (std::strcmp(driverName, "CoreAudio") == 0)
  225. return newJuce(AUDIO_API_COREAUDIO);
  226. // -------------------------------------------------------------------
  227. // windows
  228. if (std::strcmp(driverName, "ASIO") == 0)
  229. return newJuce(AUDIO_API_ASIO);
  230. if (std::strcmp(driverName, "DirectSound") == 0)
  231. return newJuce(AUDIO_API_DIRECTSOUND);
  232. if (std::strcmp(driverName, "WASAPI") == 0 || std::strcmp(driverName, "Windows Audio") == 0)
  233. return newJuce(AUDIO_API_WASAPI);
  234. # else
  235. // -------------------------------------------------------------------
  236. // common
  237. if (std::strncmp(driverName, "JACK ", 5) == 0)
  238. return newRtAudio(AUDIO_API_JACK);
  239. if (std::strcmp(driverName, "OSS") == 0)
  240. return newRtAudio(AUDIO_API_OSS);
  241. // -------------------------------------------------------------------
  242. // linux
  243. if (std::strcmp(driverName, "ALSA") == 0)
  244. return newRtAudio(AUDIO_API_ALSA);
  245. if (std::strcmp(driverName, "PulseAudio") == 0)
  246. return newRtAudio(AUDIO_API_PULSEAUDIO);
  247. // -------------------------------------------------------------------
  248. // macos
  249. if (std::strcmp(driverName, "CoreAudio") == 0)
  250. return newRtAudio(AUDIO_API_COREAUDIO);
  251. // -------------------------------------------------------------------
  252. // windows
  253. if (std::strcmp(driverName, "ASIO") == 0)
  254. return newRtAudio(AUDIO_API_ASIO);
  255. if (std::strcmp(driverName, "DirectSound") == 0)
  256. return newRtAudio(AUDIO_API_DIRECTSOUND);
  257. if (std::strcmp(driverName, "WASAPI") == 0)
  258. return newRtAudio(AUDIO_API_WASAPI);
  259. # endif
  260. #endif
  261. carla_stderr("CarlaEngine::newDriverByName(\"%s\") - invalid driver name", driverName);
  262. return nullptr;
  263. }
  264. // -----------------------------------------------------------------------
  265. // Constant values
  266. uint CarlaEngine::getMaxClientNameSize() const noexcept
  267. {
  268. return STR_MAX/2;
  269. }
  270. uint CarlaEngine::getMaxPortNameSize() const noexcept
  271. {
  272. return STR_MAX;
  273. }
  274. uint CarlaEngine::getCurrentPluginCount() const noexcept
  275. {
  276. return pData->curPluginCount;
  277. }
  278. uint CarlaEngine::getMaxPluginNumber() const noexcept
  279. {
  280. return pData->maxPluginNumber;
  281. }
  282. // -----------------------------------------------------------------------
  283. // Virtual, per-engine type calls
  284. bool CarlaEngine::close()
  285. {
  286. carla_debug("CarlaEngine::close()");
  287. if (pData->curPluginCount != 0)
  288. {
  289. pData->aboutToClose = true;
  290. removeAllPlugins();
  291. }
  292. pData->close();
  293. callback(true, true, ENGINE_CALLBACK_ENGINE_STOPPED, 0, 0, 0, 0, 0.0f, nullptr);
  294. return true;
  295. }
  296. bool CarlaEngine::usesConstantBufferSize() const noexcept
  297. {
  298. return true;
  299. }
  300. void CarlaEngine::idle() noexcept
  301. {
  302. CARLA_SAFE_ASSERT_RETURN(pData->nextAction.opcode == kEnginePostActionNull,);
  303. CARLA_SAFE_ASSERT_RETURN(pData->nextPluginId == pData->maxPluginNumber,);
  304. CARLA_SAFE_ASSERT_RETURN(getType() != kEngineTypePlugin,);
  305. const bool engineNotRunning = !isRunning();
  306. for (uint i=0; i < pData->curPluginCount; ++i)
  307. {
  308. if (const CarlaPluginPtr plugin = pData->plugins[i].plugin)
  309. {
  310. if (plugin->isEnabled())
  311. {
  312. const uint hints = plugin->getHints();
  313. if (engineNotRunning)
  314. {
  315. try {
  316. plugin->idle();
  317. } CARLA_SAFE_EXCEPTION_CONTINUE("Plugin idle");
  318. if (hints & PLUGIN_HAS_CUSTOM_UI)
  319. {
  320. try {
  321. plugin->uiIdle();
  322. } CARLA_SAFE_EXCEPTION_CONTINUE("Plugin uiIdle");
  323. }
  324. }
  325. else if ((hints & PLUGIN_HAS_CUSTOM_UI) != 0 && (hints & PLUGIN_NEEDS_UI_MAIN_THREAD) != 0)
  326. {
  327. try {
  328. plugin->uiIdle();
  329. } CARLA_SAFE_EXCEPTION_CONTINUE("Plugin uiIdle");
  330. }
  331. }
  332. }
  333. }
  334. #if defined(HAVE_LIBLO) && !defined(BUILD_BRIDGE)
  335. pData->osc.idle();
  336. #endif
  337. pData->deletePluginsAsNeeded();
  338. }
  339. CarlaEngineClient* CarlaEngine::addClient(CarlaPluginPtr plugin)
  340. {
  341. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  342. return new CarlaEngineClientForStandalone(*this, pData->graph, plugin);
  343. #else
  344. return new CarlaEngineClientForBridge(*this);
  345. // unused
  346. (void)plugin;
  347. #endif
  348. }
  349. float CarlaEngine::getDSPLoad() const noexcept
  350. {
  351. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  352. return pData->dspLoad;
  353. #else
  354. return 0.0f;
  355. #endif
  356. }
  357. uint32_t CarlaEngine::getTotalXruns() const noexcept
  358. {
  359. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  360. return pData->xruns;
  361. #else
  362. return 0;
  363. #endif
  364. }
  365. void CarlaEngine::clearXruns() const noexcept
  366. {
  367. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  368. pData->xruns = 0;
  369. #endif
  370. }
  371. bool CarlaEngine::showDeviceControlPanel() const noexcept
  372. {
  373. return false;
  374. }
  375. bool CarlaEngine::setBufferSizeAndSampleRate(const uint, const double)
  376. {
  377. return false;
  378. }
  379. // -----------------------------------------------------------------------
  380. // Plugin management
  381. bool CarlaEngine::addPlugin(const BinaryType btype,
  382. const PluginType ptype,
  383. const char* const filename,
  384. const char* const name,
  385. const char* const label,
  386. const int64_t uniqueId,
  387. const void* const extra,
  388. const uint options)
  389. {
  390. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  391. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  392. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  393. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextPluginId <= pData->maxPluginNumber, "Invalid engine internal data");
  394. #endif
  395. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  396. CARLA_SAFE_ASSERT_RETURN_ERR(btype != BINARY_NONE, "Invalid plugin binary mode");
  397. CARLA_SAFE_ASSERT_RETURN_ERR(ptype != PLUGIN_NONE, "Invalid plugin type");
  398. CARLA_SAFE_ASSERT_RETURN_ERR((filename != nullptr && filename[0] != '\0') || (label != nullptr && label[0] != '\0'), "Invalid plugin filename and label");
  399. carla_debug("CarlaEngine::addPlugin(%i:%s, %i:%s, \"%s\", \"%s\", \"%s\", " P_INT64 ", %p, %u)",
  400. btype, BinaryType2Str(btype), ptype, PluginType2Str(ptype), filename, name, label, uniqueId, extra, options);
  401. #ifndef CARLA_OS_WIN
  402. if (ptype != PLUGIN_JACK && ptype != PLUGIN_LV2 && filename != nullptr && filename[0] != '\0') {
  403. CARLA_SAFE_ASSERT_RETURN_ERR(filename[0] == CARLA_OS_SEP || filename[0] == '.' || filename[0] == '~', "Invalid plugin filename");
  404. }
  405. #endif
  406. uint id;
  407. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  408. CarlaPluginPtr oldPlugin;
  409. if (pData->nextPluginId < pData->curPluginCount)
  410. {
  411. id = pData->nextPluginId;
  412. pData->nextPluginId = pData->maxPluginNumber;
  413. oldPlugin = pData->plugins[id].plugin;
  414. CARLA_SAFE_ASSERT_RETURN_ERR(oldPlugin.get() != nullptr, "Invalid replace plugin Id");
  415. }
  416. else
  417. #endif
  418. {
  419. id = pData->curPluginCount;
  420. if (id == pData->maxPluginNumber)
  421. {
  422. setLastError("Maximum number of plugins reached");
  423. return false;
  424. }
  425. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  426. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins[id].plugin.get() == nullptr, "Invalid engine internal data");
  427. #endif
  428. }
  429. CarlaPlugin::Initializer initializer = {
  430. this,
  431. id,
  432. filename,
  433. name,
  434. label,
  435. uniqueId,
  436. options
  437. };
  438. CarlaPluginPtr plugin;
  439. CarlaString bridgeBinary(pData->options.binaryDir);
  440. if (bridgeBinary.isNotEmpty())
  441. {
  442. #ifndef CARLA_OS_WIN
  443. if (btype == BINARY_NATIVE)
  444. {
  445. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-native";
  446. }
  447. else
  448. #endif
  449. {
  450. switch (btype)
  451. {
  452. case BINARY_POSIX32:
  453. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-posix32";
  454. break;
  455. case BINARY_POSIX64:
  456. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-posix64";
  457. break;
  458. case BINARY_WIN32:
  459. #if defined(CARLA_OS_WIN) && !defined(CARLA_OS_64BIT)
  460. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-native.exe";
  461. #else
  462. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-win32.exe";
  463. #endif
  464. break;
  465. case BINARY_WIN64:
  466. #if defined(CARLA_OS_WIN) && defined(CARLA_OS_64BIT)
  467. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-native.exe";
  468. #else
  469. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-win64.exe";
  470. #endif
  471. break;
  472. default:
  473. bridgeBinary.clear();
  474. break;
  475. }
  476. }
  477. if (! File(bridgeBinary.buffer()).existsAsFile())
  478. bridgeBinary.clear();
  479. }
  480. const bool canBeBridged = ptype != PLUGIN_INTERNAL
  481. && ptype != PLUGIN_DLS
  482. && ptype != PLUGIN_GIG
  483. && ptype != PLUGIN_SF2
  484. && ptype != PLUGIN_SFZ
  485. && ptype != PLUGIN_JACK;
  486. // Prefer bridges for some specific plugins
  487. bool preferBridges = pData->options.preferPluginBridges;
  488. const char* needsArchBridge = nullptr;
  489. #ifdef CARLA_OS_MAC
  490. // Plugin might be in quarentine due to Apple stupid notarization rules, let's remove that if possible
  491. if (canBeBridged && ptype != PLUGIN_LV2 && ptype != PLUGIN_AU)
  492. removeFileFromQuarantine(filename);
  493. #endif
  494. #ifndef BUILD_BRIDGE
  495. if (canBeBridged && ! preferBridges)
  496. {
  497. # if 0
  498. if (ptype == PLUGIN_LV2 && label != nullptr)
  499. {
  500. if (std::strncmp(label, "http://calf.sourceforge.net/plugins/", 36) == 0 ||
  501. std::strcmp(label, "http://factorial.hu/plugins/lv2/ir") == 0 ||
  502. std::strstr(label, "v1.sourceforge.net/lv2") != nullptr)
  503. {
  504. preferBridges = true;
  505. }
  506. }
  507. # endif
  508. # ifdef ADAPT_FOR_APPLE_SILLICON
  509. // see if this binary needs bridging
  510. if (ptype == PLUGIN_VST2 || ptype == PLUGIN_VST3)
  511. {
  512. if (const char* const vst2Binary = findBinaryInBundle(filename))
  513. {
  514. const CarlaMagic magic;
  515. if (const char* const output = magic.getFileDescription(vst2Binary))
  516. {
  517. 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. case ENGINE_OPTION_OSC_ENABLED:
  1553. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1554. #ifndef BUILD_BRIDGE
  1555. pData->options.oscEnabled = (value != 0);
  1556. #endif
  1557. break;
  1558. case ENGINE_OPTION_OSC_PORT_TCP:
  1559. CARLA_SAFE_ASSERT_RETURN(value <= 0 || value >= 1024,);
  1560. #ifndef BUILD_BRIDGE
  1561. pData->options.oscPortTCP = value;
  1562. #endif
  1563. break;
  1564. case ENGINE_OPTION_OSC_PORT_UDP:
  1565. CARLA_SAFE_ASSERT_RETURN(value <= 0 || value >= 1024,);
  1566. #ifndef BUILD_BRIDGE
  1567. pData->options.oscPortUDP = value;
  1568. #endif
  1569. break;
  1570. case ENGINE_OPTION_FILE_PATH:
  1571. CARLA_SAFE_ASSERT_RETURN(value > FILE_NONE,);
  1572. CARLA_SAFE_ASSERT_RETURN(value <= FILE_MIDI,);
  1573. switch (value)
  1574. {
  1575. case FILE_AUDIO:
  1576. if (pData->options.pathAudio != nullptr)
  1577. delete[] pData->options.pathAudio;
  1578. if (valueStr != nullptr)
  1579. pData->options.pathAudio = carla_strdup_safe(valueStr);
  1580. else
  1581. pData->options.pathAudio = nullptr;
  1582. break;
  1583. case FILE_MIDI:
  1584. if (pData->options.pathMIDI != nullptr)
  1585. delete[] pData->options.pathMIDI;
  1586. if (valueStr != nullptr)
  1587. pData->options.pathMIDI = carla_strdup_safe(valueStr);
  1588. else
  1589. pData->options.pathMIDI = nullptr;
  1590. break;
  1591. default:
  1592. return carla_stderr("CarlaEngine::setOption(%i:%s, %i, \"%s\") - Invalid file type",
  1593. option, EngineOption2Str(option), value, valueStr);
  1594. break;
  1595. }
  1596. break;
  1597. case ENGINE_OPTION_PLUGIN_PATH:
  1598. CARLA_SAFE_ASSERT_RETURN(value > PLUGIN_NONE,);
  1599. CARLA_SAFE_ASSERT_RETURN(value <= PLUGIN_SFZ,);
  1600. switch (value)
  1601. {
  1602. case PLUGIN_LADSPA:
  1603. if (pData->options.pathLADSPA != nullptr)
  1604. delete[] pData->options.pathLADSPA;
  1605. if (valueStr != nullptr)
  1606. pData->options.pathLADSPA = carla_strdup_safe(valueStr);
  1607. else
  1608. pData->options.pathLADSPA = nullptr;
  1609. break;
  1610. case PLUGIN_DSSI:
  1611. if (pData->options.pathDSSI != nullptr)
  1612. delete[] pData->options.pathDSSI;
  1613. if (valueStr != nullptr)
  1614. pData->options.pathDSSI = carla_strdup_safe(valueStr);
  1615. else
  1616. pData->options.pathDSSI = nullptr;
  1617. break;
  1618. case PLUGIN_LV2:
  1619. if (pData->options.pathLV2 != nullptr)
  1620. delete[] pData->options.pathLV2;
  1621. if (valueStr != nullptr)
  1622. pData->options.pathLV2 = carla_strdup_safe(valueStr);
  1623. else
  1624. pData->options.pathLV2 = nullptr;
  1625. break;
  1626. case PLUGIN_VST2:
  1627. if (pData->options.pathVST2 != nullptr)
  1628. delete[] pData->options.pathVST2;
  1629. if (valueStr != nullptr)
  1630. pData->options.pathVST2 = carla_strdup_safe(valueStr);
  1631. else
  1632. pData->options.pathVST2 = nullptr;
  1633. break;
  1634. case PLUGIN_VST3:
  1635. if (pData->options.pathVST3 != nullptr)
  1636. delete[] pData->options.pathVST3;
  1637. if (valueStr != nullptr)
  1638. pData->options.pathVST3 = carla_strdup_safe(valueStr);
  1639. else
  1640. pData->options.pathVST3 = nullptr;
  1641. break;
  1642. case PLUGIN_SF2:
  1643. if (pData->options.pathSF2 != nullptr)
  1644. delete[] pData->options.pathSF2;
  1645. if (valueStr != nullptr)
  1646. pData->options.pathSF2 = carla_strdup_safe(valueStr);
  1647. else
  1648. pData->options.pathSF2 = nullptr;
  1649. break;
  1650. case PLUGIN_SFZ:
  1651. if (pData->options.pathSFZ != nullptr)
  1652. delete[] pData->options.pathSFZ;
  1653. if (valueStr != nullptr)
  1654. pData->options.pathSFZ = carla_strdup_safe(valueStr);
  1655. else
  1656. pData->options.pathSFZ = nullptr;
  1657. break;
  1658. default:
  1659. return carla_stderr("CarlaEngine::setOption(%i:%s, %i, \"%s\") - Invalid plugin type",
  1660. option, EngineOption2Str(option), value, valueStr);
  1661. break;
  1662. }
  1663. break;
  1664. case ENGINE_OPTION_PATH_BINARIES:
  1665. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1666. if (pData->options.binaryDir != nullptr)
  1667. delete[] pData->options.binaryDir;
  1668. pData->options.binaryDir = carla_strdup_safe(valueStr);
  1669. break;
  1670. case ENGINE_OPTION_PATH_RESOURCES:
  1671. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1672. if (pData->options.resourceDir != nullptr)
  1673. delete[] pData->options.resourceDir;
  1674. pData->options.resourceDir = carla_strdup_safe(valueStr);
  1675. break;
  1676. case ENGINE_OPTION_PREVENT_BAD_BEHAVIOUR: {
  1677. CARLA_SAFE_ASSERT_RETURN(pData->options.binaryDir != nullptr && pData->options.binaryDir[0] != '\0',);
  1678. #ifdef CARLA_OS_LINUX
  1679. const ScopedEngineEnvironmentLocker _seel(this);
  1680. if (value != 0)
  1681. {
  1682. CarlaString interposerPath(CarlaString(pData->options.binaryDir) + "/libcarla_interposer-safe.so");
  1683. ::setenv("LD_PRELOAD", interposerPath.buffer(), 1);
  1684. }
  1685. else
  1686. {
  1687. ::unsetenv("LD_PRELOAD");
  1688. }
  1689. #endif
  1690. } break;
  1691. case ENGINE_OPTION_FRONTEND_BACKGROUND_COLOR:
  1692. pData->options.bgColor = static_cast<uint>(value);
  1693. break;
  1694. case ENGINE_OPTION_FRONTEND_FOREGROUND_COLOR:
  1695. pData->options.fgColor = static_cast<uint>(value);
  1696. break;
  1697. case ENGINE_OPTION_FRONTEND_UI_SCALE:
  1698. CARLA_SAFE_ASSERT_RETURN(value > 0,);
  1699. pData->options.uiScale = static_cast<float>(value) / 1000;
  1700. break;
  1701. case ENGINE_OPTION_FRONTEND_WIN_ID: {
  1702. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1703. const long long winId(std::strtoll(valueStr, nullptr, 16));
  1704. CARLA_SAFE_ASSERT_RETURN(winId >= 0,);
  1705. pData->options.frontendWinId = static_cast<uintptr_t>(winId);
  1706. } break;
  1707. #if !defined(BUILD_BRIDGE_ALTERNATIVE_ARCH) && !defined(CARLA_OS_WIN)
  1708. case ENGINE_OPTION_WINE_EXECUTABLE:
  1709. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1710. if (pData->options.wine.executable != nullptr)
  1711. delete[] pData->options.wine.executable;
  1712. pData->options.wine.executable = carla_strdup_safe(valueStr);
  1713. break;
  1714. case ENGINE_OPTION_WINE_AUTO_PREFIX:
  1715. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1716. pData->options.wine.autoPrefix = (value != 0);
  1717. break;
  1718. case ENGINE_OPTION_WINE_FALLBACK_PREFIX:
  1719. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1720. if (pData->options.wine.fallbackPrefix != nullptr)
  1721. delete[] pData->options.wine.fallbackPrefix;
  1722. pData->options.wine.fallbackPrefix = carla_strdup_safe(valueStr);
  1723. break;
  1724. case ENGINE_OPTION_WINE_RT_PRIO_ENABLED:
  1725. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1726. pData->options.wine.rtPrio = (value != 0);
  1727. break;
  1728. case ENGINE_OPTION_WINE_BASE_RT_PRIO:
  1729. CARLA_SAFE_ASSERT_RETURN(value >= 1 && value <= 89,);
  1730. pData->options.wine.baseRtPrio = value;
  1731. break;
  1732. case ENGINE_OPTION_WINE_SERVER_RT_PRIO:
  1733. CARLA_SAFE_ASSERT_RETURN(value >= 1 && value <= 99,);
  1734. pData->options.wine.serverRtPrio = value;
  1735. break;
  1736. #endif
  1737. case ENGINE_OPTION_DEBUG_CONSOLE_OUTPUT:
  1738. break;
  1739. case ENGINE_OPTION_CLIENT_NAME_PREFIX:
  1740. if (pData->options.clientNamePrefix != nullptr)
  1741. delete[] pData->options.clientNamePrefix;
  1742. pData->options.clientNamePrefix = valueStr != nullptr && valueStr[0] != '\0'
  1743. ? carla_strdup_safe(valueStr)
  1744. : nullptr;
  1745. break;
  1746. }
  1747. }
  1748. #ifndef BUILD_BRIDGE
  1749. // -----------------------------------------------------------------------
  1750. // OSC Stuff
  1751. bool CarlaEngine::isOscControlRegistered() const noexcept
  1752. {
  1753. # ifdef HAVE_LIBLO
  1754. return pData->osc.isControlRegisteredForTCP();
  1755. # else
  1756. return false;
  1757. # endif
  1758. }
  1759. const char* CarlaEngine::getOscServerPathTCP() const noexcept
  1760. {
  1761. # ifdef HAVE_LIBLO
  1762. return pData->osc.getServerPathTCP();
  1763. # else
  1764. return nullptr;
  1765. # endif
  1766. }
  1767. const char* CarlaEngine::getOscServerPathUDP() const noexcept
  1768. {
  1769. # ifdef HAVE_LIBLO
  1770. return pData->osc.getServerPathUDP();
  1771. # else
  1772. return nullptr;
  1773. # endif
  1774. }
  1775. #endif
  1776. // -----------------------------------------------------------------------
  1777. // Internal stuff
  1778. void CarlaEngine::bufferSizeChanged(const uint32_t newBufferSize)
  1779. {
  1780. carla_debug("CarlaEngine::bufferSizeChanged(%i)", newBufferSize);
  1781. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1782. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1783. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1784. {
  1785. pData->graph.setBufferSize(newBufferSize);
  1786. }
  1787. #endif
  1788. pData->time.updateAudioValues(newBufferSize, pData->sampleRate);
  1789. for (uint i=0; i < pData->curPluginCount; ++i)
  1790. {
  1791. if (const CarlaPluginPtr plugin = pData->plugins[i].plugin)
  1792. {
  1793. if (plugin->isEnabled() && plugin->tryLock(true))
  1794. {
  1795. plugin->bufferSizeChanged(newBufferSize);
  1796. plugin->unlock();
  1797. }
  1798. }
  1799. }
  1800. callback(true, true, ENGINE_CALLBACK_BUFFER_SIZE_CHANGED, 0, static_cast<int>(newBufferSize), 0, 0, 0.0f, nullptr);
  1801. }
  1802. void CarlaEngine::sampleRateChanged(const double newSampleRate)
  1803. {
  1804. carla_debug("CarlaEngine::sampleRateChanged(%g)", newSampleRate);
  1805. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1806. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1807. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1808. {
  1809. pData->graph.setSampleRate(newSampleRate);
  1810. }
  1811. #endif
  1812. pData->time.updateAudioValues(pData->bufferSize, newSampleRate);
  1813. for (uint i=0; i < pData->curPluginCount; ++i)
  1814. {
  1815. if (const CarlaPluginPtr plugin = pData->plugins[i].plugin)
  1816. {
  1817. if (plugin->isEnabled() && plugin->tryLock(true))
  1818. {
  1819. plugin->sampleRateChanged(newSampleRate);
  1820. plugin->unlock();
  1821. }
  1822. }
  1823. }
  1824. callback(true, true, ENGINE_CALLBACK_SAMPLE_RATE_CHANGED, 0, 0, 0, 0, static_cast<float>(newSampleRate), nullptr);
  1825. }
  1826. void CarlaEngine::offlineModeChanged(const bool isOfflineNow)
  1827. {
  1828. carla_debug("CarlaEngine::offlineModeChanged(%s)", bool2str(isOfflineNow));
  1829. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1830. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1831. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1832. {
  1833. pData->graph.setOffline(isOfflineNow);
  1834. }
  1835. #endif
  1836. for (uint i=0; i < pData->curPluginCount; ++i)
  1837. {
  1838. if (const CarlaPluginPtr plugin = pData->plugins[i].plugin)
  1839. if (plugin->isEnabled())
  1840. plugin->offlineModeChanged(isOfflineNow);
  1841. }
  1842. }
  1843. void CarlaEngine::setPluginPeaksRT(const uint pluginId, float const inPeaks[2], float const outPeaks[2]) noexcept
  1844. {
  1845. EnginePluginData& pluginData(pData->plugins[pluginId]);
  1846. pluginData.peaks[0] = inPeaks[0];
  1847. pluginData.peaks[1] = inPeaks[1];
  1848. pluginData.peaks[2] = outPeaks[0];
  1849. pluginData.peaks[3] = outPeaks[1];
  1850. }
  1851. void CarlaEngine::saveProjectInternal(water::MemoryOutputStream& outStream) const
  1852. {
  1853. // send initial prepareForSave first, giving time for bridges to act
  1854. for (uint i=0; i < pData->curPluginCount; ++i)
  1855. {
  1856. if (const CarlaPluginPtr plugin = pData->plugins[i].plugin)
  1857. {
  1858. if (plugin->isEnabled())
  1859. {
  1860. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1861. // deactivate bridge client-side ping check, since some plugins block during save
  1862. if (plugin->getHints() & PLUGIN_IS_BRIDGE)
  1863. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "false", false);
  1864. #endif
  1865. plugin->prepareForSave(false);
  1866. }
  1867. }
  1868. }
  1869. outStream << "<?xml version='1.0' encoding='UTF-8'?>\n";
  1870. outStream << "<!DOCTYPE CARLA-PROJECT>\n";
  1871. outStream << "<CARLA-PROJECT VERSION='2.2'";
  1872. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1873. if (pData->ignoreClientPrefix)
  1874. outStream << " IgnoreClientPrefix='true'";
  1875. #endif
  1876. outStream << ">\n";
  1877. const bool isPlugin(getType() == kEngineTypePlugin);
  1878. const EngineOptions& options(pData->options);
  1879. {
  1880. MemoryOutputStream outSettings(1024);
  1881. outSettings << " <EngineSettings>\n";
  1882. outSettings << " <ForceStereo>" << bool2str(options.forceStereo) << "</ForceStereo>\n";
  1883. outSettings << " <PreferPluginBridges>" << bool2str(options.preferPluginBridges) << "</PreferPluginBridges>\n";
  1884. outSettings << " <PreferUiBridges>" << bool2str(options.preferUiBridges) << "</PreferUiBridges>\n";
  1885. outSettings << " <UIsAlwaysOnTop>" << bool2str(options.uisAlwaysOnTop) << "</UIsAlwaysOnTop>\n";
  1886. outSettings << " <MaxParameters>" << String(options.maxParameters) << "</MaxParameters>\n";
  1887. outSettings << " <UIBridgesTimeout>" << String(options.uiBridgesTimeout) << "</UIBridgesTimeout>\n";
  1888. if (isPlugin)
  1889. {
  1890. outSettings << " <LADSPA_PATH>" << xmlSafeString(options.pathLADSPA, true) << "</LADSPA_PATH>\n";
  1891. outSettings << " <DSSI_PATH>" << xmlSafeString(options.pathDSSI, true) << "</DSSI_PATH>\n";
  1892. outSettings << " <LV2_PATH>" << xmlSafeString(options.pathLV2, true) << "</LV2_PATH>\n";
  1893. outSettings << " <VST2_PATH>" << xmlSafeString(options.pathVST2, true) << "</VST2_PATH>\n";
  1894. outSettings << " <VST3_PATH>" << xmlSafeString(options.pathVST3, true) << "</VST3_PATH>\n";
  1895. outSettings << " <SF2_PATH>" << xmlSafeString(options.pathSF2, true) << "</SF2_PATH>\n";
  1896. outSettings << " <SFZ_PATH>" << xmlSafeString(options.pathSFZ, true) << "</SFZ_PATH>\n";
  1897. }
  1898. outSettings << " </EngineSettings>\n";
  1899. outStream << outSettings;
  1900. }
  1901. if (pData->timeInfo.bbt.valid && ! isPlugin)
  1902. {
  1903. MemoryOutputStream outTransport(128);
  1904. outTransport << "\n <Transport>\n";
  1905. // outTransport << " <BeatsPerBar>" << pData->timeInfo.bbt.beatsPerBar << "</BeatsPerBar>\n";
  1906. outTransport << " <BeatsPerMinute>" << pData->timeInfo.bbt.beatsPerMinute << "</BeatsPerMinute>\n";
  1907. outTransport << " </Transport>\n";
  1908. outStream << outTransport;
  1909. }
  1910. char strBuf[STR_MAX+1];
  1911. carla_zeroChars(strBuf, STR_MAX+1);
  1912. for (uint i=0; i < pData->curPluginCount; ++i)
  1913. {
  1914. if (const CarlaPluginPtr plugin = pData->plugins[i].plugin)
  1915. {
  1916. if (plugin->isEnabled())
  1917. {
  1918. MemoryOutputStream outPlugin(4096), streamPlugin;
  1919. plugin->getStateSave(false).dumpToMemoryStream(streamPlugin);
  1920. outPlugin << "\n";
  1921. if (plugin->getRealName(strBuf))
  1922. outPlugin << " <!-- " << xmlSafeString(strBuf, true) << " -->\n";
  1923. outPlugin << " <Plugin>\n";
  1924. outPlugin << streamPlugin;
  1925. outPlugin << " </Plugin>\n";
  1926. outStream << outPlugin;
  1927. }
  1928. }
  1929. }
  1930. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1931. // tell bridges we're done saving
  1932. for (uint i=0; i < pData->curPluginCount; ++i)
  1933. {
  1934. if (const CarlaPluginPtr plugin = pData->plugins[i].plugin)
  1935. if (plugin->isEnabled() && (plugin->getHints() & PLUGIN_IS_BRIDGE) != 0)
  1936. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "true", false);
  1937. }
  1938. // save internal connections
  1939. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1940. {
  1941. uint posCount = 0;
  1942. const char* const* const patchbayConns = getPatchbayConnections(false);
  1943. const PatchbayPosition* const patchbayPos = getPatchbayPositions(false, posCount);
  1944. if (patchbayConns != nullptr || patchbayPos != nullptr)
  1945. {
  1946. MemoryOutputStream outPatchbay(2048);
  1947. outPatchbay << "\n <Patchbay>\n";
  1948. if (patchbayConns != nullptr)
  1949. {
  1950. for (int i=0; patchbayConns[i] != nullptr && patchbayConns[i+1] != nullptr; ++i, ++i)
  1951. {
  1952. const char* const connSource(patchbayConns[i]);
  1953. const char* const connTarget(patchbayConns[i+1]);
  1954. CARLA_SAFE_ASSERT_CONTINUE(connSource != nullptr && connSource[0] != '\0');
  1955. CARLA_SAFE_ASSERT_CONTINUE(connTarget != nullptr && connTarget[0] != '\0');
  1956. outPatchbay << " <Connection>\n";
  1957. outPatchbay << " <Source>" << xmlSafeString(connSource, true) << "</Source>\n";
  1958. outPatchbay << " <Target>" << xmlSafeString(connTarget, true) << "</Target>\n";
  1959. outPatchbay << " </Connection>\n";
  1960. }
  1961. }
  1962. if (patchbayPos != nullptr && posCount != 0)
  1963. {
  1964. outPatchbay << " <Positions>\n";
  1965. for (uint i=0; i<posCount; ++i)
  1966. {
  1967. const PatchbayPosition& ppos(patchbayPos[i]);
  1968. CARLA_SAFE_ASSERT_CONTINUE(ppos.name != nullptr && ppos.name[0] != '\0');
  1969. outPatchbay << " <Position x1=\"" << ppos.x1 << "\" y1=\"" << ppos.y1;
  1970. if (ppos.x2 != 0 || ppos.y2 != 0)
  1971. outPatchbay << "\" x2=\"" << ppos.x2 << "\" y2=\"" << ppos.y2;
  1972. if (ppos.pluginId >= 0)
  1973. outPatchbay << "\" pluginId=\"" << ppos.pluginId;
  1974. outPatchbay << "\">\n";
  1975. outPatchbay << " <Name>" << xmlSafeString(ppos.name, true) << "</Name>\n";
  1976. outPatchbay << " </Position>\n";
  1977. if (ppos.dealloc)
  1978. delete[] ppos.name;
  1979. }
  1980. outPatchbay << " </Positions>\n";
  1981. }
  1982. outPatchbay << " </Patchbay>\n";
  1983. outStream << outPatchbay;
  1984. delete[] patchbayPos;
  1985. }
  1986. }
  1987. // if we're running inside some session-manager (and using JACK), let them handle the connections
  1988. bool saveExternalConnections, saveExternalPositions = true;
  1989. /**/ if (isPlugin)
  1990. {
  1991. saveExternalConnections = false;
  1992. saveExternalPositions = false;
  1993. }
  1994. else if (std::strcmp(getCurrentDriverName(), "JACK") != 0)
  1995. {
  1996. saveExternalConnections = true;
  1997. }
  1998. else if (std::getenv("CARLA_DONT_MANAGE_CONNECTIONS") != nullptr)
  1999. {
  2000. saveExternalConnections = false;
  2001. }
  2002. else
  2003. {
  2004. saveExternalConnections = true;
  2005. }
  2006. if (saveExternalConnections || saveExternalPositions)
  2007. {
  2008. uint posCount = 0;
  2009. const char* const* const patchbayConns = saveExternalConnections
  2010. ? getPatchbayConnections(true)
  2011. : nullptr;
  2012. const PatchbayPosition* const patchbayPos = saveExternalPositions
  2013. ? getPatchbayPositions(true, posCount)
  2014. : nullptr;
  2015. if (patchbayConns != nullptr || patchbayPos != nullptr)
  2016. {
  2017. MemoryOutputStream outPatchbay(2048);
  2018. outPatchbay << "\n <ExternalPatchbay>\n";
  2019. if (patchbayConns != nullptr)
  2020. {
  2021. for (int i=0; patchbayConns[i] != nullptr && patchbayConns[i+1] != nullptr; ++i, ++i )
  2022. {
  2023. const char* const connSource(patchbayConns[i]);
  2024. const char* const connTarget(patchbayConns[i+1]);
  2025. CARLA_SAFE_ASSERT_CONTINUE(connSource != nullptr && connSource[0] != '\0');
  2026. CARLA_SAFE_ASSERT_CONTINUE(connTarget != nullptr && connTarget[0] != '\0');
  2027. outPatchbay << " <Connection>\n";
  2028. outPatchbay << " <Source>" << xmlSafeString(connSource, true) << "</Source>\n";
  2029. outPatchbay << " <Target>" << xmlSafeString(connTarget, true) << "</Target>\n";
  2030. outPatchbay << " </Connection>\n";
  2031. }
  2032. }
  2033. if (patchbayPos != nullptr && posCount != 0)
  2034. {
  2035. outPatchbay << " <Positions>\n";
  2036. for (uint i=0; i<posCount; ++i)
  2037. {
  2038. const PatchbayPosition& ppos(patchbayPos[i]);
  2039. CARLA_SAFE_ASSERT_CONTINUE(ppos.name != nullptr && ppos.name[0] != '\0');
  2040. outPatchbay << " <Position x1=\"" << ppos.x1 << "\" y1=\"" << ppos.y1;
  2041. if (ppos.x2 != 0 || ppos.y2 != 0)
  2042. outPatchbay << "\" x2=\"" << ppos.x2 << "\" y2=\"" << ppos.y2;
  2043. if (ppos.pluginId >= 0)
  2044. outPatchbay << "\" pluginId=\"" << ppos.pluginId;
  2045. outPatchbay << "\">\n";
  2046. outPatchbay << " <Name>" << xmlSafeString(ppos.name, true) << "</Name>\n";
  2047. outPatchbay << " </Position>\n";
  2048. if (ppos.dealloc)
  2049. delete[] ppos.name;
  2050. }
  2051. outPatchbay << " </Positions>\n";
  2052. }
  2053. outPatchbay << " </ExternalPatchbay>\n";
  2054. outStream << outPatchbay;
  2055. }
  2056. }
  2057. #endif
  2058. outStream << "</CARLA-PROJECT>\n";
  2059. }
  2060. static String findBinaryInCustomPath(const char* const searchPath, const char* const binary)
  2061. {
  2062. const StringArray searchPaths(StringArray::fromTokens(searchPath, CARLA_OS_SPLIT_STR, ""));
  2063. // try direct filename first
  2064. String jbinary(binary);
  2065. // adjust for current platform
  2066. #ifdef CARLA_OS_WIN
  2067. if (jbinary[0] == '/')
  2068. jbinary = "C:" + jbinary.replaceCharacter('/', '\\');
  2069. #else
  2070. if (jbinary[1] == ':' && (jbinary[2] == '\\' || jbinary[2] == '/'))
  2071. jbinary = jbinary.substring(2).replaceCharacter('\\', '/');
  2072. #endif
  2073. String filename = File(jbinary).getFileName();
  2074. int searchFlags = File::findFiles|File::ignoreHiddenFiles;
  2075. #ifdef CARLA_OS_MAC
  2076. if (filename.endsWithIgnoreCase(".vst") || filename.endsWithIgnoreCase(".vst3"))
  2077. searchFlags |= File::findDirectories;
  2078. #endif
  2079. Array<File> results;
  2080. for (const String *it=searchPaths.begin(), *end=searchPaths.end(); it != end; ++it)
  2081. {
  2082. const File path(*it);
  2083. results.clear();
  2084. path.findChildFiles(results, searchFlags, true, filename);
  2085. if (results.size() > 0)
  2086. return results.getFirst().getFullPathName();
  2087. }
  2088. // try changing extension
  2089. #if defined(CARLA_OS_MAC)
  2090. if (filename.endsWithIgnoreCase(".dll") || filename.endsWithIgnoreCase(".so"))
  2091. filename = File(jbinary).getFileNameWithoutExtension() + ".dylib";
  2092. #elif defined(CARLA_OS_WIN)
  2093. if (filename.endsWithIgnoreCase(".dylib") || filename.endsWithIgnoreCase(".so"))
  2094. filename = File(jbinary).getFileNameWithoutExtension() + ".dll";
  2095. #else
  2096. if (filename.endsWithIgnoreCase(".dll") || filename.endsWithIgnoreCase(".dylib"))
  2097. filename = File(jbinary).getFileNameWithoutExtension() + ".so";
  2098. #endif
  2099. else
  2100. return String();
  2101. for (const String *it=searchPaths.begin(), *end=searchPaths.end(); it != end; ++it)
  2102. {
  2103. const File path(*it);
  2104. results.clear();
  2105. path.findChildFiles(results, searchFlags, true, filename);
  2106. if (results.size() > 0)
  2107. return results.getFirst().getFullPathName();
  2108. }
  2109. return String();
  2110. }
  2111. bool CarlaEngine::loadProjectInternal(water::XmlDocument& xmlDoc, const bool alwaysLoadConnections)
  2112. {
  2113. carla_debug("CarlaEngine::loadProjectInternal(%p, %s) - START", &xmlDoc, bool2str(alwaysLoadConnections));
  2114. CarlaScopedPointer<XmlElement> xmlElement(xmlDoc.getDocumentElement(true));
  2115. CARLA_SAFE_ASSERT_RETURN_ERR(xmlElement != nullptr, "Failed to parse project file");
  2116. const String& xmlType(xmlElement->getTagName());
  2117. const bool isPreset(xmlType.equalsIgnoreCase("carla-preset"));
  2118. if (! (xmlType.equalsIgnoreCase("carla-project") || isPreset))
  2119. {
  2120. callback(true, true, ENGINE_CALLBACK_PROJECT_LOAD_FINISHED, 0, 0, 0, 0, 0.0f, nullptr);
  2121. setLastError("Not a valid Carla project or preset file");
  2122. return false;
  2123. }
  2124. pData->actionCanceled = false;
  2125. callback(true, true, ENGINE_CALLBACK_CANCELABLE_ACTION, 0, 1, 0, 0, 0.0f, "Loading project");
  2126. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2127. if (pData->options.clientNamePrefix != nullptr)
  2128. {
  2129. if (carla_isEqual(xmlElement->getDoubleAttribute("VERSION", 0.0), 2.0) ||
  2130. xmlElement->getBoolAttribute("IgnoreClientPrefix", false))
  2131. {
  2132. carla_stdout("Loading project in compatibility mode, will ignore client name prefix");
  2133. pData->ignoreClientPrefix = true;
  2134. setOption(ENGINE_OPTION_CLIENT_NAME_PREFIX, 0, "");
  2135. }
  2136. }
  2137. const CarlaScopedValueSetter<bool> csvs(pData->loadingProject, true, false);
  2138. #endif
  2139. // completely load file
  2140. xmlElement = xmlDoc.getDocumentElement(false);
  2141. CARLA_SAFE_ASSERT_RETURN_ERR(xmlElement != nullptr, "Failed to completely parse project file");
  2142. if (pData->aboutToClose)
  2143. return true;
  2144. if (pData->actionCanceled)
  2145. {
  2146. setLastError("Project load canceled");
  2147. return false;
  2148. }
  2149. callback(true, false, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  2150. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2151. const bool isMultiClient = pData->options.processMode == ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS;
  2152. const bool isPatchbay = pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY;
  2153. #endif
  2154. const bool isPlugin = getType() == kEngineTypePlugin;
  2155. // load engine settings first of all
  2156. if (XmlElement* const elem = isPreset ? nullptr : xmlElement->getChildByName("EngineSettings"))
  2157. {
  2158. for (XmlElement* settElem = elem->getFirstChildElement(); settElem != nullptr; settElem = settElem->getNextElement())
  2159. {
  2160. const String& tag(settElem->getTagName());
  2161. const String text(settElem->getAllSubText().trim());
  2162. /** some settings might be incorrect or require extra work,
  2163. so we call setOption rather than modifying them direly */
  2164. int option = -1;
  2165. int value = 0;
  2166. const char* valueStr = nullptr;
  2167. /**/ if (tag == "ForceStereo")
  2168. {
  2169. option = ENGINE_OPTION_FORCE_STEREO;
  2170. value = text == "true" ? 1 : 0;
  2171. }
  2172. else if (tag == "PreferPluginBridges")
  2173. {
  2174. option = ENGINE_OPTION_PREFER_PLUGIN_BRIDGES;
  2175. value = text == "true" ? 1 : 0;
  2176. }
  2177. else if (tag == "PreferUiBridges")
  2178. {
  2179. option = ENGINE_OPTION_PREFER_UI_BRIDGES;
  2180. value = text == "true" ? 1 : 0;
  2181. }
  2182. else if (tag == "UIsAlwaysOnTop")
  2183. {
  2184. option = ENGINE_OPTION_UIS_ALWAYS_ON_TOP;
  2185. value = text == "true" ? 1 : 0;
  2186. }
  2187. else if (tag == "MaxParameters")
  2188. {
  2189. option = ENGINE_OPTION_MAX_PARAMETERS;
  2190. value = text.getIntValue();
  2191. }
  2192. else if (tag == "UIBridgesTimeout")
  2193. {
  2194. option = ENGINE_OPTION_UI_BRIDGES_TIMEOUT;
  2195. value = text.getIntValue();
  2196. }
  2197. else if (isPlugin)
  2198. {
  2199. /**/ if (tag == "LADSPA_PATH")
  2200. {
  2201. option = ENGINE_OPTION_PLUGIN_PATH;
  2202. value = PLUGIN_LADSPA;
  2203. valueStr = text.toRawUTF8();
  2204. }
  2205. else if (tag == "DSSI_PATH")
  2206. {
  2207. option = ENGINE_OPTION_PLUGIN_PATH;
  2208. value = PLUGIN_DSSI;
  2209. valueStr = text.toRawUTF8();
  2210. }
  2211. else if (tag == "LV2_PATH")
  2212. {
  2213. option = ENGINE_OPTION_PLUGIN_PATH;
  2214. value = PLUGIN_LV2;
  2215. valueStr = text.toRawUTF8();
  2216. }
  2217. else if (tag == "VST2_PATH")
  2218. {
  2219. option = ENGINE_OPTION_PLUGIN_PATH;
  2220. value = PLUGIN_VST2;
  2221. valueStr = text.toRawUTF8();
  2222. }
  2223. else if (tag.equalsIgnoreCase("VST3_PATH"))
  2224. {
  2225. option = ENGINE_OPTION_PLUGIN_PATH;
  2226. value = PLUGIN_VST3;
  2227. valueStr = text.toRawUTF8();
  2228. }
  2229. else if (tag == "SF2_PATH")
  2230. {
  2231. option = ENGINE_OPTION_PLUGIN_PATH;
  2232. value = PLUGIN_SF2;
  2233. valueStr = text.toRawUTF8();
  2234. }
  2235. else if (tag == "SFZ_PATH")
  2236. {
  2237. option = ENGINE_OPTION_PLUGIN_PATH;
  2238. value = PLUGIN_SFZ;
  2239. valueStr = text.toRawUTF8();
  2240. }
  2241. }
  2242. if (option == -1)
  2243. {
  2244. // check old stuff, unhandled now
  2245. if (tag == "GIG_PATH")
  2246. continue;
  2247. // ignored tags
  2248. if (tag == "LADSPA_PATH" || tag == "DSSI_PATH" || tag == "LV2_PATH" || tag == "VST2_PATH")
  2249. continue;
  2250. if (tag == "VST3_PATH" || tag == "AU_PATH")
  2251. continue;
  2252. if (tag == "SF2_PATH" || tag == "SFZ_PATH")
  2253. continue;
  2254. // hmm something is wrong..
  2255. carla_stderr2("CarlaEngine::loadProjectInternal() - Unhandled option '%s'", tag.toRawUTF8());
  2256. continue;
  2257. }
  2258. setOption(static_cast<EngineOption>(option), value, valueStr);
  2259. }
  2260. if (pData->aboutToClose)
  2261. return true;
  2262. if (pData->actionCanceled)
  2263. {
  2264. setLastError("Project load canceled");
  2265. return false;
  2266. }
  2267. }
  2268. // now setup transport
  2269. if (XmlElement* const elem = (isPreset || isPlugin) ? nullptr : xmlElement->getChildByName("Transport"))
  2270. {
  2271. if (XmlElement* const bpmElem = elem->getChildByName("BeatsPerMinute"))
  2272. {
  2273. const String bpmText(bpmElem->getAllSubText().trim());
  2274. const double bpm = bpmText.getDoubleValue();
  2275. // some sane limits
  2276. if (bpm >= 20.0 && bpm < 400.0)
  2277. pData->time.setBPM(bpm);
  2278. if (pData->aboutToClose)
  2279. return true;
  2280. if (pData->actionCanceled)
  2281. {
  2282. setLastError("Project load canceled");
  2283. return false;
  2284. }
  2285. }
  2286. }
  2287. // and we handle plugins
  2288. for (XmlElement* elem = xmlElement->getFirstChildElement(); elem != nullptr; elem = elem->getNextElement())
  2289. {
  2290. const String& tagName(elem->getTagName());
  2291. if (isPreset || tagName == "Plugin")
  2292. {
  2293. CarlaStateSave stateSave;
  2294. stateSave.fillFromXmlElement(isPreset ? xmlElement.get() : elem);
  2295. if (pData->aboutToClose)
  2296. return true;
  2297. if (pData->actionCanceled)
  2298. {
  2299. setLastError("Project load canceled");
  2300. return false;
  2301. }
  2302. CARLA_SAFE_ASSERT_CONTINUE(stateSave.type != nullptr);
  2303. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2304. // compatibility code to load projects with GIG files
  2305. // FIXME Remove on 2.1 release
  2306. if (std::strcmp(stateSave.type, "GIG") == 0)
  2307. {
  2308. if (addPlugin(PLUGIN_LV2, "", stateSave.name, "http://linuxsampler.org/plugins/linuxsampler", 0, nullptr))
  2309. {
  2310. const uint pluginId = pData->curPluginCount;
  2311. if (const CarlaPluginPtr plugin = pData->plugins[pluginId].plugin)
  2312. {
  2313. if (pData->aboutToClose)
  2314. return true;
  2315. if (pData->actionCanceled)
  2316. {
  2317. setLastError("Project load canceled");
  2318. return false;
  2319. }
  2320. String lsState;
  2321. lsState << "0.35\n";
  2322. lsState << "18 0 Chromatic\n";
  2323. lsState << "18 1 Drum Kits\n";
  2324. lsState << "20 0\n";
  2325. lsState << "0 1 " << stateSave.binary << "\n";
  2326. lsState << "0 0 0 0 1 0 GIG\n";
  2327. plugin->setCustomData(LV2_ATOM__String, "http://linuxsampler.org/schema#state-string", lsState.toRawUTF8(), true);
  2328. plugin->restoreLV2State(true);
  2329. plugin->setDryWet(stateSave.dryWet, true, true);
  2330. plugin->setVolume(stateSave.volume, true, true);
  2331. plugin->setBalanceLeft(stateSave.balanceLeft, true, true);
  2332. plugin->setBalanceRight(stateSave.balanceRight, true, true);
  2333. plugin->setPanning(stateSave.panning, true, true);
  2334. plugin->setCtrlChannel(stateSave.ctrlChannel, true, true);
  2335. plugin->setActive(stateSave.active, true, true);
  2336. plugin->setEnabled(true);
  2337. ++pData->curPluginCount;
  2338. callback(true, true, ENGINE_CALLBACK_PLUGIN_ADDED, pluginId, 0, 0, 0, 0.0f, plugin->getName());
  2339. if (isPatchbay)
  2340. pData->graph.addPlugin(plugin);
  2341. }
  2342. else
  2343. {
  2344. carla_stderr2("Failed to get new plugin, state will not be restored correctly\n");
  2345. }
  2346. }
  2347. else
  2348. {
  2349. carla_stderr2("Failed to load a linuxsampler LV2 plugin, GIG file won't be loaded");
  2350. }
  2351. callback(true, true, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  2352. continue;
  2353. }
  2354. # ifdef SFZ_FILES_USING_SFIZZ
  2355. if (std::strcmp(stateSave.type, "SFZ") == 0)
  2356. {
  2357. if (addPlugin(PLUGIN_LV2, "", stateSave.name, "http://sfztools.github.io/sfizz", 0, nullptr))
  2358. {
  2359. const uint pluginId = pData->curPluginCount;
  2360. if (const CarlaPluginPtr plugin = pData->plugins[pluginId].plugin)
  2361. {
  2362. if (pData->aboutToClose)
  2363. return true;
  2364. if (pData->actionCanceled)
  2365. {
  2366. setLastError("Project load canceled");
  2367. return false;
  2368. }
  2369. plugin->setCustomData(LV2_ATOM__Path,
  2370. "http://sfztools.github.io/sfizz:sfzfile",
  2371. stateSave.binary,
  2372. false);
  2373. plugin->restoreLV2State(true);
  2374. plugin->setDryWet(stateSave.dryWet, true, true);
  2375. plugin->setVolume(stateSave.volume, true, true);
  2376. plugin->setBalanceLeft(stateSave.balanceLeft, true, true);
  2377. plugin->setBalanceRight(stateSave.balanceRight, true, true);
  2378. plugin->setPanning(stateSave.panning, true, true);
  2379. plugin->setCtrlChannel(stateSave.ctrlChannel, true, true);
  2380. plugin->setActive(stateSave.active, true, true);
  2381. plugin->setEnabled(true);
  2382. ++pData->curPluginCount;
  2383. callback(true, true, ENGINE_CALLBACK_PLUGIN_ADDED, pluginId, 0, 0, 0, 0.0f, plugin->getName());
  2384. if (isPatchbay)
  2385. pData->graph.addPlugin(plugin);
  2386. }
  2387. else
  2388. {
  2389. carla_stderr2("Failed to get new plugin, state will not be restored correctly\n");
  2390. }
  2391. }
  2392. else
  2393. {
  2394. carla_stderr2("Failed to load a sfizz LV2 plugin, SFZ file won't be loaded");
  2395. }
  2396. callback(true, true, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  2397. continue;
  2398. }
  2399. # endif
  2400. #endif
  2401. const void* extraStuff = nullptr;
  2402. static const char kTrue[] = "true";
  2403. const PluginType ptype(getPluginTypeFromString(stateSave.type));
  2404. switch (ptype)
  2405. {
  2406. case PLUGIN_SF2:
  2407. if (CarlaString(stateSave.label).endsWith(" (16 outs)"))
  2408. extraStuff = kTrue;
  2409. // fall through
  2410. case PLUGIN_LADSPA:
  2411. case PLUGIN_DSSI:
  2412. case PLUGIN_VST2:
  2413. case PLUGIN_VST3:
  2414. case PLUGIN_SFZ:
  2415. if (stateSave.binary != nullptr && stateSave.binary[0] != '\0' &&
  2416. ! (File::isAbsolutePath(stateSave.binary) && File(stateSave.binary).exists()))
  2417. {
  2418. const char* searchPath;
  2419. switch (ptype)
  2420. {
  2421. case PLUGIN_LADSPA: searchPath = pData->options.pathLADSPA; break;
  2422. case PLUGIN_DSSI: searchPath = pData->options.pathDSSI; break;
  2423. case PLUGIN_VST2: searchPath = pData->options.pathVST2; break;
  2424. case PLUGIN_VST3: searchPath = pData->options.pathVST3; break;
  2425. case PLUGIN_SF2: searchPath = pData->options.pathSF2; break;
  2426. case PLUGIN_SFZ: searchPath = pData->options.pathSFZ; break;
  2427. default: searchPath = nullptr; break;
  2428. }
  2429. if (searchPath != nullptr && searchPath[0] != '\0')
  2430. {
  2431. carla_stderr("Plugin binary '%s' doesn't exist on this filesystem, let's look for it...",
  2432. stateSave.binary);
  2433. String result = findBinaryInCustomPath(searchPath, stateSave.binary);
  2434. if (result.isEmpty())
  2435. {
  2436. switch (ptype)
  2437. {
  2438. case PLUGIN_LADSPA: searchPath = std::getenv("LADSPA_PATH"); break;
  2439. case PLUGIN_DSSI: searchPath = std::getenv("DSSI_PATH"); break;
  2440. case PLUGIN_VST2: searchPath = std::getenv("VST_PATH"); break;
  2441. case PLUGIN_VST3: searchPath = std::getenv("VST3_PATH"); break;
  2442. case PLUGIN_SF2: searchPath = std::getenv("SF2_PATH"); break;
  2443. case PLUGIN_SFZ: searchPath = std::getenv("SFZ_PATH"); break;
  2444. default: searchPath = nullptr; break;
  2445. }
  2446. if (searchPath != nullptr && searchPath[0] != '\0')
  2447. result = findBinaryInCustomPath(searchPath, stateSave.binary);
  2448. }
  2449. if (result.isNotEmpty())
  2450. {
  2451. delete[] stateSave.binary;
  2452. stateSave.binary = carla_strdup(result.toRawUTF8());
  2453. carla_stderr("Found it! :)");
  2454. }
  2455. else
  2456. {
  2457. carla_stderr("Damn, we failed... :(");
  2458. }
  2459. callback(true, true, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  2460. }
  2461. }
  2462. break;
  2463. default:
  2464. break;
  2465. }
  2466. BinaryType btype;
  2467. switch (ptype)
  2468. {
  2469. case PLUGIN_LADSPA:
  2470. case PLUGIN_DSSI:
  2471. case PLUGIN_LV2:
  2472. case PLUGIN_VST2:
  2473. case PLUGIN_VST3:
  2474. btype = getBinaryTypeFromFile(stateSave.binary);
  2475. break;
  2476. default:
  2477. btype = BINARY_NATIVE;
  2478. break;
  2479. }
  2480. if (addPlugin(btype, ptype, stateSave.binary,
  2481. stateSave.name, stateSave.label, stateSave.uniqueId, extraStuff, stateSave.options))
  2482. {
  2483. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2484. const uint pluginId = pData->curPluginCount;
  2485. #else
  2486. const uint pluginId = 0;
  2487. #endif
  2488. if (const CarlaPluginPtr plugin = pData->plugins[pluginId].plugin)
  2489. {
  2490. if (pData->aboutToClose)
  2491. return true;
  2492. if (pData->actionCanceled)
  2493. {
  2494. setLastError("Project load canceled");
  2495. return false;
  2496. }
  2497. // deactivate bridge client-side ping check, since some plugins block during load
  2498. if ((plugin->getHints() & PLUGIN_IS_BRIDGE) != 0 && ! isPreset)
  2499. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "false", false);
  2500. plugin->loadStateSave(stateSave);
  2501. /* NOTE: The following code is the same as the end of addPlugin().
  2502. * When project is loading we do not enable the plugin right away,
  2503. * as we want to load state first.
  2504. */
  2505. plugin->setEnabled(true);
  2506. ++pData->curPluginCount;
  2507. callback(true, true, ENGINE_CALLBACK_PLUGIN_ADDED, pluginId, 0, 0, 0, 0.0f, plugin->getName());
  2508. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2509. if (isPatchbay)
  2510. pData->graph.addPlugin(plugin);
  2511. #endif
  2512. }
  2513. else
  2514. {
  2515. carla_stderr2("Failed to get new plugin, state will not be restored correctly\n");
  2516. }
  2517. }
  2518. else
  2519. {
  2520. carla_stderr2("Failed to load a plugin '%s', error was:\n%s", stateSave.name, getLastError());
  2521. }
  2522. if (! isPreset)
  2523. callback(true, true, ENGINE_CALLBACK_IDLE, 0, 0, 0, 0, 0.0f, nullptr);
  2524. }
  2525. if (isPreset)
  2526. {
  2527. callback(true, true, ENGINE_CALLBACK_PROJECT_LOAD_FINISHED, 0, 0, 0, 0, 0.0f, nullptr);
  2528. callback(true, true, ENGINE_CALLBACK_CANCELABLE_ACTION, 0, 0, 0, 0, 0.0f, "Loading project");
  2529. return true;
  2530. }
  2531. }
  2532. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2533. // tell bridges we're done loading
  2534. for (uint i=0; i < pData->curPluginCount; ++i)
  2535. {
  2536. if (const CarlaPluginPtr plugin = pData->plugins[i].plugin)
  2537. if (plugin->isEnabled() && (plugin->getHints() & PLUGIN_IS_BRIDGE) != 0)
  2538. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "true", false);
  2539. }
  2540. if (pData->aboutToClose)
  2541. return true;
  2542. if (pData->actionCanceled)
  2543. {
  2544. setLastError("Project load canceled");
  2545. return false;
  2546. }
  2547. // now we handle positions
  2548. bool loadingAsExternal;
  2549. std::map<water::String, water::String> mapGroupNamesInternal, mapGroupNamesExternal;
  2550. bool hasInternalPositions = false;
  2551. if (XmlElement* const elemPatchbay = xmlElement->getChildByName("Patchbay"))
  2552. {
  2553. hasInternalPositions = true;
  2554. if (XmlElement* const elemPositions = elemPatchbay->getChildByName("Positions"))
  2555. {
  2556. String name;
  2557. PatchbayPosition ppos = { nullptr, -1, 0, 0, 0, 0, false };
  2558. for (XmlElement* patchElem = elemPositions->getFirstChildElement(); patchElem != nullptr; patchElem = patchElem->getNextElement())
  2559. {
  2560. const String& patchTag(patchElem->getTagName());
  2561. if (patchTag != "Position")
  2562. continue;
  2563. XmlElement* const patchName = patchElem->getChildByName("Name");
  2564. CARLA_SAFE_ASSERT_CONTINUE(patchName != nullptr);
  2565. const String nameText(patchName->getAllSubText().trim());
  2566. name = xmlSafeString(nameText, false);
  2567. ppos.name = name.toRawUTF8();
  2568. ppos.x1 = patchElem->getIntAttribute("x1");
  2569. ppos.y1 = patchElem->getIntAttribute("y1");
  2570. ppos.x2 = patchElem->getIntAttribute("x2");
  2571. ppos.y2 = patchElem->getIntAttribute("y2");
  2572. ppos.pluginId = patchElem->getIntAttribute("pluginId", -1);
  2573. ppos.dealloc = false;
  2574. loadingAsExternal = ppos.pluginId >= 0 && isMultiClient;
  2575. if (name.isNotEmpty() && restorePatchbayGroupPosition(loadingAsExternal, ppos))
  2576. {
  2577. if (name != ppos.name)
  2578. {
  2579. carla_stdout("Converted client name '%s' to '%s' for this session",
  2580. name.toRawUTF8(), ppos.name);
  2581. if (loadingAsExternal)
  2582. mapGroupNamesExternal[name] = ppos.name;
  2583. else
  2584. mapGroupNamesInternal[name] = ppos.name;
  2585. }
  2586. if (ppos.dealloc)
  2587. std::free(const_cast<char*>(ppos.name));
  2588. }
  2589. }
  2590. if (pData->aboutToClose)
  2591. return true;
  2592. if (pData->actionCanceled)
  2593. {
  2594. setLastError("Project load canceled");
  2595. return false;
  2596. }
  2597. }
  2598. }
  2599. if (XmlElement* const elemPatchbay = xmlElement->getChildByName("ExternalPatchbay"))
  2600. {
  2601. if (XmlElement* const elemPositions = elemPatchbay->getChildByName("Positions"))
  2602. {
  2603. String name;
  2604. PatchbayPosition ppos = { nullptr, -1, 0, 0, 0, 0, false };
  2605. for (XmlElement* patchElem = elemPositions->getFirstChildElement(); patchElem != nullptr; patchElem = patchElem->getNextElement())
  2606. {
  2607. const String& patchTag(patchElem->getTagName());
  2608. if (patchTag != "Position")
  2609. continue;
  2610. XmlElement* const patchName = patchElem->getChildByName("Name");
  2611. CARLA_SAFE_ASSERT_CONTINUE(patchName != nullptr);
  2612. const String nameText(patchName->getAllSubText().trim());
  2613. name = xmlSafeString(nameText, false);
  2614. ppos.name = name.toRawUTF8();
  2615. ppos.x1 = patchElem->getIntAttribute("x1");
  2616. ppos.y1 = patchElem->getIntAttribute("y1");
  2617. ppos.x2 = patchElem->getIntAttribute("x2");
  2618. ppos.y2 = patchElem->getIntAttribute("y2");
  2619. ppos.pluginId = patchElem->getIntAttribute("pluginId", -1);
  2620. ppos.dealloc = false;
  2621. loadingAsExternal = ppos.pluginId < 0 || hasInternalPositions || !isPatchbay;
  2622. carla_debug("loadingAsExternal: %i because %i %i %i",
  2623. loadingAsExternal, ppos.pluginId < 0, hasInternalPositions, !isPatchbay);
  2624. if (name.isNotEmpty() && restorePatchbayGroupPosition(loadingAsExternal, ppos))
  2625. {
  2626. if (name != ppos.name)
  2627. {
  2628. carla_stdout("Converted client name '%s' to '%s' for this session",
  2629. name.toRawUTF8(), ppos.name);
  2630. if (loadingAsExternal)
  2631. mapGroupNamesExternal[name] = ppos.name;
  2632. else
  2633. mapGroupNamesInternal[name] = ppos.name;
  2634. }
  2635. if (ppos.dealloc)
  2636. std::free(const_cast<char*>(ppos.name));
  2637. }
  2638. }
  2639. if (pData->aboutToClose)
  2640. return true;
  2641. if (pData->actionCanceled)
  2642. {
  2643. setLastError("Project load canceled");
  2644. return false;
  2645. }
  2646. }
  2647. }
  2648. bool hasInternalConnections = false;
  2649. // and now we handle connections (internal)
  2650. if (XmlElement* const elem = xmlElement->getChildByName("Patchbay"))
  2651. {
  2652. hasInternalConnections = true;
  2653. if (isPatchbay)
  2654. {
  2655. water::String sourcePort, targetPort;
  2656. for (XmlElement* patchElem = elem->getFirstChildElement(); patchElem != nullptr; patchElem = patchElem->getNextElement())
  2657. {
  2658. const String& patchTag(patchElem->getTagName());
  2659. if (patchTag != "Connection")
  2660. continue;
  2661. sourcePort.clear();
  2662. targetPort.clear();
  2663. for (XmlElement* connElem = patchElem->getFirstChildElement(); connElem != nullptr; connElem = connElem->getNextElement())
  2664. {
  2665. const String& tag(connElem->getTagName());
  2666. const String text(connElem->getAllSubText().trim());
  2667. /**/ if (tag == "Source")
  2668. sourcePort = xmlSafeString(text, false);
  2669. else if (tag == "Target")
  2670. targetPort = xmlSafeString(text, false);
  2671. }
  2672. if (sourcePort.isNotEmpty() && targetPort.isNotEmpty())
  2673. {
  2674. std::map<water::String, water::String>& map(mapGroupNamesInternal);
  2675. std::map<water::String, water::String>::iterator it;
  2676. if ((it = map.find(sourcePort.upToFirstOccurrenceOf(":", false, false))) != map.end())
  2677. sourcePort = it->second + sourcePort.fromFirstOccurrenceOf(":", true, false);
  2678. if ((it = map.find(targetPort.upToFirstOccurrenceOf(":", false, false))) != map.end())
  2679. targetPort = it->second + targetPort.fromFirstOccurrenceOf(":", true, false);
  2680. restorePatchbayConnection(false, sourcePort.toRawUTF8(), targetPort.toRawUTF8());
  2681. }
  2682. }
  2683. if (pData->aboutToClose)
  2684. return true;
  2685. if (pData->actionCanceled)
  2686. {
  2687. setLastError("Project load canceled");
  2688. return false;
  2689. }
  2690. }
  2691. }
  2692. // if we're running inside some session-manager (and using JACK), let them handle the external connections
  2693. bool loadExternalConnections;
  2694. if (alwaysLoadConnections)
  2695. {
  2696. loadExternalConnections = true;
  2697. }
  2698. else
  2699. {
  2700. /**/ if (std::strcmp(getCurrentDriverName(), "JACK") != 0)
  2701. loadExternalConnections = true;
  2702. else if (std::getenv("CARLA_DONT_MANAGE_CONNECTIONS") != nullptr)
  2703. loadExternalConnections = false;
  2704. else if (std::getenv("LADISH_APP_NAME") != nullptr)
  2705. loadExternalConnections = false;
  2706. else if (std::getenv("NSM_URL") != nullptr)
  2707. loadExternalConnections = false;
  2708. else
  2709. loadExternalConnections = true;
  2710. }
  2711. // plus external connections too
  2712. if (loadExternalConnections)
  2713. {
  2714. bool isExternal;
  2715. loadingAsExternal = hasInternalConnections &&
  2716. (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK || isPatchbay);
  2717. for (XmlElement* elem = xmlElement->getFirstChildElement(); elem != nullptr; elem = elem->getNextElement())
  2718. {
  2719. const String& tagName(elem->getTagName());
  2720. // check if we want to load patchbay-mode connections into an external (multi-client) graph
  2721. if (tagName == "Patchbay")
  2722. {
  2723. if (isPatchbay)
  2724. continue;
  2725. isExternal = false;
  2726. loadingAsExternal = true;
  2727. }
  2728. // or load external patchbay connections
  2729. else if (tagName == "ExternalPatchbay")
  2730. {
  2731. if (! isPatchbay)
  2732. loadingAsExternal = true;
  2733. isExternal = true;
  2734. }
  2735. else
  2736. {
  2737. continue;
  2738. }
  2739. water::String sourcePort, targetPort;
  2740. for (XmlElement* patchElem = elem->getFirstChildElement(); patchElem != nullptr; patchElem = patchElem->getNextElement())
  2741. {
  2742. const String& patchTag(patchElem->getTagName());
  2743. if (patchTag != "Connection")
  2744. continue;
  2745. sourcePort.clear();
  2746. targetPort.clear();
  2747. for (XmlElement* connElem = patchElem->getFirstChildElement(); connElem != nullptr; connElem = connElem->getNextElement())
  2748. {
  2749. const String& tag(connElem->getTagName());
  2750. const String text(connElem->getAllSubText().trim());
  2751. /**/ if (tag == "Source")
  2752. sourcePort = xmlSafeString(text, false);
  2753. else if (tag == "Target")
  2754. targetPort = xmlSafeString(text, false);
  2755. }
  2756. if (sourcePort.isNotEmpty() && targetPort.isNotEmpty())
  2757. {
  2758. std::map<water::String, water::String>& map(loadingAsExternal ? mapGroupNamesExternal
  2759. : mapGroupNamesInternal);
  2760. std::map<water::String, water::String>::iterator it;
  2761. if (isExternal && isPatchbay && !loadingAsExternal && sourcePort.startsWith("system:capture_"))
  2762. {
  2763. water::String internalPort = sourcePort.trimCharactersAtStart("system:capture_");
  2764. if (pData->graph.getNumAudioOuts() < 3)
  2765. {
  2766. /**/ if (internalPort == "1")
  2767. internalPort = "Audio Input:Left";
  2768. else if (internalPort == "2")
  2769. internalPort = "Audio Input:Right";
  2770. else if (internalPort == "3")
  2771. internalPort = "Audio Input:Sidechain";
  2772. else
  2773. continue;
  2774. }
  2775. else
  2776. {
  2777. internalPort = "Audio Input:Capture " + internalPort;
  2778. }
  2779. carla_stdout("Converted port name '%s' to '%s' for this session",
  2780. sourcePort.toRawUTF8(), internalPort.toRawUTF8());
  2781. sourcePort = internalPort;
  2782. }
  2783. else if (!isExternal && isMultiClient && sourcePort.startsWith("Audio Input:"))
  2784. {
  2785. water::String externalPort = sourcePort.trimCharactersAtStart("Audio Input:");
  2786. /**/ if (externalPort == "Left")
  2787. externalPort = "system:capture_1";
  2788. else if (externalPort == "Right")
  2789. externalPort = "system:capture_2";
  2790. else if (externalPort == "Sidechain")
  2791. externalPort = "system:capture_3";
  2792. else
  2793. externalPort = "system:capture_ " + externalPort.trimCharactersAtStart("Capture ");
  2794. carla_stdout("Converted port name '%s' to '%s' for this session",
  2795. sourcePort.toRawUTF8(), externalPort.toRawUTF8());
  2796. sourcePort = externalPort;
  2797. }
  2798. else if ((it = map.find(sourcePort.upToFirstOccurrenceOf(":", false, false))) != map.end())
  2799. {
  2800. sourcePort = it->second + sourcePort.fromFirstOccurrenceOf(":", true, false);
  2801. }
  2802. if (isExternal && isPatchbay && !loadingAsExternal && targetPort.startsWith("system:playback_"))
  2803. {
  2804. water::String internalPort = targetPort.trimCharactersAtStart("system:playback_");
  2805. if (pData->graph.getNumAudioOuts() < 3)
  2806. {
  2807. /**/ if (internalPort == "1")
  2808. internalPort = "Audio Output:Left";
  2809. else if (internalPort == "2")
  2810. internalPort = "Audio Output:Right";
  2811. else
  2812. continue;
  2813. }
  2814. else
  2815. {
  2816. internalPort = "Audio Input:Playback " + internalPort;
  2817. }
  2818. carla_stdout("Converted port name '%s' to '%s' for this session",
  2819. targetPort.toRawUTF8(), internalPort.toRawUTF8());
  2820. targetPort = internalPort;
  2821. }
  2822. else if (!isExternal && isMultiClient && targetPort.startsWith("Audio Output:"))
  2823. {
  2824. water::String externalPort = targetPort.trimCharactersAtStart("Audio Output:");
  2825. /**/ if (externalPort == "Left")
  2826. externalPort = "system:playback_1";
  2827. else if (externalPort == "Right")
  2828. externalPort = "system:playback_2";
  2829. else
  2830. externalPort = "system:playback_ " + externalPort.trimCharactersAtStart("Playback ");
  2831. carla_stdout("Converted port name '%s' to '%s' for this session",
  2832. targetPort.toRawUTF8(), externalPort.toRawUTF8());
  2833. targetPort = externalPort;
  2834. }
  2835. else if ((it = map.find(targetPort.upToFirstOccurrenceOf(":", false, false))) != map.end())
  2836. {
  2837. targetPort = it->second + targetPort.fromFirstOccurrenceOf(":", true, false);
  2838. }
  2839. restorePatchbayConnection(loadingAsExternal, sourcePort.toRawUTF8(), targetPort.toRawUTF8());
  2840. }
  2841. }
  2842. break;
  2843. }
  2844. }
  2845. #endif
  2846. if (pData->options.resetXruns)
  2847. clearXruns();
  2848. callback(true, true, ENGINE_CALLBACK_PROJECT_LOAD_FINISHED, 0, 0, 0, 0, 0.0f, nullptr);
  2849. callback(true, true, ENGINE_CALLBACK_CANCELABLE_ACTION, 0, 0, 0, 0, 0.0f, "Loading project");
  2850. carla_debug("CarlaEngine::loadProjectInternal(%p, %s) - END", &xmlDoc, bool2str(alwaysLoadConnections));
  2851. return true;
  2852. #ifdef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2853. // unused
  2854. (void)alwaysLoadConnections;
  2855. #endif
  2856. }
  2857. // -----------------------------------------------------------------------
  2858. CARLA_BACKEND_END_NAMESPACE