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.

2622 lines
87KB

  1. /*
  2. * Carla Plugin Host
  3. * Copyright (C) 2011-2018 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 "CarlaEngineInternal.hpp"
  24. #include "CarlaPlugin.hpp"
  25. #include "CarlaBackendUtils.hpp"
  26. #include "CarlaBinaryUtils.hpp"
  27. #include "CarlaEngineUtils.hpp"
  28. #include "CarlaMathUtils.hpp"
  29. #include "CarlaPipeUtils.hpp"
  30. #include "CarlaStateUtils.hpp"
  31. #include "CarlaMIDI.h"
  32. #include "jackbridge/JackBridge.hpp"
  33. #include "water/files/File.h"
  34. #include "water/streams/MemoryOutputStream.h"
  35. #include "water/xml/XmlDocument.h"
  36. #include "water/xml/XmlElement.h"
  37. // FIXME Remove on 2.1 release
  38. #include "lv2/atom.h"
  39. using water::Array;
  40. using water::CharPointer_UTF8;
  41. using water::File;
  42. using water::MemoryOutputStream;
  43. using water::String;
  44. using water::StringArray;
  45. using water::XmlDocument;
  46. using water::XmlElement;
  47. CARLA_BACKEND_START_NAMESPACE
  48. // -----------------------------------------------------------------------
  49. // Carla Engine
  50. CarlaEngine::CarlaEngine()
  51. : pData(new ProtectedData(this))
  52. {
  53. carla_debug("CarlaEngine::CarlaEngine()");
  54. }
  55. CarlaEngine::~CarlaEngine()
  56. {
  57. carla_debug("CarlaEngine::~CarlaEngine()");
  58. delete pData;
  59. }
  60. // -----------------------------------------------------------------------
  61. // Static calls
  62. uint CarlaEngine::getDriverCount()
  63. {
  64. carla_debug("CarlaEngine::getDriverCount()");
  65. uint count = 0;
  66. if (jackbridge_is_ok())
  67. count += 1;
  68. #ifndef BUILD_BRIDGE
  69. # ifdef USING_JUCE
  70. count += getJuceApiCount();
  71. # else
  72. count += getRtAudioApiCount();
  73. # endif
  74. #endif
  75. return count;
  76. }
  77. const char* CarlaEngine::getDriverName(const uint index2)
  78. {
  79. carla_debug("CarlaEngine::getDriverName(%i)", index2);
  80. uint index = index2;
  81. if (jackbridge_is_ok() && index-- == 0)
  82. return "JACK";
  83. #ifndef BUILD_BRIDGE
  84. # ifdef USING_JUCE
  85. if (const uint count = getJuceApiCount())
  86. {
  87. if (index < count)
  88. return getJuceApiName(index);
  89. index -= count;
  90. }
  91. # else
  92. if (const uint count = getRtAudioApiCount())
  93. {
  94. if (index < count)
  95. return getRtAudioApiName(index);
  96. }
  97. # endif
  98. #endif
  99. carla_stderr("CarlaEngine::getDriverName(%i) - invalid index", index2);
  100. return nullptr;
  101. }
  102. const char* const* CarlaEngine::getDriverDeviceNames(const uint index2)
  103. {
  104. carla_debug("CarlaEngine::getDriverDeviceNames(%i)", index2);
  105. uint index = index2;
  106. if (jackbridge_is_ok() && index-- == 0)
  107. {
  108. static const char* ret[3] = { "Auto-Connect ON", "Auto-Connect OFF", nullptr };
  109. return ret;
  110. }
  111. #ifndef BUILD_BRIDGE
  112. # ifdef USING_JUCE
  113. if (const uint count = getJuceApiCount())
  114. {
  115. if (index < count)
  116. return getJuceApiDeviceNames(index);
  117. index -= count;
  118. }
  119. # else
  120. if (const uint count = getRtAudioApiCount())
  121. {
  122. if (index < count)
  123. return getRtAudioApiDeviceNames(index);
  124. }
  125. # endif
  126. #endif
  127. carla_stderr("CarlaEngine::getDriverDeviceNames(%i) - invalid index", index2);
  128. return nullptr;
  129. }
  130. const EngineDriverDeviceInfo* CarlaEngine::getDriverDeviceInfo(const uint index2, const char* const deviceName)
  131. {
  132. carla_debug("CarlaEngine::getDriverDeviceInfo(%i, \"%s\")", index2, deviceName);
  133. uint index = index2;
  134. if (jackbridge_is_ok() && index-- == 0)
  135. {
  136. static EngineDriverDeviceInfo devInfo;
  137. devInfo.hints = ENGINE_DRIVER_DEVICE_VARIABLE_BUFFER_SIZE;
  138. devInfo.bufferSizes = nullptr;
  139. devInfo.sampleRates = nullptr;
  140. return &devInfo;
  141. }
  142. #ifndef BUILD_BRIDGE
  143. # ifdef USING_JUCE
  144. if (const uint count = getJuceApiCount())
  145. {
  146. if (index < count)
  147. return getJuceDeviceInfo(index, deviceName);
  148. index -= count;
  149. }
  150. # else
  151. if (const uint count = getRtAudioApiCount())
  152. {
  153. if (index < count)
  154. return getRtAudioDeviceInfo(index, deviceName);
  155. }
  156. # endif
  157. #endif
  158. carla_stderr("CarlaEngine::getDriverDeviceNames(%i, \"%s\") - invalid index", index2, deviceName);
  159. return nullptr;
  160. }
  161. CarlaEngine* CarlaEngine::newDriverByName(const char* const driverName)
  162. {
  163. CARLA_SAFE_ASSERT_RETURN(driverName != nullptr && driverName[0] != '\0', nullptr);
  164. carla_debug("CarlaEngine::newDriverByName(\"%s\")", driverName);
  165. if (std::strcmp(driverName, "JACK") == 0)
  166. return newJack();
  167. #ifndef BUILD_BRIDGE
  168. # ifdef USING_JUCE
  169. // -------------------------------------------------------------------
  170. // linux
  171. if (std::strcmp(driverName, "ALSA") == 0)
  172. return newJuce(AUDIO_API_ALSA);
  173. // -------------------------------------------------------------------
  174. // macos
  175. if (std::strcmp(driverName, "CoreAudio") == 0)
  176. return newJuce(AUDIO_API_COREAUDIO);
  177. // -------------------------------------------------------------------
  178. // windows
  179. if (std::strcmp(driverName, "ASIO") == 0)
  180. return newJuce(AUDIO_API_ASIO);
  181. if (std::strcmp(driverName, "DirectSound") == 0)
  182. return newJuce(AUDIO_API_DIRECTSOUND);
  183. # else
  184. // -------------------------------------------------------------------
  185. // common
  186. if (std::strcmp(driverName, "Dummy") == 0)
  187. return newRtAudio(AUDIO_API_NULL);
  188. if (std::strncmp(driverName, "JACK ", 5) == 0)
  189. return newRtAudio(AUDIO_API_JACK);
  190. if (std::strcmp(driverName, "OSS") == 0)
  191. return newRtAudio(AUDIO_API_OSS);
  192. // -------------------------------------------------------------------
  193. // linux
  194. if (std::strcmp(driverName, "ALSA") == 0)
  195. return newRtAudio(AUDIO_API_ALSA);
  196. if (std::strcmp(driverName, "PulseAudio") == 0)
  197. return newRtAudio(AUDIO_API_PULSEAUDIO);
  198. // -------------------------------------------------------------------
  199. // macos
  200. if (std::strcmp(driverName, "CoreAudio") == 0)
  201. return newRtAudio(AUDIO_API_COREAUDIO);
  202. // -------------------------------------------------------------------
  203. // windows
  204. if (std::strcmp(driverName, "ASIO") == 0)
  205. return newRtAudio(AUDIO_API_ASIO);
  206. if (std::strcmp(driverName, "DirectSound") == 0)
  207. return newRtAudio(AUDIO_API_DIRECTSOUND);
  208. if (std::strcmp(driverName, "WASAPI") == 0)
  209. return newRtAudio(AUDIO_API_WASAPI);
  210. # endif
  211. #endif
  212. carla_stderr("CarlaEngine::newDriverByName(\"%s\") - invalid driver name", driverName);
  213. return nullptr;
  214. }
  215. // -----------------------------------------------------------------------
  216. // Constant values
  217. uint CarlaEngine::getMaxClientNameSize() const noexcept
  218. {
  219. return STR_MAX/2;
  220. }
  221. uint CarlaEngine::getMaxPortNameSize() const noexcept
  222. {
  223. return STR_MAX;
  224. }
  225. uint CarlaEngine::getCurrentPluginCount() const noexcept
  226. {
  227. return pData->curPluginCount;
  228. }
  229. uint CarlaEngine::getMaxPluginNumber() const noexcept
  230. {
  231. return pData->maxPluginNumber;
  232. }
  233. // -----------------------------------------------------------------------
  234. // Virtual, per-engine type calls
  235. bool CarlaEngine::close()
  236. {
  237. carla_debug("CarlaEngine::close()");
  238. if (pData->curPluginCount != 0)
  239. {
  240. pData->aboutToClose = true;
  241. removeAllPlugins();
  242. }
  243. #if defined(HAVE_LIBLO) && ! defined(BUILD_BRIDGE)
  244. if (pData->osc.isControlRegistered())
  245. oscSend_control_exit();
  246. #endif
  247. pData->close();
  248. callback(ENGINE_CALLBACK_ENGINE_STOPPED, 0, 0, 0, 0.0f, nullptr);
  249. return true;
  250. }
  251. bool CarlaEngine::usesConstantBufferSize() const noexcept
  252. {
  253. return true;
  254. }
  255. void CarlaEngine::idle() noexcept
  256. {
  257. CARLA_SAFE_ASSERT_RETURN(pData->nextAction.opcode == kEnginePostActionNull,);
  258. CARLA_SAFE_ASSERT_RETURN(pData->nextPluginId == pData->maxPluginNumber,);
  259. CARLA_SAFE_ASSERT_RETURN(getType() != kEngineTypePlugin,);
  260. for (uint i=0; i < pData->curPluginCount; ++i)
  261. {
  262. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  263. if (plugin != nullptr && plugin->isEnabled())
  264. {
  265. const uint hints(plugin->getHints());
  266. if ((hints & PLUGIN_HAS_CUSTOM_UI) != 0 && (hints & PLUGIN_NEEDS_UI_MAIN_THREAD) != 0)
  267. {
  268. try {
  269. plugin->uiIdle();
  270. } CARLA_SAFE_EXCEPTION_CONTINUE("Plugin uiIdle");
  271. }
  272. }
  273. }
  274. #if defined(HAVE_LIBLO) && !defined(BUILD_BRIDGE)
  275. pData->osc.idle();
  276. #endif
  277. }
  278. CarlaEngineClient* CarlaEngine::addClient(CarlaPlugin* const)
  279. {
  280. return new CarlaEngineClient(*this);
  281. }
  282. // -----------------------------------------------------------------------
  283. // Plugin management
  284. bool CarlaEngine::addPlugin(const BinaryType btype, const PluginType ptype,
  285. const char* const filename, const char* const name, const char* const label, const int64_t uniqueId,
  286. const void* const extra, const uint options)
  287. {
  288. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  289. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  290. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  291. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextPluginId <= pData->maxPluginNumber, "Invalid engine internal data");
  292. #endif
  293. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  294. CARLA_SAFE_ASSERT_RETURN_ERR(btype != BINARY_NONE, "Invalid plugin binary mode");
  295. CARLA_SAFE_ASSERT_RETURN_ERR(ptype != PLUGIN_NONE, "Invalid plugin type");
  296. CARLA_SAFE_ASSERT_RETURN_ERR((filename != nullptr && filename[0] != '\0') || (label != nullptr && label[0] != '\0'), "Invalid plugin filename and label");
  297. carla_debug("CarlaEngine::addPlugin(%i:%s, %i:%s, \"%s\", \"%s\", \"%s\", " P_INT64 ", %p, %u)", btype, BinaryType2Str(btype), ptype, PluginType2Str(ptype), filename, name, label, uniqueId, extra, options);
  298. #ifndef CARLA_OS_WIN
  299. if (ptype != PLUGIN_JACK && filename != nullptr && filename[0] != '\0') {
  300. CARLA_SAFE_ASSERT_RETURN_ERR(filename[0] == CARLA_OS_SEP || filename[0] == '.' || filename[0] == '~', "Invalid plugin filename");
  301. }
  302. #endif
  303. uint id;
  304. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  305. CarlaPlugin* oldPlugin = nullptr;
  306. if (pData->nextPluginId < pData->curPluginCount)
  307. {
  308. id = pData->nextPluginId;
  309. pData->nextPluginId = pData->maxPluginNumber;
  310. oldPlugin = pData->plugins[id].plugin;
  311. CARLA_SAFE_ASSERT_RETURN_ERR(oldPlugin != nullptr, "Invalid replace plugin Id");
  312. }
  313. else
  314. #endif
  315. {
  316. id = pData->curPluginCount;
  317. if (id == pData->maxPluginNumber)
  318. {
  319. setLastError("Maximum number of plugins reached");
  320. return false;
  321. }
  322. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  323. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins[id].plugin == nullptr, "Invalid engine internal data");
  324. #endif
  325. }
  326. CarlaPlugin::Initializer initializer = {
  327. this,
  328. id,
  329. filename,
  330. name,
  331. label,
  332. uniqueId,
  333. options
  334. };
  335. CarlaPlugin* plugin = nullptr;
  336. CarlaString bridgeBinary(pData->options.binaryDir);
  337. if (bridgeBinary.isNotEmpty())
  338. {
  339. #ifndef CARLA_OS_WIN
  340. if (btype == BINARY_NATIVE)
  341. {
  342. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-native";
  343. }
  344. else
  345. #endif
  346. {
  347. switch (btype)
  348. {
  349. case BINARY_POSIX32:
  350. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-posix32";
  351. break;
  352. case BINARY_POSIX64:
  353. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-posix64";
  354. break;
  355. case BINARY_WIN32:
  356. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-win32.exe";
  357. break;
  358. case BINARY_WIN64:
  359. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-win64.exe";
  360. break;
  361. default:
  362. bridgeBinary.clear();
  363. break;
  364. }
  365. }
  366. if (! File(bridgeBinary.buffer()).existsAsFile())
  367. bridgeBinary.clear();
  368. }
  369. // Prefer bridges for some specific plugins
  370. const bool preferBridges = pData->options.preferPluginBridges;
  371. #if 0 // ndef BUILD_BRIDGE
  372. if (! preferBridges)
  373. {
  374. if (ptype == PLUGIN_LV2 && label != nullptr)
  375. {
  376. if (std::strncmp(label, "http://calf.sourceforge.net/plugins/", 36) == 0 ||
  377. std::strcmp(label, "http://factorial.hu/plugins/lv2/ir") == 0 ||
  378. std::strstr(label, "v1.sourceforge.net/lv2") != nullptr)
  379. {
  380. preferBridges = true;
  381. }
  382. }
  383. }
  384. #endif // ! BUILD_BRIDGE
  385. const bool canBeBridged = ptype != PLUGIN_INTERNAL
  386. && ptype != PLUGIN_SF2
  387. && ptype != PLUGIN_SFZ
  388. && ptype != PLUGIN_JACK;
  389. if (canBeBridged && (btype != BINARY_NATIVE || (preferBridges && bridgeBinary.isNotEmpty())))
  390. {
  391. if (bridgeBinary.isNotEmpty())
  392. {
  393. plugin = CarlaPlugin::newBridge(initializer, btype, ptype, bridgeBinary);
  394. }
  395. else
  396. {
  397. setLastError("This Carla build cannot handle this binary");
  398. return false;
  399. }
  400. }
  401. else
  402. {
  403. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  404. bool use16Outs;
  405. #endif
  406. setLastError("Invalid or unsupported plugin type");
  407. switch (ptype)
  408. {
  409. case PLUGIN_NONE:
  410. break;
  411. case PLUGIN_LADSPA:
  412. plugin = CarlaPlugin::newLADSPA(initializer, (const LADSPA_RDF_Descriptor*)extra);
  413. break;
  414. case PLUGIN_DSSI:
  415. plugin = CarlaPlugin::newDSSI(initializer);
  416. break;
  417. case PLUGIN_LV2:
  418. plugin = CarlaPlugin::newLV2(initializer);
  419. break;
  420. case PLUGIN_VST2:
  421. plugin = CarlaPlugin::newVST2(initializer);
  422. break;
  423. case PLUGIN_VST3:
  424. plugin = CarlaPlugin::newVST3(initializer);
  425. break;
  426. case PLUGIN_AU:
  427. plugin = CarlaPlugin::newAU(initializer);
  428. break;
  429. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  430. case PLUGIN_INTERNAL:
  431. plugin = CarlaPlugin::newNative(initializer);
  432. break;
  433. case PLUGIN_SF2:
  434. use16Outs = (extra != nullptr && std::strcmp((const char*)extra, "true") == 0);
  435. plugin = CarlaPlugin::newFluidSynth(initializer, use16Outs);
  436. break;
  437. case PLUGIN_SFZ:
  438. plugin = CarlaPlugin::newSFZero(initializer);
  439. break;
  440. case PLUGIN_JACK:
  441. plugin = CarlaPlugin::newJackApp(initializer);
  442. break;
  443. #else
  444. case PLUGIN_INTERNAL:
  445. case PLUGIN_SF2:
  446. case PLUGIN_SFZ:
  447. case PLUGIN_JACK:
  448. setLastError("Plugin bridges cannot handle this binary");
  449. break;
  450. #endif
  451. }
  452. }
  453. if (plugin == nullptr)
  454. return false;
  455. plugin->reload();
  456. bool canRun = true;
  457. /**/ if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  458. {
  459. if (plugin->getCVInCount() > 0 || plugin->getCVInCount() > 0)
  460. {
  461. setLastError("Carla's rack mode cannot work with plugins that have CV ports, sorry!");
  462. canRun = false;
  463. }
  464. }
  465. else if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  466. {
  467. /**/ if (plugin->getMidiInCount() > 1 || plugin->getMidiOutCount() > 1)
  468. {
  469. setLastError("Carla's patchbay mode cannot work with plugins that have multiple MIDI ports, sorry!");
  470. canRun = false;
  471. }
  472. else if (plugin->getCVInCount() > 0 || plugin->getCVInCount() > 0)
  473. {
  474. setLastError("CV ports in patchbay mode is still TODO");
  475. canRun = false;
  476. }
  477. }
  478. if (! canRun)
  479. {
  480. delete plugin;
  481. return false;
  482. }
  483. EnginePluginData& pluginData(pData->plugins[id]);
  484. pluginData.plugin = plugin;
  485. carla_zeroFloats(pluginData.peaks, 4);
  486. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  487. if (oldPlugin != nullptr)
  488. {
  489. CARLA_SAFE_ASSERT(! pData->loadingProject);
  490. const ScopedThreadStopper sts(this);
  491. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  492. pData->graph.replacePlugin(oldPlugin, plugin);
  493. const bool wasActive = oldPlugin->getInternalParameterValue(PARAMETER_ACTIVE) >= 0.5f;
  494. const float oldDryWet = oldPlugin->getInternalParameterValue(PARAMETER_DRYWET);
  495. const float oldVolume = oldPlugin->getInternalParameterValue(PARAMETER_VOLUME);
  496. delete oldPlugin;
  497. if (plugin->getHints() & PLUGIN_CAN_DRYWET)
  498. plugin->setDryWet(oldDryWet, true, true);
  499. if (plugin->getHints() & PLUGIN_CAN_VOLUME)
  500. plugin->setVolume(oldVolume, true, true);
  501. plugin->setActive(wasActive, true, true);
  502. plugin->setEnabled(true);
  503. callback(ENGINE_CALLBACK_RELOAD_ALL, id, 0, 0, 0.0f, nullptr);
  504. }
  505. else if (! pData->loadingProject)
  506. #endif
  507. {
  508. plugin->setEnabled(true);
  509. ++pData->curPluginCount;
  510. callback(ENGINE_CALLBACK_PLUGIN_ADDED, id, 0, 0, 0.0f, plugin->getName());
  511. if (getType() != kEngineTypeBridge)
  512. plugin->setActive(true, false, true);
  513. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  514. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  515. pData->graph.addPlugin(plugin);
  516. #endif
  517. }
  518. #if defined(HAVE_LIBLO) && ! defined(BUILD_BRIDGE)
  519. plugin->registerToOscClient();
  520. #endif
  521. return true;
  522. }
  523. bool CarlaEngine::addPlugin(const PluginType ptype, const char* const filename, const char* const name, const char* const label, const int64_t uniqueId, const void* const extra)
  524. {
  525. return addPlugin(BINARY_NATIVE, ptype, filename, name, label, uniqueId, extra, 0x0);
  526. }
  527. bool CarlaEngine::removePlugin(const uint id)
  528. {
  529. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  530. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  531. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  532. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount != 0, "Invalid engine internal data");
  533. #endif
  534. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  535. CARLA_SAFE_ASSERT_RETURN_ERR(id < pData->curPluginCount, "Invalid plugin Id");
  536. carla_debug("CarlaEngine::removePlugin(%i)", id);
  537. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  538. CARLA_SAFE_ASSERT_RETURN_ERR(plugin != nullptr, "Could not find plugin to remove");
  539. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  540. const ScopedThreadStopper sts(this);
  541. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  542. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  543. pData->graph.removePlugin(plugin);
  544. const ScopedActionLock sal(this, kEnginePostActionRemovePlugin, id, 0);
  545. /*
  546. for (uint i=id; i < pData->curPluginCount; ++i)
  547. {
  548. CarlaPlugin* const plugin2(pData->plugins[i].plugin);
  549. CARLA_SAFE_ASSERT_BREAK(plugin2 != nullptr);
  550. plugin2->updateOscURL();
  551. }
  552. */
  553. # if defined(HAVE_LIBLO) && !defined(BUILD_BRIDGE)
  554. if (isOscControlRegistered())
  555. oscSend_control_remove_plugin(id);
  556. # endif
  557. #else
  558. pData->curPluginCount = 0;
  559. carla_zeroStructs(pData->plugins, 1);
  560. #endif
  561. delete plugin;
  562. callback(ENGINE_CALLBACK_PLUGIN_REMOVED, id, 0, 0, 0.0f, nullptr);
  563. return true;
  564. }
  565. bool CarlaEngine::removeAllPlugins()
  566. {
  567. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  568. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  569. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  570. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextPluginId == pData->maxPluginNumber, "Invalid engine internal data");
  571. #endif
  572. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  573. carla_debug("CarlaEngine::removeAllPlugins()");
  574. if (pData->curPluginCount == 0)
  575. return true;
  576. const ScopedThreadStopper sts(this);
  577. const uint curPluginCount(pData->curPluginCount);
  578. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  579. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  580. pData->graph.removeAllPlugins();
  581. # if defined(HAVE_LIBLO) && !defined(BUILD_BRIDGE)
  582. if (isOscControlRegistered())
  583. {
  584. for (uint i=0; i < curPluginCount; ++i)
  585. oscSend_control_remove_plugin(curPluginCount-i-1);
  586. }
  587. # endif
  588. #endif
  589. const ScopedActionLock sal(this, kEnginePostActionZeroCount, 0, 0);
  590. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  591. for (uint i=0; i < curPluginCount; ++i)
  592. {
  593. EnginePluginData& pluginData(pData->plugins[i]);
  594. if (pluginData.plugin != nullptr)
  595. {
  596. delete pluginData.plugin;
  597. pluginData.plugin = nullptr;
  598. }
  599. carla_zeroFloats(pluginData.peaks, 4);
  600. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  601. }
  602. return true;
  603. }
  604. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  605. const char* CarlaEngine::renamePlugin(const uint id, const char* const newName)
  606. {
  607. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  608. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->plugins != nullptr, "Invalid engine internal data");
  609. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->curPluginCount != 0, "Invalid engine internal data");
  610. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  611. CARLA_SAFE_ASSERT_RETURN_ERRN(id < pData->curPluginCount, "Invalid plugin Id");
  612. CARLA_SAFE_ASSERT_RETURN_ERRN(newName != nullptr && newName[0] != '\0', "Invalid plugin name");
  613. carla_debug("CarlaEngine::renamePlugin(%i, \"%s\")", id, newName);
  614. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  615. CARLA_SAFE_ASSERT_RETURN_ERRN(plugin != nullptr, "Could not find plugin to rename");
  616. CARLA_SAFE_ASSERT_RETURN_ERRN(plugin->getId() == id, "Invalid engine internal data");
  617. const char* const uniqueName(getUniquePluginName(newName));
  618. CARLA_SAFE_ASSERT_RETURN_ERRN(uniqueName != nullptr, "Unable to get new unique plugin name");
  619. plugin->setName(uniqueName);
  620. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  621. pData->graph.renamePlugin(plugin, uniqueName);
  622. delete[] uniqueName;
  623. return plugin->getName();
  624. }
  625. bool CarlaEngine::clonePlugin(const uint id)
  626. {
  627. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  628. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  629. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount != 0, "Invalid engine internal data");
  630. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  631. CARLA_SAFE_ASSERT_RETURN_ERR(id < pData->curPluginCount, "Invalid plugin Id");
  632. carla_debug("CarlaEngine::clonePlugin(%i)", id);
  633. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  634. CARLA_SAFE_ASSERT_RETURN_ERR(plugin != nullptr, "Could not find plugin to clone");
  635. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  636. char label[STR_MAX+1];
  637. carla_zeroChars(label, STR_MAX+1);
  638. plugin->getLabel(label);
  639. const uint pluginCountBefore(pData->curPluginCount);
  640. if (! addPlugin(plugin->getBinaryType(), plugin->getType(),
  641. plugin->getFilename(), plugin->getName(), label, plugin->getUniqueId(),
  642. plugin->getExtraStuff(), plugin->getOptionsEnabled()))
  643. return false;
  644. CARLA_SAFE_ASSERT_RETURN_ERR(pluginCountBefore+1 == pData->curPluginCount, "No new plugin found");
  645. if (CarlaPlugin* const newPlugin = pData->plugins[pluginCountBefore].plugin)
  646. newPlugin->loadStateSave(plugin->getStateSave());
  647. return true;
  648. }
  649. bool CarlaEngine::replacePlugin(const uint id) noexcept
  650. {
  651. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  652. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  653. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount != 0, "Invalid engine internal data");
  654. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  655. carla_debug("CarlaEngine::replacePlugin(%i)", id);
  656. // might use this to reset
  657. if (id == pData->maxPluginNumber)
  658. {
  659. pData->nextPluginId = pData->maxPluginNumber;
  660. return true;
  661. }
  662. CARLA_SAFE_ASSERT_RETURN_ERR(id < pData->curPluginCount, "Invalid plugin Id");
  663. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  664. CARLA_SAFE_ASSERT_RETURN_ERR(plugin != nullptr, "Could not find plugin to replace");
  665. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  666. pData->nextPluginId = id;
  667. return true;
  668. }
  669. bool CarlaEngine::switchPlugins(const uint idA, const uint idB) noexcept
  670. {
  671. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  672. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  673. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount >= 2, "Invalid engine internal data");
  674. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  675. CARLA_SAFE_ASSERT_RETURN_ERR(idA != idB, "Invalid operation, cannot switch plugin with itself");
  676. CARLA_SAFE_ASSERT_RETURN_ERR(idA < pData->curPluginCount, "Invalid plugin Id");
  677. CARLA_SAFE_ASSERT_RETURN_ERR(idB < pData->curPluginCount, "Invalid plugin Id");
  678. carla_debug("CarlaEngine::switchPlugins(%i)", idA, idB);
  679. CarlaPlugin* const pluginA(pData->plugins[idA].plugin);
  680. CarlaPlugin* const pluginB(pData->plugins[idB].plugin);
  681. CARLA_SAFE_ASSERT_RETURN_ERR(pluginA != nullptr, "Could not find plugin to switch");
  682. CARLA_SAFE_ASSERT_RETURN_ERR(pluginA != nullptr, "Could not find plugin to switch");
  683. CARLA_SAFE_ASSERT_RETURN_ERR(pluginA->getId() == idA, "Invalid engine internal data");
  684. CARLA_SAFE_ASSERT_RETURN_ERR(pluginB->getId() == idB, "Invalid engine internal data");
  685. const ScopedThreadStopper sts(this);
  686. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  687. pData->graph.replacePlugin(pluginA, pluginB);
  688. const ScopedActionLock sal(this, kEnginePostActionSwitchPlugins, idA, idB);
  689. // TODO
  690. /*
  691. pluginA->updateOscURL();
  692. pluginB->updateOscURL();
  693. if (isOscControlRegistered())
  694. oscSend_control_switch_plugins(idA, idB);
  695. */
  696. return true;
  697. }
  698. #endif
  699. CarlaPlugin* CarlaEngine::getPlugin(const uint id) const noexcept
  700. {
  701. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  702. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->plugins != nullptr, "Invalid engine internal data");
  703. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->curPluginCount != 0, "Invalid engine internal data");
  704. #endif
  705. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  706. CARLA_SAFE_ASSERT_RETURN_ERRN(id < pData->curPluginCount, "Invalid plugin Id");
  707. return pData->plugins[id].plugin;
  708. }
  709. CarlaPlugin* CarlaEngine::getPluginUnchecked(const uint id) const noexcept
  710. {
  711. return pData->plugins[id].plugin;
  712. }
  713. const char* CarlaEngine::getUniquePluginName(const char* const name) const
  714. {
  715. CARLA_SAFE_ASSERT_RETURN(pData->nextAction.opcode == kEnginePostActionNull, nullptr);
  716. CARLA_SAFE_ASSERT_RETURN(name != nullptr && name[0] != '\0', nullptr);
  717. carla_debug("CarlaEngine::getUniquePluginName(\"%s\")", name);
  718. CarlaString sname;
  719. sname = name;
  720. if (sname.isEmpty())
  721. {
  722. sname = "(No name)";
  723. return sname.dup();
  724. }
  725. const std::size_t maxNameSize(carla_minConstrained<uint>(getMaxClientNameSize(), 0xff, 6U) - 6); // 6 = strlen(" (10)") + 1
  726. if (maxNameSize == 0 || ! isRunning())
  727. return sname.dup();
  728. sname.truncate(maxNameSize);
  729. sname.replace(':', '.'); // ':' is used in JACK1 to split client/port names
  730. for (uint i=0; i < pData->curPluginCount; ++i)
  731. {
  732. CARLA_SAFE_ASSERT_BREAK(pData->plugins[i].plugin != nullptr);
  733. // Check if unique name doesn't exist
  734. if (const char* const pluginName = pData->plugins[i].plugin->getName())
  735. {
  736. if (sname != pluginName)
  737. continue;
  738. }
  739. // Check if string has already been modified
  740. {
  741. const std::size_t len(sname.length());
  742. // 1 digit, ex: " (2)"
  743. if (sname[len-4] == ' ' && sname[len-3] == '(' && sname.isDigit(len-2) && sname[len-1] == ')')
  744. {
  745. const int number = sname[len-2] - '0';
  746. if (number == 9)
  747. {
  748. // next number is 10, 2 digits
  749. sname.truncate(len-4);
  750. sname += " (10)";
  751. //sname.replace(" (9)", " (10)");
  752. }
  753. else
  754. sname[len-2] = char('0' + number + 1);
  755. continue;
  756. }
  757. // 2 digits, ex: " (11)"
  758. if (sname[len-5] == ' ' && sname[len-4] == '(' && sname.isDigit(len-3) && sname.isDigit(len-2) && sname[len-1] == ')')
  759. {
  760. char n2 = sname[len-2];
  761. char n3 = sname[len-3];
  762. if (n2 == '9')
  763. {
  764. n2 = '0';
  765. n3 = static_cast<char>(n3 + 1);
  766. }
  767. else
  768. n2 = static_cast<char>(n2 + 1);
  769. sname[len-2] = n2;
  770. sname[len-3] = n3;
  771. continue;
  772. }
  773. }
  774. // Modify string if not
  775. sname += " (2)";
  776. }
  777. return sname.dup();
  778. }
  779. // -----------------------------------------------------------------------
  780. // Project management
  781. bool CarlaEngine::loadFile(const char* const filename)
  782. {
  783. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  784. CARLA_SAFE_ASSERT_RETURN_ERR(filename != nullptr && filename[0] != '\0', "Invalid filename");
  785. carla_debug("CarlaEngine::loadFile(\"%s\")", filename);
  786. const String jfilename = String(CharPointer_UTF8(filename));
  787. File file(jfilename);
  788. CARLA_SAFE_ASSERT_RETURN_ERR(file.exists(), "Requested file does not exist or is not a readable");
  789. CarlaString baseName(file.getFileNameWithoutExtension().toRawUTF8());
  790. CarlaString extension(file.getFileExtension().replace(".","").toLowerCase().toRawUTF8());
  791. const uint curPluginId(pData->nextPluginId < pData->curPluginCount ? pData->nextPluginId : pData->curPluginCount);
  792. // -------------------------------------------------------------------
  793. // NOTE: please keep in sync with carla_get_supported_file_extensions!!
  794. if (extension == "carxp" || extension == "carxs")
  795. return loadProject(filename);
  796. // -------------------------------------------------------------------
  797. if (extension == "sf2" || extension == "sf3")
  798. return addPlugin(PLUGIN_SF2, filename, baseName, baseName, 0, nullptr);
  799. if (extension == "sfz")
  800. return addPlugin(PLUGIN_SFZ, filename, baseName, baseName, 0, nullptr);
  801. // -------------------------------------------------------------------
  802. if (
  803. #ifdef HAVE_SNDFILE
  804. extension == "aif" ||
  805. extension == "aifc" ||
  806. extension == "aiff" ||
  807. extension == "au" ||
  808. extension == "bwf" ||
  809. extension == "flac" ||
  810. extension == "htk" ||
  811. extension == "iff" ||
  812. extension == "mat4" ||
  813. extension == "mat5" ||
  814. extension == "oga" ||
  815. extension == "ogg" ||
  816. extension == "paf" ||
  817. extension == "pvf" ||
  818. extension == "pvf5" ||
  819. extension == "sd2" ||
  820. extension == "sf" ||
  821. extension == "snd" ||
  822. extension == "svx" ||
  823. extension == "vcc" ||
  824. extension == "w64" ||
  825. extension == "wav" ||
  826. extension == "xi" ||
  827. #endif
  828. #ifdef HAVE_FFMPEG
  829. extension == "3g2" ||
  830. extension == "3gp" ||
  831. extension == "aac" ||
  832. extension == "ac3" ||
  833. extension == "amr" ||
  834. extension == "ape" ||
  835. extension == "mp2" ||
  836. extension == "mp3" ||
  837. extension == "mpc" ||
  838. extension == "wma" ||
  839. # ifndef HAVE_SNDFILE
  840. // FFmpeg without sndfile
  841. extension == "flac" ||
  842. extension == "oga" ||
  843. extension == "ogg" ||
  844. extension == "w64" ||
  845. extension == "wav" ||
  846. # endif
  847. #endif
  848. false
  849. )
  850. {
  851. if (addPlugin(PLUGIN_INTERNAL, nullptr, baseName, "audiofile", 0, nullptr))
  852. {
  853. if (CarlaPlugin* const plugin = getPlugin(curPluginId))
  854. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "file", filename, true);
  855. return true;
  856. }
  857. return false;
  858. }
  859. // -------------------------------------------------------------------
  860. if (extension == "mid" || extension == "midi")
  861. {
  862. if (addPlugin(PLUGIN_INTERNAL, nullptr, baseName, "midifile", 0, nullptr))
  863. {
  864. if (CarlaPlugin* const plugin = getPlugin(curPluginId))
  865. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "file", filename, true);
  866. return true;
  867. }
  868. return false;
  869. }
  870. // -------------------------------------------------------------------
  871. // ZynAddSubFX
  872. if (extension == "xmz" || extension == "xiz")
  873. {
  874. #ifdef HAVE_ZYN_DEPS
  875. CarlaString nicerName("Zyn - ");
  876. const std::size_t sep(baseName.find('-')+1);
  877. if (sep < baseName.length())
  878. nicerName += baseName.buffer()+sep;
  879. else
  880. nicerName += baseName;
  881. //nicerName
  882. if (addPlugin(PLUGIN_INTERNAL, nullptr, nicerName, "zynaddsubfx", 0, nullptr))
  883. {
  884. callback(ENGINE_CALLBACK_UI_STATE_CHANGED, curPluginId, 0, 0, 0.0f, nullptr);
  885. if (CarlaPlugin* const plugin = getPlugin(curPluginId))
  886. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, (extension == "xmz") ? "CarlaAlternateFile1" : "CarlaAlternateFile2", filename, true);
  887. return true;
  888. }
  889. return false;
  890. #else
  891. setLastError("This Carla build does not have ZynAddSubFX support");
  892. return false;
  893. #endif
  894. }
  895. // -------------------------------------------------------------------
  896. // Direct plugin binaries
  897. #ifdef CARLA_OS_MAC
  898. if (extension == "vst")
  899. return addPlugin(PLUGIN_VST2, filename, nullptr, nullptr, 0, nullptr);
  900. #else
  901. if (extension == "dll" || extension == "so")
  902. return addPlugin(getBinaryTypeFromFile(filename), PLUGIN_VST2, filename, nullptr, nullptr, 0, nullptr, 0x0);
  903. #endif
  904. #if defined(USING_JUCE) && (defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN))
  905. if (extension == "vst3")
  906. return addPlugin(getBinaryTypeFromFile(filename), PLUGIN_VST3, filename, nullptr, nullptr, 0, nullptr, 0x0);
  907. #endif
  908. // -------------------------------------------------------------------
  909. setLastError("Unknown file extension");
  910. return false;
  911. }
  912. bool CarlaEngine::loadProject(const char* const filename)
  913. {
  914. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  915. CARLA_SAFE_ASSERT_RETURN_ERR(filename != nullptr && filename[0] != '\0', "Invalid filename");
  916. carla_debug("CarlaEngine::loadProject(\"%s\")", filename);
  917. const String jfilename = String(CharPointer_UTF8(filename));
  918. File file(jfilename);
  919. CARLA_SAFE_ASSERT_RETURN_ERR(file.existsAsFile(), "Requested file does not exist or is not a readable file");
  920. XmlDocument xml(file);
  921. return loadProjectInternal(xml);
  922. }
  923. bool CarlaEngine::saveProject(const char* const filename)
  924. {
  925. CARLA_SAFE_ASSERT_RETURN_ERR(filename != nullptr && filename[0] != '\0', "Invalid filename");
  926. carla_debug("CarlaEngine::saveProject(\"%s\")", filename);
  927. MemoryOutputStream out;
  928. saveProjectInternal(out);
  929. const String jfilename = String(CharPointer_UTF8(filename));
  930. File file(jfilename);
  931. if (file.replaceWithData(out.getData(), out.getDataSize()))
  932. return true;
  933. setLastError("Failed to write file");
  934. return false;
  935. }
  936. // -----------------------------------------------------------------------
  937. // Information (base)
  938. uint CarlaEngine::getHints() const noexcept
  939. {
  940. return pData->hints;
  941. }
  942. uint32_t CarlaEngine::getBufferSize() const noexcept
  943. {
  944. return pData->bufferSize;
  945. }
  946. double CarlaEngine::getSampleRate() const noexcept
  947. {
  948. return pData->sampleRate;
  949. }
  950. const char* CarlaEngine::getName() const noexcept
  951. {
  952. return pData->name;
  953. }
  954. EngineProcessMode CarlaEngine::getProccessMode() const noexcept
  955. {
  956. return pData->options.processMode;
  957. }
  958. const EngineOptions& CarlaEngine::getOptions() const noexcept
  959. {
  960. return pData->options;
  961. }
  962. EngineTimeInfo CarlaEngine::getTimeInfo() const noexcept
  963. {
  964. return pData->timeInfo;
  965. }
  966. // -----------------------------------------------------------------------
  967. // Information (peaks)
  968. float* CarlaEngine::getPeaks(const uint pluginId) const noexcept
  969. {
  970. carla_zeroFloats(pData->peaks, 4);
  971. if (pluginId == MAIN_CARLA_PLUGIN_ID)
  972. {
  973. // get peak from first plugin, if available
  974. if (const uint count = pData->curPluginCount)
  975. {
  976. pData->peaks[0] = pData->plugins[0].peaks[0];
  977. pData->peaks[1] = pData->plugins[0].peaks[1];
  978. pData->peaks[2] = pData->plugins[count-1].peaks[2];
  979. pData->peaks[3] = pData->plugins[count-1].peaks[3];
  980. }
  981. return pData->peaks;
  982. }
  983. CARLA_SAFE_ASSERT_RETURN(pluginId < pData->curPluginCount, pData->peaks);
  984. return pData->plugins[pluginId].peaks;
  985. }
  986. float CarlaEngine::getInputPeak(const uint pluginId, const bool isLeft) const noexcept
  987. {
  988. if (pluginId == MAIN_CARLA_PLUGIN_ID)
  989. {
  990. // get peak from first plugin, if available
  991. if (pData->curPluginCount > 0)
  992. return pData->plugins[0].peaks[isLeft ? 0 : 1];
  993. return 0.0f;
  994. }
  995. CARLA_SAFE_ASSERT_RETURN(pluginId < pData->curPluginCount, 0.0f);
  996. return pData->plugins[pluginId].peaks[isLeft ? 0 : 1];
  997. }
  998. float CarlaEngine::getOutputPeak(const uint pluginId, const bool isLeft) const noexcept
  999. {
  1000. if (pluginId == MAIN_CARLA_PLUGIN_ID)
  1001. {
  1002. // get peak from last plugin, if available
  1003. if (pData->curPluginCount > 0)
  1004. return pData->plugins[pData->curPluginCount-1].peaks[isLeft ? 2 : 3];
  1005. return 0.0f;
  1006. }
  1007. CARLA_SAFE_ASSERT_RETURN(pluginId < pData->curPluginCount, 0.0f);
  1008. return pData->plugins[pluginId].peaks[isLeft ? 2 : 3];
  1009. }
  1010. // -----------------------------------------------------------------------
  1011. // Callback
  1012. void CarlaEngine::callback(const EngineCallbackOpcode action, const uint pluginId, const int value1, const int value2, const float value3, const char* const valueStr) noexcept
  1013. {
  1014. #ifdef DEBUG
  1015. if (pData->isIdling)
  1016. carla_stdout("CarlaEngine::callback [while idling] (%i:%s, %i, %i, %i, %f, \"%s\")",
  1017. action, EngineCallbackOpcode2Str(action), pluginId, value1, value2, value3, valueStr);
  1018. else if (action != ENGINE_CALLBACK_IDLE && action != ENGINE_CALLBACK_NOTE_ON && action != ENGINE_CALLBACK_NOTE_OFF)
  1019. carla_debug("CarlaEngine::callback(%i:%s, %i, %i, %i, %f, \"%s\")",
  1020. action, EngineCallbackOpcode2Str(action), pluginId, value1, value2, value3, valueStr);
  1021. #endif
  1022. if (pData->callback != nullptr)
  1023. {
  1024. if (action == ENGINE_CALLBACK_IDLE)
  1025. ++pData->isIdling;
  1026. try {
  1027. pData->callback(pData->callbackPtr, action, pluginId, value1, value2, value3, valueStr);
  1028. #if defined(CARLA_OS_LINUX) && defined(__arm__)
  1029. } catch (__cxxabiv1::__forced_unwind&) {
  1030. carla_stderr2("Caught forced unwind exception in callback");
  1031. throw;
  1032. #endif
  1033. } catch (...) {
  1034. carla_safe_exception("callback", __FILE__, __LINE__);
  1035. }
  1036. if (action == ENGINE_CALLBACK_IDLE)
  1037. --pData->isIdling;
  1038. }
  1039. }
  1040. void CarlaEngine::setCallback(const EngineCallbackFunc func, void* const ptr) noexcept
  1041. {
  1042. carla_debug("CarlaEngine::setCallback(%p, %p)", func, ptr);
  1043. pData->callback = func;
  1044. pData->callbackPtr = ptr;
  1045. }
  1046. // -----------------------------------------------------------------------
  1047. // File Callback
  1048. const char* CarlaEngine::runFileCallback(const FileCallbackOpcode action, const bool isDir, const char* const title, const char* const filter) noexcept
  1049. {
  1050. CARLA_SAFE_ASSERT_RETURN(title != nullptr && title[0] != '\0', nullptr);
  1051. CARLA_SAFE_ASSERT_RETURN(filter != nullptr, nullptr);
  1052. carla_debug("CarlaEngine::runFileCallback(%i:%s, %s, \"%s\", \"%s\")", action, FileCallbackOpcode2Str(action), bool2str(isDir), title, filter);
  1053. const char* ret = nullptr;
  1054. if (pData->fileCallback != nullptr)
  1055. {
  1056. try {
  1057. ret = pData->fileCallback(pData->fileCallbackPtr, action, isDir, title, filter);
  1058. } CARLA_SAFE_EXCEPTION("runFileCallback");
  1059. }
  1060. return ret;
  1061. }
  1062. void CarlaEngine::setFileCallback(const FileCallbackFunc func, void* const ptr) noexcept
  1063. {
  1064. carla_debug("CarlaEngine::setFileCallback(%p, %p)", func, ptr);
  1065. pData->fileCallback = func;
  1066. pData->fileCallbackPtr = ptr;
  1067. }
  1068. // -----------------------------------------------------------------------
  1069. // Transport
  1070. void CarlaEngine::transportPlay() noexcept
  1071. {
  1072. pData->timeInfo.playing = true;
  1073. pData->time.setNeedsReset();
  1074. }
  1075. void CarlaEngine::transportPause() noexcept
  1076. {
  1077. if (pData->timeInfo.playing)
  1078. pData->time.pause();
  1079. else
  1080. pData->time.setNeedsReset();
  1081. }
  1082. void CarlaEngine::transportBPM(const double bpm) noexcept
  1083. {
  1084. try {
  1085. pData->time.setBPM(bpm);
  1086. } CARLA_SAFE_EXCEPTION("CarlaEngine::transportBPM");
  1087. }
  1088. void CarlaEngine::transportRelocate(const uint64_t frame) noexcept
  1089. {
  1090. pData->time.relocate(frame);
  1091. }
  1092. // -----------------------------------------------------------------------
  1093. // Error handling
  1094. const char* CarlaEngine::getLastError() const noexcept
  1095. {
  1096. return pData->lastError;
  1097. }
  1098. void CarlaEngine::setLastError(const char* const error) const noexcept
  1099. {
  1100. pData->lastError = error;
  1101. }
  1102. // -----------------------------------------------------------------------
  1103. // Misc
  1104. bool CarlaEngine::isAboutToClose() const noexcept
  1105. {
  1106. return pData->aboutToClose;
  1107. }
  1108. bool CarlaEngine::setAboutToClose() noexcept
  1109. {
  1110. carla_debug("CarlaEngine::setAboutToClose()");
  1111. pData->aboutToClose = true;
  1112. return (pData->isIdling == 0);
  1113. }
  1114. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1115. bool CarlaEngine::isLoadingProject() const noexcept
  1116. {
  1117. return pData->loadingProject;
  1118. }
  1119. #endif
  1120. void CarlaEngine::setActionCanceled(const bool canceled) noexcept
  1121. {
  1122. pData->actionCanceled = canceled;
  1123. }
  1124. bool CarlaEngine::wasActionCanceled() const noexcept
  1125. {
  1126. return pData->actionCanceled;
  1127. }
  1128. // -----------------------------------------------------------------------
  1129. // Global options
  1130. void CarlaEngine::setOption(const EngineOption option, const int value, const char* const valueStr) noexcept
  1131. {
  1132. carla_debug("CarlaEngine::setOption(%i:%s, %i, \"%s\")", option, EngineOption2Str(option), value, valueStr);
  1133. if (isRunning())
  1134. {
  1135. switch (option)
  1136. {
  1137. case ENGINE_OPTION_PROCESS_MODE:
  1138. case ENGINE_OPTION_AUDIO_TRIPLE_BUFFER:
  1139. case ENGINE_OPTION_AUDIO_DEVICE:
  1140. return carla_stderr("CarlaEngine::setOption(%i:%s, %i, \"%s\") - Cannot set this option while engine is running!",
  1141. option, EngineOption2Str(option), value, valueStr);
  1142. default:
  1143. break;
  1144. }
  1145. }
  1146. // do not un-force stereo for rack mode
  1147. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK && option == ENGINE_OPTION_FORCE_STEREO && value != 0)
  1148. return;
  1149. switch (option)
  1150. {
  1151. case ENGINE_OPTION_DEBUG:
  1152. break;
  1153. case ENGINE_OPTION_PROCESS_MODE:
  1154. CARLA_SAFE_ASSERT_RETURN(value >= ENGINE_PROCESS_MODE_SINGLE_CLIENT && value <= ENGINE_PROCESS_MODE_BRIDGE,);
  1155. pData->options.processMode = static_cast<EngineProcessMode>(value);
  1156. break;
  1157. case ENGINE_OPTION_TRANSPORT_MODE:
  1158. CARLA_SAFE_ASSERT_RETURN(value >= ENGINE_TRANSPORT_MODE_DISABLED && value <= ENGINE_TRANSPORT_MODE_BRIDGE,);
  1159. CARLA_SAFE_ASSERT_RETURN(getType() == kEngineTypeJack || value != ENGINE_TRANSPORT_MODE_JACK,);
  1160. pData->options.transportMode = static_cast<EngineTransportMode>(value);
  1161. delete[] pData->options.transportExtra;
  1162. if (value >= ENGINE_TRANSPORT_MODE_DISABLED && valueStr != nullptr)
  1163. pData->options.transportExtra = carla_strdup_safe(valueStr);
  1164. else
  1165. pData->options.transportExtra = nullptr;
  1166. pData->time.setNeedsReset();
  1167. #if defined(HAVE_HYLIA) && !defined(BUILD_BRIDGE)
  1168. // enable link now if needed
  1169. {
  1170. const bool linkEnabled = pData->options.transportExtra != nullptr && std::strstr(pData->options.transportExtra, ":link:") != nullptr;
  1171. pData->time.enableLink(linkEnabled);
  1172. }
  1173. #endif
  1174. break;
  1175. case ENGINE_OPTION_FORCE_STEREO:
  1176. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1177. pData->options.forceStereo = (value != 0);
  1178. break;
  1179. case ENGINE_OPTION_PREFER_PLUGIN_BRIDGES:
  1180. #ifdef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1181. CARLA_SAFE_ASSERT_RETURN(value == 0,);
  1182. #else
  1183. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1184. #endif
  1185. pData->options.preferPluginBridges = (value != 0);
  1186. break;
  1187. case ENGINE_OPTION_PREFER_UI_BRIDGES:
  1188. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1189. pData->options.preferUiBridges = (value != 0);
  1190. break;
  1191. case ENGINE_OPTION_UIS_ALWAYS_ON_TOP:
  1192. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1193. pData->options.uisAlwaysOnTop = (value != 0);
  1194. break;
  1195. case ENGINE_OPTION_MAX_PARAMETERS:
  1196. CARLA_SAFE_ASSERT_RETURN(value >= 0,);
  1197. pData->options.maxParameters = static_cast<uint>(value);
  1198. break;
  1199. case ENGINE_OPTION_UI_BRIDGES_TIMEOUT:
  1200. CARLA_SAFE_ASSERT_RETURN(value >= 0,);
  1201. pData->options.uiBridgesTimeout = static_cast<uint>(value);
  1202. break;
  1203. case ENGINE_OPTION_AUDIO_BUFFER_SIZE:
  1204. CARLA_SAFE_ASSERT_RETURN(value >= 8,);
  1205. pData->options.audioBufferSize = static_cast<uint>(value);
  1206. break;
  1207. case ENGINE_OPTION_AUDIO_SAMPLE_RATE:
  1208. CARLA_SAFE_ASSERT_RETURN(value >= 22050,);
  1209. pData->options.audioSampleRate = static_cast<uint>(value);
  1210. break;
  1211. case ENGINE_OPTION_AUDIO_TRIPLE_BUFFER:
  1212. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1213. pData->options.audioTripleBuffer = (value != 0);
  1214. break;
  1215. case ENGINE_OPTION_AUDIO_DEVICE:
  1216. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr,);
  1217. if (pData->options.audioDevice != nullptr)
  1218. delete[] pData->options.audioDevice;
  1219. pData->options.audioDevice = carla_strdup_safe(valueStr);
  1220. break;
  1221. case ENGINE_OPTION_PLUGIN_PATH:
  1222. CARLA_SAFE_ASSERT_RETURN(value > PLUGIN_NONE,);
  1223. CARLA_SAFE_ASSERT_RETURN(value <= PLUGIN_SFZ,);
  1224. switch (value)
  1225. {
  1226. case PLUGIN_LADSPA:
  1227. if (pData->options.pathLADSPA != nullptr)
  1228. delete[] pData->options.pathLADSPA;
  1229. if (valueStr != nullptr)
  1230. pData->options.pathLADSPA = carla_strdup_safe(valueStr);
  1231. else
  1232. pData->options.pathLADSPA = nullptr;
  1233. break;
  1234. case PLUGIN_DSSI:
  1235. if (pData->options.pathDSSI != nullptr)
  1236. delete[] pData->options.pathDSSI;
  1237. if (valueStr != nullptr)
  1238. pData->options.pathDSSI = carla_strdup_safe(valueStr);
  1239. else
  1240. pData->options.pathDSSI = nullptr;
  1241. break;
  1242. case PLUGIN_LV2:
  1243. if (pData->options.pathLV2 != nullptr)
  1244. delete[] pData->options.pathLV2;
  1245. if (valueStr != nullptr)
  1246. pData->options.pathLV2 = carla_strdup_safe(valueStr);
  1247. else
  1248. pData->options.pathLV2 = nullptr;
  1249. break;
  1250. case PLUGIN_VST2:
  1251. if (pData->options.pathVST2 != nullptr)
  1252. delete[] pData->options.pathVST2;
  1253. if (valueStr != nullptr)
  1254. pData->options.pathVST2 = carla_strdup_safe(valueStr);
  1255. else
  1256. pData->options.pathVST2 = nullptr;
  1257. break;
  1258. case PLUGIN_VST3:
  1259. if (pData->options.pathVST3 != nullptr)
  1260. delete[] pData->options.pathVST3;
  1261. if (valueStr != nullptr)
  1262. pData->options.pathVST3 = carla_strdup_safe(valueStr);
  1263. else
  1264. pData->options.pathVST3 = nullptr;
  1265. break;
  1266. case PLUGIN_SF2:
  1267. if (pData->options.pathSF2 != nullptr)
  1268. delete[] pData->options.pathSF2;
  1269. if (valueStr != nullptr)
  1270. pData->options.pathSF2 = carla_strdup_safe(valueStr);
  1271. else
  1272. pData->options.pathSF2 = nullptr;
  1273. break;
  1274. case PLUGIN_SFZ:
  1275. if (pData->options.pathSFZ != nullptr)
  1276. delete[] pData->options.pathSFZ;
  1277. if (valueStr != nullptr)
  1278. pData->options.pathSFZ = carla_strdup_safe(valueStr);
  1279. else
  1280. pData->options.pathSFZ = nullptr;
  1281. break;
  1282. default:
  1283. return carla_stderr("CarlaEngine::setOption(%i:%s, %i, \"%s\") - Invalid plugin type", option, EngineOption2Str(option), value, valueStr);
  1284. break;
  1285. }
  1286. break;
  1287. case ENGINE_OPTION_PATH_BINARIES:
  1288. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1289. if (pData->options.binaryDir != nullptr)
  1290. delete[] pData->options.binaryDir;
  1291. pData->options.binaryDir = carla_strdup_safe(valueStr);
  1292. break;
  1293. case ENGINE_OPTION_PATH_RESOURCES:
  1294. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1295. if (pData->options.resourceDir != nullptr)
  1296. delete[] pData->options.resourceDir;
  1297. pData->options.resourceDir = carla_strdup_safe(valueStr);
  1298. break;
  1299. case ENGINE_OPTION_PREVENT_BAD_BEHAVIOUR: {
  1300. CARLA_SAFE_ASSERT_RETURN(pData->options.binaryDir != nullptr && pData->options.binaryDir[0] != '\0',);
  1301. #ifdef CARLA_OS_LINUX
  1302. const ScopedEngineEnvironmentLocker _seel(this);
  1303. if (value != 0)
  1304. {
  1305. CarlaString interposerPath(CarlaString(pData->options.binaryDir) + "/libcarla_interposer-safe.so");
  1306. ::setenv("LD_PRELOAD", interposerPath.buffer(), 1);
  1307. }
  1308. else
  1309. {
  1310. ::unsetenv("LD_PRELOAD");
  1311. }
  1312. #endif
  1313. } break;
  1314. case ENGINE_OPTION_FRONTEND_WIN_ID: {
  1315. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1316. const long long winId(std::strtoll(valueStr, nullptr, 16));
  1317. CARLA_SAFE_ASSERT_RETURN(winId >= 0,);
  1318. pData->options.frontendWinId = static_cast<uintptr_t>(winId);
  1319. } break;
  1320. #if !defined(BUILD_BRIDGE_ALTERNATIVE_ARCH) && !defined(CARLA_OS_WIN)
  1321. case ENGINE_OPTION_WINE_EXECUTABLE:
  1322. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1323. if (pData->options.wine.executable != nullptr)
  1324. delete[] pData->options.wine.executable;
  1325. pData->options.wine.executable = carla_strdup_safe(valueStr);
  1326. break;
  1327. case ENGINE_OPTION_WINE_AUTO_PREFIX:
  1328. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1329. pData->options.wine.autoPrefix = (value != 0);
  1330. break;
  1331. case ENGINE_OPTION_WINE_FALLBACK_PREFIX:
  1332. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1333. if (pData->options.wine.fallbackPrefix != nullptr)
  1334. delete[] pData->options.wine.fallbackPrefix;
  1335. pData->options.wine.fallbackPrefix = carla_strdup_safe(valueStr);
  1336. break;
  1337. case ENGINE_OPTION_WINE_RT_PRIO_ENABLED:
  1338. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1339. pData->options.wine.rtPrio = (value != 0);
  1340. break;
  1341. case ENGINE_OPTION_WINE_BASE_RT_PRIO:
  1342. CARLA_SAFE_ASSERT_RETURN(value >= 1 && value <= 89,);
  1343. pData->options.wine.baseRtPrio = value;
  1344. break;
  1345. case ENGINE_OPTION_WINE_SERVER_RT_PRIO:
  1346. CARLA_SAFE_ASSERT_RETURN(value >= 1 && value <= 99,);
  1347. pData->options.wine.serverRtPrio = value;
  1348. break;
  1349. #endif
  1350. case ENGINE_OPTION_DEBUG_CONSOLE_OUTPUT:
  1351. break;
  1352. }
  1353. }
  1354. #ifndef BUILD_BRIDGE
  1355. // -----------------------------------------------------------------------
  1356. // OSC Stuff
  1357. bool CarlaEngine::isOscControlRegistered() const noexcept
  1358. {
  1359. # ifdef HAVE_LIBLO
  1360. return pData->osc.isControlRegistered();
  1361. # else
  1362. return false;
  1363. # endif
  1364. }
  1365. void CarlaEngine::idleOsc() const noexcept
  1366. {
  1367. # ifdef HAVE_LIBLO
  1368. pData->osc.idle();
  1369. # endif
  1370. }
  1371. const char* CarlaEngine::getOscServerPathTCP() const noexcept
  1372. {
  1373. # ifdef HAVE_LIBLO
  1374. return pData->osc.getServerPathTCP();
  1375. # else
  1376. return nullptr;
  1377. # endif
  1378. }
  1379. const char* CarlaEngine::getOscServerPathUDP() const noexcept
  1380. {
  1381. # ifdef HAVE_LIBLO
  1382. return pData->osc.getServerPathUDP();
  1383. # else
  1384. return nullptr;
  1385. # endif
  1386. }
  1387. #endif
  1388. // -----------------------------------------------------------------------
  1389. // Helper functions
  1390. EngineEvent* CarlaEngine::getInternalEventBuffer(const bool isInput) const noexcept
  1391. {
  1392. return isInput ? pData->events.in : pData->events.out;
  1393. }
  1394. // -----------------------------------------------------------------------
  1395. // Internal stuff
  1396. void CarlaEngine::bufferSizeChanged(const uint32_t newBufferSize)
  1397. {
  1398. carla_debug("CarlaEngine::bufferSizeChanged(%i)", newBufferSize);
  1399. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1400. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1401. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1402. {
  1403. pData->graph.setBufferSize(newBufferSize);
  1404. }
  1405. #endif
  1406. pData->time.updateAudioValues(newBufferSize, pData->sampleRate);
  1407. for (uint i=0; i < pData->curPluginCount; ++i)
  1408. {
  1409. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1410. if (plugin != nullptr && plugin->isEnabled())
  1411. {
  1412. plugin->tryLock(true);
  1413. plugin->bufferSizeChanged(newBufferSize);
  1414. plugin->unlock();
  1415. }
  1416. }
  1417. callback(ENGINE_CALLBACK_BUFFER_SIZE_CHANGED, 0, static_cast<int>(newBufferSize), 0, 0.0f, nullptr);
  1418. }
  1419. void CarlaEngine::sampleRateChanged(const double newSampleRate)
  1420. {
  1421. carla_debug("CarlaEngine::sampleRateChanged(%g)", newSampleRate);
  1422. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1423. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1424. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1425. {
  1426. pData->graph.setSampleRate(newSampleRate);
  1427. }
  1428. #endif
  1429. pData->time.updateAudioValues(pData->bufferSize, newSampleRate);
  1430. for (uint i=0; i < pData->curPluginCount; ++i)
  1431. {
  1432. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1433. if (plugin != nullptr && plugin->isEnabled())
  1434. {
  1435. plugin->tryLock(true);
  1436. plugin->sampleRateChanged(newSampleRate);
  1437. plugin->unlock();
  1438. }
  1439. }
  1440. callback(ENGINE_CALLBACK_SAMPLE_RATE_CHANGED, 0, 0, 0, static_cast<float>(newSampleRate), nullptr);
  1441. }
  1442. void CarlaEngine::offlineModeChanged(const bool isOfflineNow)
  1443. {
  1444. carla_debug("CarlaEngine::offlineModeChanged(%s)", bool2str(isOfflineNow));
  1445. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1446. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1447. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1448. {
  1449. pData->graph.setOffline(isOfflineNow);
  1450. }
  1451. #endif
  1452. for (uint i=0; i < pData->curPluginCount; ++i)
  1453. {
  1454. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1455. if (plugin != nullptr && plugin->isEnabled())
  1456. plugin->offlineModeChanged(isOfflineNow);
  1457. }
  1458. }
  1459. void CarlaEngine::setPluginPeaks(const uint pluginId, float const inPeaks[2], float const outPeaks[2]) noexcept
  1460. {
  1461. EnginePluginData& pluginData(pData->plugins[pluginId]);
  1462. pluginData.peaks[0] = inPeaks[0];
  1463. pluginData.peaks[1] = inPeaks[1];
  1464. pluginData.peaks[2] = outPeaks[0];
  1465. pluginData.peaks[3] = outPeaks[1];
  1466. }
  1467. void CarlaEngine::saveProjectInternal(water::MemoryOutputStream& outStream) const
  1468. {
  1469. // send initial prepareForSave first, giving time for bridges to act
  1470. for (uint i=0; i < pData->curPluginCount; ++i)
  1471. {
  1472. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1473. if (plugin != nullptr && plugin->isEnabled())
  1474. {
  1475. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1476. // deactivate bridge client-side ping check, since some plugins block during save
  1477. if (plugin->getHints() & PLUGIN_IS_BRIDGE)
  1478. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "false", false);
  1479. #endif
  1480. plugin->prepareForSave();
  1481. }
  1482. }
  1483. outStream << "<?xml version='1.0' encoding='UTF-8'?>\n";
  1484. outStream << "<!DOCTYPE CARLA-PROJECT>\n";
  1485. outStream << "<CARLA-PROJECT VERSION='2.0'>\n";
  1486. const bool isPlugin(getType() == kEngineTypePlugin);
  1487. const EngineOptions& options(pData->options);
  1488. {
  1489. MemoryOutputStream outSettings(1024);
  1490. outSettings << " <EngineSettings>\n";
  1491. outSettings << " <ForceStereo>" << bool2str(options.forceStereo) << "</ForceStereo>\n";
  1492. outSettings << " <PreferPluginBridges>" << bool2str(options.preferPluginBridges) << "</PreferPluginBridges>\n";
  1493. outSettings << " <PreferUiBridges>" << bool2str(options.preferUiBridges) << "</PreferUiBridges>\n";
  1494. outSettings << " <UIsAlwaysOnTop>" << bool2str(options.uisAlwaysOnTop) << "</UIsAlwaysOnTop>\n";
  1495. outSettings << " <MaxParameters>" << String(options.maxParameters) << "</MaxParameters>\n";
  1496. outSettings << " <UIBridgesTimeout>" << String(options.uiBridgesTimeout) << "</UIBridgesTimeout>\n";
  1497. if (isPlugin)
  1498. {
  1499. outSettings << " <LADSPA_PATH>" << xmlSafeString(options.pathLADSPA, true) << "</LADSPA_PATH>\n";
  1500. outSettings << " <DSSI_PATH>" << xmlSafeString(options.pathDSSI, true) << "</DSSI_PATH>\n";
  1501. outSettings << " <LV2_PATH>" << xmlSafeString(options.pathLV2, true) << "</LV2_PATH>\n";
  1502. outSettings << " <VST2_PATH>" << xmlSafeString(options.pathVST2, true) << "</VST2_PATH>\n";
  1503. outSettings << " <VST3_PATH>" << xmlSafeString(options.pathVST3, true) << "</VST3_PATH>\n";
  1504. outSettings << " <SF2_PATH>" << xmlSafeString(options.pathSF2, true) << "</SF2_PATH>\n";
  1505. outSettings << " <SFZ_PATH>" << xmlSafeString(options.pathSFZ, true) << "</SFZ_PATH>\n";
  1506. }
  1507. outSettings << " </EngineSettings>\n";
  1508. outStream << outSettings;
  1509. }
  1510. if (pData->timeInfo.bbt.valid && ! isPlugin)
  1511. {
  1512. MemoryOutputStream outTransport(128);
  1513. outTransport << "\n <Transport>\n";
  1514. // outTransport << " <BeatsPerBar>" << pData->timeInfo.bbt.beatsPerBar << "</BeatsPerBar>\n";
  1515. outTransport << " <BeatsPerMinute>" << pData->timeInfo.bbt.beatsPerMinute << "</BeatsPerMinute>\n";
  1516. outTransport << " </Transport>\n";
  1517. outStream << outTransport;
  1518. }
  1519. char strBuf[STR_MAX+1];
  1520. for (uint i=0; i < pData->curPluginCount; ++i)
  1521. {
  1522. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1523. if (plugin != nullptr && plugin->isEnabled())
  1524. {
  1525. MemoryOutputStream outPlugin(4096), streamPlugin;
  1526. plugin->getStateSave(false).dumpToMemoryStream(streamPlugin);
  1527. outPlugin << "\n";
  1528. strBuf[0] = '\0';
  1529. plugin->getRealName(strBuf);
  1530. if (strBuf[0] != '\0')
  1531. outPlugin << " <!-- " << xmlSafeString(strBuf, true) << " -->\n";
  1532. outPlugin << " <Plugin>\n";
  1533. outPlugin << streamPlugin;
  1534. outPlugin << " </Plugin>\n";
  1535. outStream << outPlugin;
  1536. }
  1537. }
  1538. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1539. // tell bridges we're done saving
  1540. for (uint i=0; i < pData->curPluginCount; ++i)
  1541. {
  1542. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1543. if (plugin != nullptr && plugin->isEnabled() && (plugin->getHints() & PLUGIN_IS_BRIDGE) != 0)
  1544. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "true", false);
  1545. }
  1546. // save internal connections
  1547. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1548. {
  1549. if (const char* const* const patchbayConns = getPatchbayConnections(false))
  1550. {
  1551. MemoryOutputStream outPatchbay(2048);
  1552. outPatchbay << "\n <Patchbay>\n";
  1553. for (int i=0; patchbayConns[i] != nullptr && patchbayConns[i+1] != nullptr; ++i, ++i )
  1554. {
  1555. const char* const connSource(patchbayConns[i]);
  1556. const char* const connTarget(patchbayConns[i+1]);
  1557. CARLA_SAFE_ASSERT_CONTINUE(connSource != nullptr && connSource[0] != '\0');
  1558. CARLA_SAFE_ASSERT_CONTINUE(connTarget != nullptr && connTarget[0] != '\0');
  1559. outPatchbay << " <Connection>\n";
  1560. outPatchbay << " <Source>" << xmlSafeString(connSource, true) << "</Source>\n";
  1561. outPatchbay << " <Target>" << xmlSafeString(connTarget, true) << "</Target>\n";
  1562. outPatchbay << " </Connection>\n";
  1563. }
  1564. outPatchbay << " </Patchbay>\n";
  1565. outStream << outPatchbay;
  1566. }
  1567. }
  1568. // if we're running inside some session-manager (and using JACK), let them handle the connections
  1569. bool saveExternalConnections;
  1570. /**/ if (isPlugin)
  1571. saveExternalConnections = false;
  1572. else if (std::strcmp(getCurrentDriverName(), "JACK") != 0)
  1573. saveExternalConnections = true;
  1574. else if (std::getenv("CARLA_DONT_MANAGE_CONNECTIONS") != nullptr)
  1575. saveExternalConnections = false;
  1576. else if (std::getenv("LADISH_APP_NAME") != nullptr)
  1577. saveExternalConnections = false;
  1578. else if (std::getenv("NSM_URL") != nullptr)
  1579. saveExternalConnections = false;
  1580. else
  1581. saveExternalConnections = true;
  1582. if (saveExternalConnections)
  1583. {
  1584. if (const char* const* const patchbayConns = getPatchbayConnections(true))
  1585. {
  1586. MemoryOutputStream outPatchbay(2048);
  1587. outPatchbay << "\n <ExternalPatchbay>\n";
  1588. for (int i=0; patchbayConns[i] != nullptr && patchbayConns[i+1] != nullptr; ++i, ++i )
  1589. {
  1590. const char* const connSource(patchbayConns[i]);
  1591. const char* const connTarget(patchbayConns[i+1]);
  1592. CARLA_SAFE_ASSERT_CONTINUE(connSource != nullptr && connSource[0] != '\0');
  1593. CARLA_SAFE_ASSERT_CONTINUE(connTarget != nullptr && connTarget[0] != '\0');
  1594. outPatchbay << " <Connection>\n";
  1595. outPatchbay << " <Source>" << xmlSafeString(connSource, true) << "</Source>\n";
  1596. outPatchbay << " <Target>" << xmlSafeString(connTarget, true) << "</Target>\n";
  1597. outPatchbay << " </Connection>\n";
  1598. }
  1599. outPatchbay << " </ExternalPatchbay>\n";
  1600. outStream << outPatchbay;
  1601. }
  1602. }
  1603. #endif
  1604. outStream << "</CARLA-PROJECT>\n";
  1605. }
  1606. static String findBinaryInCustomPath(const char* const searchPath, const char* const binary)
  1607. {
  1608. const StringArray searchPaths(StringArray::fromTokens(searchPath, CARLA_OS_SPLIT_STR, ""));
  1609. // try direct filename first
  1610. String jbinary(binary);
  1611. // adjust for current platform
  1612. #ifdef CARLA_OS_WIN
  1613. if (jbinary[0] == '/')
  1614. jbinary = "C:" + jbinary.replaceCharacter('/', '\\');
  1615. #else
  1616. if (jbinary[1] == ':' && (jbinary[2] == '\\' || jbinary[2] == '/'))
  1617. jbinary = jbinary.substring(2).replaceCharacter('\\', '/');
  1618. #endif
  1619. String filename = File(jbinary).getFileName();
  1620. int searchFlags = File::findFiles|File::ignoreHiddenFiles;
  1621. #ifdef CARLA_OS_MAC
  1622. if (filename.endsWithIgnoreCase(".vst") || filename.endsWithIgnoreCase(".vst3"))
  1623. searchFlags |= File::findDirectories;
  1624. #endif
  1625. Array<File> results;
  1626. for (const String *it=searchPaths.begin(), *end=searchPaths.end(); it != end; ++it)
  1627. {
  1628. const File path(*it);
  1629. results.clear();
  1630. path.findChildFiles(results, searchFlags, true, filename);
  1631. if (results.size() > 0)
  1632. return results.getFirst().getFullPathName();
  1633. }
  1634. // try changing extension
  1635. #if defined(CARLA_OS_MAC)
  1636. if (filename.endsWithIgnoreCase(".dll") || filename.endsWithIgnoreCase(".so"))
  1637. filename = File(jbinary).getFileNameWithoutExtension() + ".dylib";
  1638. #elif defined(CARLA_OS_WIN)
  1639. if (filename.endsWithIgnoreCase(".dylib") || filename.endsWithIgnoreCase(".so"))
  1640. filename = File(jbinary).getFileNameWithoutExtension() + ".dll";
  1641. #else
  1642. if (filename.endsWithIgnoreCase(".dll") || filename.endsWithIgnoreCase(".dylib"))
  1643. filename = File(jbinary).getFileNameWithoutExtension() + ".so";
  1644. #endif
  1645. else
  1646. return String();
  1647. for (const String *it=searchPaths.begin(), *end=searchPaths.end(); it != end; ++it)
  1648. {
  1649. const File path(*it);
  1650. results.clear();
  1651. path.findChildFiles(results, searchFlags, true, filename);
  1652. if (results.size() > 0)
  1653. return results.getFirst().getFullPathName();
  1654. }
  1655. return String();
  1656. }
  1657. bool CarlaEngine::loadProjectInternal(water::XmlDocument& xmlDoc)
  1658. {
  1659. ScopedPointer<XmlElement> xmlElement(xmlDoc.getDocumentElement(true));
  1660. CARLA_SAFE_ASSERT_RETURN_ERR(xmlElement != nullptr, "Failed to parse project file");
  1661. const String& xmlType(xmlElement->getTagName());
  1662. const bool isPreset(xmlType.equalsIgnoreCase("carla-preset"));
  1663. if (! (xmlType.equalsIgnoreCase("carla-project") || isPreset))
  1664. {
  1665. callback(ENGINE_CALLBACK_PROJECT_LOAD_FINISHED, 0, 0, 0, 0.0f, nullptr);
  1666. setLastError("Not a valid Carla project or preset file");
  1667. return false;
  1668. }
  1669. pData->actionCanceled = false;
  1670. callback(ENGINE_CALLBACK_CANCELABLE_ACTION, 0, 1, 0, 0.0f, "Loading project");
  1671. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1672. const ScopedValueSetter<bool> _svs2(pData->loadingProject, true, false);
  1673. #endif
  1674. // completely load file
  1675. xmlElement = xmlDoc.getDocumentElement(false);
  1676. CARLA_SAFE_ASSERT_RETURN_ERR(xmlElement != nullptr, "Failed to completely parse project file");
  1677. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  1678. if (pData->aboutToClose)
  1679. return true;
  1680. if (pData->actionCanceled)
  1681. {
  1682. setLastError("Project load canceled");
  1683. return false;
  1684. }
  1685. const bool isPlugin(getType() == kEngineTypePlugin);
  1686. // load engine settings first of all
  1687. if (XmlElement* const elem = isPreset ? nullptr : xmlElement->getChildByName("EngineSettings"))
  1688. {
  1689. for (XmlElement* settElem = elem->getFirstChildElement(); settElem != nullptr; settElem = settElem->getNextElement())
  1690. {
  1691. const String& tag(settElem->getTagName());
  1692. const String text(settElem->getAllSubText().trim());
  1693. /** some settings might be incorrect or require extra work,
  1694. so we call setOption rather than modifying them direly */
  1695. int option = -1;
  1696. int value = 0;
  1697. const char* valueStr = nullptr;
  1698. /**/ if (tag == "ForceStereo")
  1699. {
  1700. option = ENGINE_OPTION_FORCE_STEREO;
  1701. value = text == "true" ? 1 : 0;
  1702. }
  1703. else if (tag == "PreferPluginBridges")
  1704. {
  1705. option = ENGINE_OPTION_PREFER_PLUGIN_BRIDGES;
  1706. value = text == "true" ? 1 : 0;
  1707. }
  1708. else if (tag == "PreferUiBridges")
  1709. {
  1710. option = ENGINE_OPTION_PREFER_UI_BRIDGES;
  1711. value = text == "true" ? 1 : 0;
  1712. }
  1713. else if (tag == "UIsAlwaysOnTop")
  1714. {
  1715. option = ENGINE_OPTION_UIS_ALWAYS_ON_TOP;
  1716. value = text == "true" ? 1 : 0;
  1717. }
  1718. else if (tag == "MaxParameters")
  1719. {
  1720. option = ENGINE_OPTION_MAX_PARAMETERS;
  1721. value = text.getIntValue();
  1722. }
  1723. else if (tag == "UIBridgesTimeout")
  1724. {
  1725. option = ENGINE_OPTION_UI_BRIDGES_TIMEOUT;
  1726. value = text.getIntValue();
  1727. }
  1728. else if (isPlugin)
  1729. {
  1730. /**/ if (tag == "LADSPA_PATH")
  1731. {
  1732. option = ENGINE_OPTION_PLUGIN_PATH;
  1733. value = PLUGIN_LADSPA;
  1734. valueStr = text.toRawUTF8();
  1735. }
  1736. else if (tag == "DSSI_PATH")
  1737. {
  1738. option = ENGINE_OPTION_PLUGIN_PATH;
  1739. value = PLUGIN_DSSI;
  1740. valueStr = text.toRawUTF8();
  1741. }
  1742. else if (tag == "LV2_PATH")
  1743. {
  1744. option = ENGINE_OPTION_PLUGIN_PATH;
  1745. value = PLUGIN_LV2;
  1746. valueStr = text.toRawUTF8();
  1747. }
  1748. else if (tag == "VST2_PATH")
  1749. {
  1750. option = ENGINE_OPTION_PLUGIN_PATH;
  1751. value = PLUGIN_VST2;
  1752. valueStr = text.toRawUTF8();
  1753. }
  1754. else if (tag.equalsIgnoreCase("VST3_PATH"))
  1755. {
  1756. option = ENGINE_OPTION_PLUGIN_PATH;
  1757. value = PLUGIN_VST3;
  1758. valueStr = text.toRawUTF8();
  1759. }
  1760. else if (tag == "SF2_PATH")
  1761. {
  1762. option = ENGINE_OPTION_PLUGIN_PATH;
  1763. value = PLUGIN_SF2;
  1764. valueStr = text.toRawUTF8();
  1765. }
  1766. else if (tag == "SFZ_PATH")
  1767. {
  1768. option = ENGINE_OPTION_PLUGIN_PATH;
  1769. value = PLUGIN_SFZ;
  1770. valueStr = text.toRawUTF8();
  1771. }
  1772. }
  1773. if (option == -1)
  1774. {
  1775. // check old stuff, unhandled now
  1776. if (tag == "GIG_PATH")
  1777. continue;
  1778. // ignored tags
  1779. if (tag == "LADSPA_PATH" || tag == "DSSI_PATH" || tag == "LV2_PATH" || tag == "VST2_PATH")
  1780. continue;
  1781. if (tag == "VST3_PATH" || tag == "AU_PATH")
  1782. continue;
  1783. if (tag == "SF2_PATH" || tag == "SFZ_PATH")
  1784. continue;
  1785. // hmm something is wrong..
  1786. carla_stderr2("CarlaEngine::loadProjectInternal() - Unhandled option '%s'", tag.toRawUTF8());
  1787. continue;
  1788. }
  1789. setOption(static_cast<EngineOption>(option), value, valueStr);
  1790. }
  1791. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  1792. if (pData->aboutToClose)
  1793. return true;
  1794. if (pData->actionCanceled)
  1795. {
  1796. setLastError("Project load canceled");
  1797. return false;
  1798. }
  1799. }
  1800. // now setup transport
  1801. if (XmlElement* const elem = (isPreset || isPlugin) ? nullptr : xmlElement->getChildByName("Transport"))
  1802. {
  1803. if (XmlElement* const bpmElem = elem->getChildByName("BeatsPerMinute"))
  1804. {
  1805. const String bpmText(bpmElem->getAllSubText().trim());
  1806. const double bpm = bpmText.getDoubleValue();
  1807. // some sane limits
  1808. if (bpm >= 20.0 && bpm < 400.0)
  1809. pData->time.setBPM(bpm);
  1810. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  1811. if (pData->aboutToClose)
  1812. return true;
  1813. if (pData->actionCanceled)
  1814. {
  1815. setLastError("Project load canceled");
  1816. return false;
  1817. }
  1818. }
  1819. }
  1820. // and we handle plugins
  1821. for (XmlElement* elem = xmlElement->getFirstChildElement(); elem != nullptr; elem = elem->getNextElement())
  1822. {
  1823. const String& tagName(elem->getTagName());
  1824. if (isPreset || tagName == "Plugin")
  1825. {
  1826. CarlaStateSave stateSave;
  1827. stateSave.fillFromXmlElement(isPreset ? xmlElement.get() : elem);
  1828. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  1829. if (pData->aboutToClose)
  1830. return true;
  1831. if (pData->actionCanceled)
  1832. {
  1833. setLastError("Project load canceled");
  1834. return false;
  1835. }
  1836. CARLA_SAFE_ASSERT_CONTINUE(stateSave.type != nullptr);
  1837. #ifndef BUILD_BRIDGE
  1838. // compatibility code to load projects with GIG files
  1839. // FIXME Remove on 2.1 release
  1840. if (std::strcmp(stateSave.type, "GIG") == 0)
  1841. {
  1842. if (addPlugin(PLUGIN_LV2, "", stateSave.name, "http://linuxsampler.org/plugins/linuxsampler", 0, nullptr))
  1843. {
  1844. const uint pluginId = pData->curPluginCount;
  1845. if (CarlaPlugin* const plugin = pData->plugins[pluginId].plugin)
  1846. {
  1847. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  1848. if (pData->aboutToClose)
  1849. return true;
  1850. if (pData->actionCanceled)
  1851. {
  1852. setLastError("Project load canceled");
  1853. return false;
  1854. }
  1855. String lsState;
  1856. lsState << "0.35\n";
  1857. lsState << "18 0 Chromatic\n";
  1858. lsState << "18 1 Drum Kits\n";
  1859. lsState << "20 0\n";
  1860. lsState << "0 1 " << stateSave.binary << "\n";
  1861. lsState << "0 0 0 0 1 0 GIG\n";
  1862. plugin->setCustomData(LV2_ATOM__String, "http://linuxsampler.org/schema#state-string", lsState.toRawUTF8(), true);
  1863. plugin->restoreLV2State();
  1864. plugin->setDryWet(stateSave.dryWet, true, true);
  1865. plugin->setVolume(stateSave.volume, true, true);
  1866. plugin->setBalanceLeft(stateSave.balanceLeft, true, true);
  1867. plugin->setBalanceRight(stateSave.balanceRight, true, true);
  1868. plugin->setPanning(stateSave.panning, true, true);
  1869. plugin->setCtrlChannel(stateSave.ctrlChannel, true, true);
  1870. plugin->setActive(stateSave.active, true, true);
  1871. ++pData->curPluginCount;
  1872. plugin->setEnabled(true);
  1873. callback(ENGINE_CALLBACK_PLUGIN_ADDED, pluginId, 0, 0, 0.0f, plugin->getName());
  1874. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1875. pData->graph.addPlugin(plugin);
  1876. }
  1877. else
  1878. {
  1879. carla_stderr2("Failed to get new plugin, state will not be restored correctly\n");
  1880. }
  1881. }
  1882. else
  1883. {
  1884. carla_stderr2("Failed to load a linuxsampler LV2 plugin, GIG file won't be loaded");
  1885. }
  1886. continue;
  1887. }
  1888. #endif
  1889. const void* extraStuff = nullptr;
  1890. static const char kTrue[] = "true";
  1891. const PluginType ptype(getPluginTypeFromString(stateSave.type));
  1892. switch (ptype)
  1893. {
  1894. case PLUGIN_SF2:
  1895. if (CarlaString(stateSave.label).endsWith(" (16 outs)"))
  1896. extraStuff = kTrue;
  1897. // fall through
  1898. case PLUGIN_LADSPA:
  1899. case PLUGIN_DSSI:
  1900. case PLUGIN_VST2:
  1901. case PLUGIN_VST3:
  1902. case PLUGIN_SFZ:
  1903. if (stateSave.binary != nullptr && stateSave.binary[0] != '\0' &&
  1904. ! (File::isAbsolutePath(stateSave.binary) && File(stateSave.binary).exists()))
  1905. {
  1906. const char* searchPath;
  1907. switch (ptype)
  1908. {
  1909. case PLUGIN_LADSPA: searchPath = pData->options.pathLADSPA; break;
  1910. case PLUGIN_DSSI: searchPath = pData->options.pathDSSI; break;
  1911. case PLUGIN_VST2: searchPath = pData->options.pathVST2; break;
  1912. case PLUGIN_VST3: searchPath = pData->options.pathVST3; break;
  1913. case PLUGIN_SF2: searchPath = pData->options.pathSF2; break;
  1914. case PLUGIN_SFZ: searchPath = pData->options.pathSFZ; break;
  1915. default: searchPath = nullptr; break;
  1916. }
  1917. if (searchPath != nullptr && searchPath[0] != '\0')
  1918. {
  1919. carla_stderr("Plugin binary '%s' doesn't exist on this filesystem, let's look for it...",
  1920. stateSave.binary);
  1921. String result = findBinaryInCustomPath(searchPath, stateSave.binary);
  1922. if (result.isEmpty())
  1923. {
  1924. switch (ptype)
  1925. {
  1926. case PLUGIN_LADSPA: searchPath = std::getenv("LADSPA_PATH"); break;
  1927. case PLUGIN_DSSI: searchPath = std::getenv("DSSI_PATH"); break;
  1928. case PLUGIN_VST2: searchPath = std::getenv("VST_PATH"); break;
  1929. case PLUGIN_VST3: searchPath = std::getenv("VST3_PATH"); break;
  1930. case PLUGIN_SF2: searchPath = std::getenv("SF2_PATH"); break;
  1931. case PLUGIN_SFZ: searchPath = std::getenv("SFZ_PATH"); break;
  1932. default: searchPath = nullptr; break;
  1933. }
  1934. if (searchPath != nullptr && searchPath[0] != '\0')
  1935. result = findBinaryInCustomPath(searchPath, stateSave.binary);
  1936. }
  1937. if (result.isNotEmpty())
  1938. {
  1939. delete[] stateSave.binary;
  1940. stateSave.binary = carla_strdup(result.toRawUTF8());
  1941. carla_stderr("Found it! :)");
  1942. }
  1943. else
  1944. {
  1945. carla_stderr("Damn, we failed... :(");
  1946. }
  1947. }
  1948. }
  1949. break;
  1950. default:
  1951. break;
  1952. }
  1953. BinaryType btype;
  1954. switch (ptype)
  1955. {
  1956. case PLUGIN_LADSPA:
  1957. case PLUGIN_DSSI:
  1958. case PLUGIN_LV2:
  1959. case PLUGIN_VST2:
  1960. btype = getBinaryTypeFromFile(stateSave.binary);
  1961. break;
  1962. default:
  1963. btype = BINARY_NATIVE;
  1964. break;
  1965. }
  1966. if (addPlugin(btype, ptype, stateSave.binary,
  1967. stateSave.name, stateSave.label, stateSave.uniqueId, extraStuff, stateSave.options))
  1968. {
  1969. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1970. const uint pluginId = pData->curPluginCount;
  1971. #else
  1972. const uint pluginId = 0;
  1973. #endif
  1974. if (CarlaPlugin* const plugin = pData->plugins[pluginId].plugin)
  1975. {
  1976. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  1977. if (pData->aboutToClose)
  1978. return true;
  1979. if (pData->actionCanceled)
  1980. {
  1981. setLastError("Project load canceled");
  1982. return false;
  1983. }
  1984. // deactivate bridge client-side ping check, since some plugins block during load
  1985. if ((plugin->getHints() & PLUGIN_IS_BRIDGE) != 0 && ! isPreset)
  1986. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "false", false);
  1987. plugin->loadStateSave(stateSave);
  1988. /* NOTE: The following code is the same as the end of addPlugin().
  1989. * When project is loading we do not enable the plugin right away,
  1990. * as we want to load state first.
  1991. */
  1992. plugin->setEnabled(true);
  1993. ++pData->curPluginCount;
  1994. callback(ENGINE_CALLBACK_PLUGIN_ADDED, pluginId, 0, 0, 0.0f, plugin->getName());
  1995. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1996. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1997. pData->graph.addPlugin(plugin);
  1998. #endif
  1999. }
  2000. else
  2001. {
  2002. carla_stderr2("Failed to get new plugin, state will not be restored correctly\n");
  2003. }
  2004. }
  2005. else
  2006. {
  2007. carla_stderr2("Failed to load a plugin '%s', error was:\n%s", stateSave.name, getLastError());
  2008. }
  2009. }
  2010. if (isPreset)
  2011. {
  2012. callback(ENGINE_CALLBACK_PROJECT_LOAD_FINISHED, 0, 0, 0, 0.0f, nullptr);
  2013. callback(ENGINE_CALLBACK_CANCELABLE_ACTION, 0, 0, 0, 0.0f, "Loading project");
  2014. return true;
  2015. }
  2016. }
  2017. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2018. // tell bridges we're done loading
  2019. for (uint i=0; i < pData->curPluginCount; ++i)
  2020. {
  2021. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  2022. if (plugin != nullptr && plugin->isEnabled() && (plugin->getHints() & PLUGIN_IS_BRIDGE) != 0)
  2023. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "true", false);
  2024. }
  2025. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  2026. if (pData->aboutToClose)
  2027. return true;
  2028. if (pData->actionCanceled)
  2029. {
  2030. setLastError("Project load canceled");
  2031. return false;
  2032. }
  2033. bool hasInternalConnections = false;
  2034. // and now we handle connections (internal)
  2035. if (XmlElement* const elem = xmlElement->getChildByName("Patchbay"))
  2036. {
  2037. hasInternalConnections = true;
  2038. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  2039. {
  2040. CarlaString sourcePort, targetPort;
  2041. const bool isUsingExternal(pData->graph.isUsingExternal());
  2042. for (XmlElement* patchElem = elem->getFirstChildElement(); patchElem != nullptr; patchElem = patchElem->getNextElement())
  2043. {
  2044. const String& patchTag(patchElem->getTagName());
  2045. if (patchTag != "Connection")
  2046. continue;
  2047. sourcePort.clear();
  2048. targetPort.clear();
  2049. for (XmlElement* connElem = patchElem->getFirstChildElement(); connElem != nullptr; connElem = connElem->getNextElement())
  2050. {
  2051. const String& tag(connElem->getTagName());
  2052. const String text(connElem->getAllSubText().trim());
  2053. /**/ if (tag == "Source")
  2054. sourcePort = xmlSafeString(text, false).toRawUTF8();
  2055. else if (tag == "Target")
  2056. targetPort = xmlSafeString(text, false).toRawUTF8();
  2057. }
  2058. if (sourcePort.isNotEmpty() && targetPort.isNotEmpty())
  2059. restorePatchbayConnection(false, sourcePort, targetPort, !isUsingExternal);
  2060. }
  2061. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  2062. if (pData->aboutToClose)
  2063. return true;
  2064. if (pData->actionCanceled)
  2065. {
  2066. setLastError("Project load canceled");
  2067. return false;
  2068. }
  2069. }
  2070. }
  2071. // if we're running inside some session-manager (and using JACK), let them handle the external connections
  2072. bool loadExternalConnections;
  2073. /**/ if (std::strcmp(getCurrentDriverName(), "JACK") != 0)
  2074. loadExternalConnections = true;
  2075. else if (std::getenv("CARLA_DONT_MANAGE_CONNECTIONS") != nullptr)
  2076. loadExternalConnections = false;
  2077. else if (std::getenv("LADISH_APP_NAME") != nullptr)
  2078. loadExternalConnections = false;
  2079. else if (std::getenv("NSM_URL") != nullptr)
  2080. loadExternalConnections = false;
  2081. else
  2082. loadExternalConnections = true;
  2083. // plus external connections too
  2084. if (loadExternalConnections)
  2085. {
  2086. const bool isUsingExternal = pData->options.processMode != ENGINE_PROCESS_MODE_PATCHBAY ||
  2087. pData->graph.isUsingExternal();
  2088. const bool loadingAsExternal = pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY &&
  2089. hasInternalConnections;
  2090. for (XmlElement* elem = xmlElement->getFirstChildElement(); elem != nullptr; elem = elem->getNextElement())
  2091. {
  2092. const String& tagName(elem->getTagName());
  2093. // check if we want to load patchbay-mode connections into an external (multi-client) graph
  2094. if (tagName == "Patchbay")
  2095. {
  2096. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  2097. continue;
  2098. }
  2099. // or load external patchbay connections
  2100. else if (tagName != "ExternalPatchbay")
  2101. {
  2102. continue;
  2103. }
  2104. CarlaString sourcePort, targetPort;
  2105. for (XmlElement* patchElem = elem->getFirstChildElement(); patchElem != nullptr; patchElem = patchElem->getNextElement())
  2106. {
  2107. const String& patchTag(patchElem->getTagName());
  2108. if (patchTag != "Connection")
  2109. continue;
  2110. sourcePort.clear();
  2111. targetPort.clear();
  2112. for (XmlElement* connElem = patchElem->getFirstChildElement(); connElem != nullptr; connElem = connElem->getNextElement())
  2113. {
  2114. const String& tag(connElem->getTagName());
  2115. const String text(connElem->getAllSubText().trim());
  2116. /**/ if (tag == "Source")
  2117. sourcePort = xmlSafeString(text, false).toRawUTF8();
  2118. else if (tag == "Target")
  2119. targetPort = xmlSafeString(text, false).toRawUTF8();
  2120. }
  2121. if (sourcePort.isNotEmpty() && targetPort.isNotEmpty())
  2122. restorePatchbayConnection(loadingAsExternal, sourcePort, targetPort, isUsingExternal);
  2123. }
  2124. break;
  2125. }
  2126. }
  2127. #endif
  2128. callback(ENGINE_CALLBACK_PROJECT_LOAD_FINISHED, 0, 0, 0, 0.0f, nullptr);
  2129. callback(ENGINE_CALLBACK_CANCELABLE_ACTION, 0, 0, 0, 0.0f, "Loading project");
  2130. return true;
  2131. }
  2132. // -----------------------------------------------------------------------
  2133. CARLA_BACKEND_END_NAMESPACE