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.

3448 lines
117KB

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