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.

3466 lines
118KB

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