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.

3471 lines
118KB

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