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.

2648 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, false);
  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, const bool setAsCurrentProject)
  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. if (setAsCurrentProject)
  921. {
  922. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  923. pData->currentProjectFilename = filename;
  924. #endif
  925. }
  926. XmlDocument xml(file);
  927. return loadProjectInternal(xml);
  928. }
  929. bool CarlaEngine::saveProject(const char* const filename, const bool setAsCurrentProject)
  930. {
  931. CARLA_SAFE_ASSERT_RETURN_ERR(filename != nullptr && filename[0] != '\0', "Invalid filename");
  932. carla_debug("CarlaEngine::saveProject(\"%s\")", filename);
  933. MemoryOutputStream out;
  934. saveProjectInternal(out);
  935. const String jfilename = String(CharPointer_UTF8(filename));
  936. File file(jfilename);
  937. if (setAsCurrentProject)
  938. {
  939. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  940. pData->currentProjectFilename = filename;
  941. #endif
  942. }
  943. if (file.replaceWithData(out.getData(), out.getDataSize()))
  944. return true;
  945. setLastError("Failed to write file");
  946. return false;
  947. }
  948. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  949. const char* CarlaEngine::getCurrentProjectFilename() const noexcept
  950. {
  951. return pData->currentProjectFilename;
  952. }
  953. void CarlaEngine::clearCurrentProjectFilename() noexcept
  954. {
  955. pData->currentProjectFilename.clear();
  956. }
  957. #endif
  958. // -----------------------------------------------------------------------
  959. // Information (base)
  960. uint CarlaEngine::getHints() const noexcept
  961. {
  962. return pData->hints;
  963. }
  964. uint32_t CarlaEngine::getBufferSize() const noexcept
  965. {
  966. return pData->bufferSize;
  967. }
  968. double CarlaEngine::getSampleRate() const noexcept
  969. {
  970. return pData->sampleRate;
  971. }
  972. const char* CarlaEngine::getName() const noexcept
  973. {
  974. return pData->name;
  975. }
  976. EngineProcessMode CarlaEngine::getProccessMode() const noexcept
  977. {
  978. return pData->options.processMode;
  979. }
  980. const EngineOptions& CarlaEngine::getOptions() const noexcept
  981. {
  982. return pData->options;
  983. }
  984. EngineTimeInfo CarlaEngine::getTimeInfo() const noexcept
  985. {
  986. return pData->timeInfo;
  987. }
  988. // -----------------------------------------------------------------------
  989. // Information (peaks)
  990. float* CarlaEngine::getPeaks(const uint pluginId) const noexcept
  991. {
  992. carla_zeroFloats(pData->peaks, 4);
  993. if (pluginId == MAIN_CARLA_PLUGIN_ID)
  994. {
  995. // get peak from first plugin, if available
  996. if (const uint count = pData->curPluginCount)
  997. {
  998. pData->peaks[0] = pData->plugins[0].peaks[0];
  999. pData->peaks[1] = pData->plugins[0].peaks[1];
  1000. pData->peaks[2] = pData->plugins[count-1].peaks[2];
  1001. pData->peaks[3] = pData->plugins[count-1].peaks[3];
  1002. }
  1003. return pData->peaks;
  1004. }
  1005. CARLA_SAFE_ASSERT_RETURN(pluginId < pData->curPluginCount, pData->peaks);
  1006. return pData->plugins[pluginId].peaks;
  1007. }
  1008. float CarlaEngine::getInputPeak(const uint pluginId, const bool isLeft) const noexcept
  1009. {
  1010. if (pluginId == MAIN_CARLA_PLUGIN_ID)
  1011. {
  1012. // get peak from first plugin, if available
  1013. if (pData->curPluginCount > 0)
  1014. return pData->plugins[0].peaks[isLeft ? 0 : 1];
  1015. return 0.0f;
  1016. }
  1017. CARLA_SAFE_ASSERT_RETURN(pluginId < pData->curPluginCount, 0.0f);
  1018. return pData->plugins[pluginId].peaks[isLeft ? 0 : 1];
  1019. }
  1020. float CarlaEngine::getOutputPeak(const uint pluginId, const bool isLeft) const noexcept
  1021. {
  1022. if (pluginId == MAIN_CARLA_PLUGIN_ID)
  1023. {
  1024. // get peak from last plugin, if available
  1025. if (pData->curPluginCount > 0)
  1026. return pData->plugins[pData->curPluginCount-1].peaks[isLeft ? 2 : 3];
  1027. return 0.0f;
  1028. }
  1029. CARLA_SAFE_ASSERT_RETURN(pluginId < pData->curPluginCount, 0.0f);
  1030. return pData->plugins[pluginId].peaks[isLeft ? 2 : 3];
  1031. }
  1032. // -----------------------------------------------------------------------
  1033. // Callback
  1034. void CarlaEngine::callback(const EngineCallbackOpcode action, const uint pluginId, const int value1, const int value2, const float value3, const char* const valueStr) noexcept
  1035. {
  1036. #ifdef DEBUG
  1037. if (pData->isIdling)
  1038. carla_stdout("CarlaEngine::callback [while idling] (%i:%s, %i, %i, %i, %f, \"%s\")",
  1039. action, EngineCallbackOpcode2Str(action), pluginId, value1, value2, value3, valueStr);
  1040. else if (action != ENGINE_CALLBACK_IDLE && action != ENGINE_CALLBACK_NOTE_ON && action != ENGINE_CALLBACK_NOTE_OFF)
  1041. carla_debug("CarlaEngine::callback(%i:%s, %i, %i, %i, %f, \"%s\")",
  1042. action, EngineCallbackOpcode2Str(action), pluginId, value1, value2, value3, valueStr);
  1043. #endif
  1044. if (pData->callback != nullptr)
  1045. {
  1046. if (action == ENGINE_CALLBACK_IDLE)
  1047. ++pData->isIdling;
  1048. try {
  1049. pData->callback(pData->callbackPtr, action, pluginId, value1, value2, value3, valueStr);
  1050. #if defined(CARLA_OS_LINUX) && defined(__arm__)
  1051. } catch (__cxxabiv1::__forced_unwind&) {
  1052. carla_stderr2("Caught forced unwind exception in callback");
  1053. throw;
  1054. #endif
  1055. } catch (...) {
  1056. carla_safe_exception("callback", __FILE__, __LINE__);
  1057. }
  1058. if (action == ENGINE_CALLBACK_IDLE)
  1059. --pData->isIdling;
  1060. }
  1061. }
  1062. void CarlaEngine::setCallback(const EngineCallbackFunc func, void* const ptr) noexcept
  1063. {
  1064. carla_debug("CarlaEngine::setCallback(%p, %p)", func, ptr);
  1065. pData->callback = func;
  1066. pData->callbackPtr = ptr;
  1067. }
  1068. // -----------------------------------------------------------------------
  1069. // File Callback
  1070. const char* CarlaEngine::runFileCallback(const FileCallbackOpcode action, const bool isDir, const char* const title, const char* const filter) noexcept
  1071. {
  1072. CARLA_SAFE_ASSERT_RETURN(title != nullptr && title[0] != '\0', nullptr);
  1073. CARLA_SAFE_ASSERT_RETURN(filter != nullptr, nullptr);
  1074. carla_debug("CarlaEngine::runFileCallback(%i:%s, %s, \"%s\", \"%s\")", action, FileCallbackOpcode2Str(action), bool2str(isDir), title, filter);
  1075. const char* ret = nullptr;
  1076. if (pData->fileCallback != nullptr)
  1077. {
  1078. try {
  1079. ret = pData->fileCallback(pData->fileCallbackPtr, action, isDir, title, filter);
  1080. } CARLA_SAFE_EXCEPTION("runFileCallback");
  1081. }
  1082. return ret;
  1083. }
  1084. void CarlaEngine::setFileCallback(const FileCallbackFunc func, void* const ptr) noexcept
  1085. {
  1086. carla_debug("CarlaEngine::setFileCallback(%p, %p)", func, ptr);
  1087. pData->fileCallback = func;
  1088. pData->fileCallbackPtr = ptr;
  1089. }
  1090. // -----------------------------------------------------------------------
  1091. // Transport
  1092. void CarlaEngine::transportPlay() noexcept
  1093. {
  1094. pData->timeInfo.playing = true;
  1095. pData->time.setNeedsReset();
  1096. }
  1097. void CarlaEngine::transportPause() noexcept
  1098. {
  1099. if (pData->timeInfo.playing)
  1100. pData->time.pause();
  1101. else
  1102. pData->time.setNeedsReset();
  1103. }
  1104. void CarlaEngine::transportBPM(const double bpm) noexcept
  1105. {
  1106. try {
  1107. pData->time.setBPM(bpm);
  1108. } CARLA_SAFE_EXCEPTION("CarlaEngine::transportBPM");
  1109. }
  1110. void CarlaEngine::transportRelocate(const uint64_t frame) noexcept
  1111. {
  1112. pData->time.relocate(frame);
  1113. }
  1114. // -----------------------------------------------------------------------
  1115. // Error handling
  1116. const char* CarlaEngine::getLastError() const noexcept
  1117. {
  1118. return pData->lastError;
  1119. }
  1120. void CarlaEngine::setLastError(const char* const error) const noexcept
  1121. {
  1122. pData->lastError = error;
  1123. }
  1124. // -----------------------------------------------------------------------
  1125. // Misc
  1126. bool CarlaEngine::isAboutToClose() const noexcept
  1127. {
  1128. return pData->aboutToClose;
  1129. }
  1130. bool CarlaEngine::setAboutToClose() noexcept
  1131. {
  1132. carla_debug("CarlaEngine::setAboutToClose()");
  1133. pData->aboutToClose = true;
  1134. return (pData->isIdling == 0);
  1135. }
  1136. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1137. bool CarlaEngine::isLoadingProject() const noexcept
  1138. {
  1139. return pData->loadingProject;
  1140. }
  1141. #endif
  1142. void CarlaEngine::setActionCanceled(const bool canceled) noexcept
  1143. {
  1144. pData->actionCanceled = canceled;
  1145. }
  1146. bool CarlaEngine::wasActionCanceled() const noexcept
  1147. {
  1148. return pData->actionCanceled;
  1149. }
  1150. // -----------------------------------------------------------------------
  1151. // Global options
  1152. void CarlaEngine::setOption(const EngineOption option, const int value, const char* const valueStr) noexcept
  1153. {
  1154. carla_debug("CarlaEngine::setOption(%i:%s, %i, \"%s\")", option, EngineOption2Str(option), value, valueStr);
  1155. if (isRunning())
  1156. {
  1157. switch (option)
  1158. {
  1159. case ENGINE_OPTION_PROCESS_MODE:
  1160. case ENGINE_OPTION_AUDIO_TRIPLE_BUFFER:
  1161. case ENGINE_OPTION_AUDIO_DEVICE:
  1162. return carla_stderr("CarlaEngine::setOption(%i:%s, %i, \"%s\") - Cannot set this option while engine is running!",
  1163. option, EngineOption2Str(option), value, valueStr);
  1164. default:
  1165. break;
  1166. }
  1167. }
  1168. // do not un-force stereo for rack mode
  1169. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK && option == ENGINE_OPTION_FORCE_STEREO && value != 0)
  1170. return;
  1171. switch (option)
  1172. {
  1173. case ENGINE_OPTION_DEBUG:
  1174. break;
  1175. case ENGINE_OPTION_PROCESS_MODE:
  1176. CARLA_SAFE_ASSERT_RETURN(value >= ENGINE_PROCESS_MODE_SINGLE_CLIENT && value <= ENGINE_PROCESS_MODE_BRIDGE,);
  1177. pData->options.processMode = static_cast<EngineProcessMode>(value);
  1178. break;
  1179. case ENGINE_OPTION_TRANSPORT_MODE:
  1180. CARLA_SAFE_ASSERT_RETURN(value >= ENGINE_TRANSPORT_MODE_DISABLED && value <= ENGINE_TRANSPORT_MODE_BRIDGE,);
  1181. CARLA_SAFE_ASSERT_RETURN(getType() == kEngineTypeJack || value != ENGINE_TRANSPORT_MODE_JACK,);
  1182. pData->options.transportMode = static_cast<EngineTransportMode>(value);
  1183. delete[] pData->options.transportExtra;
  1184. if (value >= ENGINE_TRANSPORT_MODE_DISABLED && valueStr != nullptr)
  1185. pData->options.transportExtra = carla_strdup_safe(valueStr);
  1186. else
  1187. pData->options.transportExtra = nullptr;
  1188. pData->time.setNeedsReset();
  1189. #if defined(HAVE_HYLIA) && !defined(BUILD_BRIDGE)
  1190. // enable link now if needed
  1191. {
  1192. const bool linkEnabled = pData->options.transportExtra != nullptr && std::strstr(pData->options.transportExtra, ":link:") != nullptr;
  1193. pData->time.enableLink(linkEnabled);
  1194. }
  1195. #endif
  1196. break;
  1197. case ENGINE_OPTION_FORCE_STEREO:
  1198. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1199. pData->options.forceStereo = (value != 0);
  1200. break;
  1201. case ENGINE_OPTION_PREFER_PLUGIN_BRIDGES:
  1202. #ifdef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1203. CARLA_SAFE_ASSERT_RETURN(value == 0,);
  1204. #else
  1205. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1206. #endif
  1207. pData->options.preferPluginBridges = (value != 0);
  1208. break;
  1209. case ENGINE_OPTION_PREFER_UI_BRIDGES:
  1210. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1211. pData->options.preferUiBridges = (value != 0);
  1212. break;
  1213. case ENGINE_OPTION_UIS_ALWAYS_ON_TOP:
  1214. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1215. pData->options.uisAlwaysOnTop = (value != 0);
  1216. break;
  1217. case ENGINE_OPTION_MAX_PARAMETERS:
  1218. CARLA_SAFE_ASSERT_RETURN(value >= 0,);
  1219. pData->options.maxParameters = static_cast<uint>(value);
  1220. break;
  1221. case ENGINE_OPTION_UI_BRIDGES_TIMEOUT:
  1222. CARLA_SAFE_ASSERT_RETURN(value >= 0,);
  1223. pData->options.uiBridgesTimeout = static_cast<uint>(value);
  1224. break;
  1225. case ENGINE_OPTION_AUDIO_BUFFER_SIZE:
  1226. CARLA_SAFE_ASSERT_RETURN(value >= 8,);
  1227. pData->options.audioBufferSize = static_cast<uint>(value);
  1228. break;
  1229. case ENGINE_OPTION_AUDIO_SAMPLE_RATE:
  1230. CARLA_SAFE_ASSERT_RETURN(value >= 22050,);
  1231. pData->options.audioSampleRate = static_cast<uint>(value);
  1232. break;
  1233. case ENGINE_OPTION_AUDIO_TRIPLE_BUFFER:
  1234. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1235. pData->options.audioTripleBuffer = (value != 0);
  1236. break;
  1237. case ENGINE_OPTION_AUDIO_DEVICE:
  1238. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr,);
  1239. if (pData->options.audioDevice != nullptr)
  1240. delete[] pData->options.audioDevice;
  1241. pData->options.audioDevice = carla_strdup_safe(valueStr);
  1242. break;
  1243. case ENGINE_OPTION_PLUGIN_PATH:
  1244. CARLA_SAFE_ASSERT_RETURN(value > PLUGIN_NONE,);
  1245. CARLA_SAFE_ASSERT_RETURN(value <= PLUGIN_SFZ,);
  1246. switch (value)
  1247. {
  1248. case PLUGIN_LADSPA:
  1249. if (pData->options.pathLADSPA != nullptr)
  1250. delete[] pData->options.pathLADSPA;
  1251. if (valueStr != nullptr)
  1252. pData->options.pathLADSPA = carla_strdup_safe(valueStr);
  1253. else
  1254. pData->options.pathLADSPA = nullptr;
  1255. break;
  1256. case PLUGIN_DSSI:
  1257. if (pData->options.pathDSSI != nullptr)
  1258. delete[] pData->options.pathDSSI;
  1259. if (valueStr != nullptr)
  1260. pData->options.pathDSSI = carla_strdup_safe(valueStr);
  1261. else
  1262. pData->options.pathDSSI = nullptr;
  1263. break;
  1264. case PLUGIN_LV2:
  1265. if (pData->options.pathLV2 != nullptr)
  1266. delete[] pData->options.pathLV2;
  1267. if (valueStr != nullptr)
  1268. pData->options.pathLV2 = carla_strdup_safe(valueStr);
  1269. else
  1270. pData->options.pathLV2 = nullptr;
  1271. break;
  1272. case PLUGIN_VST2:
  1273. if (pData->options.pathVST2 != nullptr)
  1274. delete[] pData->options.pathVST2;
  1275. if (valueStr != nullptr)
  1276. pData->options.pathVST2 = carla_strdup_safe(valueStr);
  1277. else
  1278. pData->options.pathVST2 = nullptr;
  1279. break;
  1280. case PLUGIN_VST3:
  1281. if (pData->options.pathVST3 != nullptr)
  1282. delete[] pData->options.pathVST3;
  1283. if (valueStr != nullptr)
  1284. pData->options.pathVST3 = carla_strdup_safe(valueStr);
  1285. else
  1286. pData->options.pathVST3 = nullptr;
  1287. break;
  1288. case PLUGIN_SF2:
  1289. if (pData->options.pathSF2 != nullptr)
  1290. delete[] pData->options.pathSF2;
  1291. if (valueStr != nullptr)
  1292. pData->options.pathSF2 = carla_strdup_safe(valueStr);
  1293. else
  1294. pData->options.pathSF2 = nullptr;
  1295. break;
  1296. case PLUGIN_SFZ:
  1297. if (pData->options.pathSFZ != nullptr)
  1298. delete[] pData->options.pathSFZ;
  1299. if (valueStr != nullptr)
  1300. pData->options.pathSFZ = carla_strdup_safe(valueStr);
  1301. else
  1302. pData->options.pathSFZ = nullptr;
  1303. break;
  1304. default:
  1305. return carla_stderr("CarlaEngine::setOption(%i:%s, %i, \"%s\") - Invalid plugin type", option, EngineOption2Str(option), value, valueStr);
  1306. break;
  1307. }
  1308. break;
  1309. case ENGINE_OPTION_PATH_BINARIES:
  1310. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1311. if (pData->options.binaryDir != nullptr)
  1312. delete[] pData->options.binaryDir;
  1313. pData->options.binaryDir = carla_strdup_safe(valueStr);
  1314. break;
  1315. case ENGINE_OPTION_PATH_RESOURCES:
  1316. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1317. if (pData->options.resourceDir != nullptr)
  1318. delete[] pData->options.resourceDir;
  1319. pData->options.resourceDir = carla_strdup_safe(valueStr);
  1320. break;
  1321. case ENGINE_OPTION_PREVENT_BAD_BEHAVIOUR: {
  1322. CARLA_SAFE_ASSERT_RETURN(pData->options.binaryDir != nullptr && pData->options.binaryDir[0] != '\0',);
  1323. #ifdef CARLA_OS_LINUX
  1324. const ScopedEngineEnvironmentLocker _seel(this);
  1325. if (value != 0)
  1326. {
  1327. CarlaString interposerPath(CarlaString(pData->options.binaryDir) + "/libcarla_interposer-safe.so");
  1328. ::setenv("LD_PRELOAD", interposerPath.buffer(), 1);
  1329. }
  1330. else
  1331. {
  1332. ::unsetenv("LD_PRELOAD");
  1333. }
  1334. #endif
  1335. } break;
  1336. case ENGINE_OPTION_FRONTEND_WIN_ID: {
  1337. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1338. const long long winId(std::strtoll(valueStr, nullptr, 16));
  1339. CARLA_SAFE_ASSERT_RETURN(winId >= 0,);
  1340. pData->options.frontendWinId = static_cast<uintptr_t>(winId);
  1341. } break;
  1342. #if !defined(BUILD_BRIDGE_ALTERNATIVE_ARCH) && !defined(CARLA_OS_WIN)
  1343. case ENGINE_OPTION_WINE_EXECUTABLE:
  1344. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1345. if (pData->options.wine.executable != nullptr)
  1346. delete[] pData->options.wine.executable;
  1347. pData->options.wine.executable = carla_strdup_safe(valueStr);
  1348. break;
  1349. case ENGINE_OPTION_WINE_AUTO_PREFIX:
  1350. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1351. pData->options.wine.autoPrefix = (value != 0);
  1352. break;
  1353. case ENGINE_OPTION_WINE_FALLBACK_PREFIX:
  1354. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1355. if (pData->options.wine.fallbackPrefix != nullptr)
  1356. delete[] pData->options.wine.fallbackPrefix;
  1357. pData->options.wine.fallbackPrefix = carla_strdup_safe(valueStr);
  1358. break;
  1359. case ENGINE_OPTION_WINE_RT_PRIO_ENABLED:
  1360. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1361. pData->options.wine.rtPrio = (value != 0);
  1362. break;
  1363. case ENGINE_OPTION_WINE_BASE_RT_PRIO:
  1364. CARLA_SAFE_ASSERT_RETURN(value >= 1 && value <= 89,);
  1365. pData->options.wine.baseRtPrio = value;
  1366. break;
  1367. case ENGINE_OPTION_WINE_SERVER_RT_PRIO:
  1368. CARLA_SAFE_ASSERT_RETURN(value >= 1 && value <= 99,);
  1369. pData->options.wine.serverRtPrio = value;
  1370. break;
  1371. #endif
  1372. case ENGINE_OPTION_DEBUG_CONSOLE_OUTPUT:
  1373. break;
  1374. }
  1375. }
  1376. #ifndef BUILD_BRIDGE
  1377. // -----------------------------------------------------------------------
  1378. // OSC Stuff
  1379. bool CarlaEngine::isOscControlRegistered() const noexcept
  1380. {
  1381. # ifdef HAVE_LIBLO
  1382. return pData->osc.isControlRegistered();
  1383. # else
  1384. return false;
  1385. # endif
  1386. }
  1387. void CarlaEngine::idleOsc() const noexcept
  1388. {
  1389. # ifdef HAVE_LIBLO
  1390. pData->osc.idle();
  1391. # endif
  1392. }
  1393. const char* CarlaEngine::getOscServerPathTCP() const noexcept
  1394. {
  1395. # ifdef HAVE_LIBLO
  1396. return pData->osc.getServerPathTCP();
  1397. # else
  1398. return nullptr;
  1399. # endif
  1400. }
  1401. const char* CarlaEngine::getOscServerPathUDP() const noexcept
  1402. {
  1403. # ifdef HAVE_LIBLO
  1404. return pData->osc.getServerPathUDP();
  1405. # else
  1406. return nullptr;
  1407. # endif
  1408. }
  1409. #endif
  1410. // -----------------------------------------------------------------------
  1411. // Helper functions
  1412. EngineEvent* CarlaEngine::getInternalEventBuffer(const bool isInput) const noexcept
  1413. {
  1414. return isInput ? pData->events.in : pData->events.out;
  1415. }
  1416. // -----------------------------------------------------------------------
  1417. // Internal stuff
  1418. void CarlaEngine::bufferSizeChanged(const uint32_t newBufferSize)
  1419. {
  1420. carla_debug("CarlaEngine::bufferSizeChanged(%i)", newBufferSize);
  1421. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1422. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1423. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1424. {
  1425. pData->graph.setBufferSize(newBufferSize);
  1426. }
  1427. #endif
  1428. pData->time.updateAudioValues(newBufferSize, pData->sampleRate);
  1429. for (uint i=0; i < pData->curPluginCount; ++i)
  1430. {
  1431. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1432. if (plugin != nullptr && plugin->isEnabled())
  1433. {
  1434. plugin->tryLock(true);
  1435. plugin->bufferSizeChanged(newBufferSize);
  1436. plugin->unlock();
  1437. }
  1438. }
  1439. callback(ENGINE_CALLBACK_BUFFER_SIZE_CHANGED, 0, static_cast<int>(newBufferSize), 0, 0.0f, nullptr);
  1440. }
  1441. void CarlaEngine::sampleRateChanged(const double newSampleRate)
  1442. {
  1443. carla_debug("CarlaEngine::sampleRateChanged(%g)", newSampleRate);
  1444. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1445. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1446. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1447. {
  1448. pData->graph.setSampleRate(newSampleRate);
  1449. }
  1450. #endif
  1451. pData->time.updateAudioValues(pData->bufferSize, newSampleRate);
  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. {
  1457. plugin->tryLock(true);
  1458. plugin->sampleRateChanged(newSampleRate);
  1459. plugin->unlock();
  1460. }
  1461. }
  1462. callback(ENGINE_CALLBACK_SAMPLE_RATE_CHANGED, 0, 0, 0, static_cast<float>(newSampleRate), nullptr);
  1463. }
  1464. void CarlaEngine::offlineModeChanged(const bool isOfflineNow)
  1465. {
  1466. carla_debug("CarlaEngine::offlineModeChanged(%s)", bool2str(isOfflineNow));
  1467. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1468. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK ||
  1469. pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1470. {
  1471. pData->graph.setOffline(isOfflineNow);
  1472. }
  1473. #endif
  1474. for (uint i=0; i < pData->curPluginCount; ++i)
  1475. {
  1476. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1477. if (plugin != nullptr && plugin->isEnabled())
  1478. plugin->offlineModeChanged(isOfflineNow);
  1479. }
  1480. }
  1481. void CarlaEngine::setPluginPeaks(const uint pluginId, float const inPeaks[2], float const outPeaks[2]) noexcept
  1482. {
  1483. EnginePluginData& pluginData(pData->plugins[pluginId]);
  1484. pluginData.peaks[0] = inPeaks[0];
  1485. pluginData.peaks[1] = inPeaks[1];
  1486. pluginData.peaks[2] = outPeaks[0];
  1487. pluginData.peaks[3] = outPeaks[1];
  1488. }
  1489. void CarlaEngine::saveProjectInternal(water::MemoryOutputStream& outStream) const
  1490. {
  1491. // send initial prepareForSave first, giving time for bridges to act
  1492. for (uint i=0; i < pData->curPluginCount; ++i)
  1493. {
  1494. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1495. if (plugin != nullptr && plugin->isEnabled())
  1496. {
  1497. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1498. // deactivate bridge client-side ping check, since some plugins block during save
  1499. if (plugin->getHints() & PLUGIN_IS_BRIDGE)
  1500. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "false", false);
  1501. #endif
  1502. plugin->prepareForSave();
  1503. }
  1504. }
  1505. outStream << "<?xml version='1.0' encoding='UTF-8'?>\n";
  1506. outStream << "<!DOCTYPE CARLA-PROJECT>\n";
  1507. outStream << "<CARLA-PROJECT VERSION='2.0'>\n";
  1508. const bool isPlugin(getType() == kEngineTypePlugin);
  1509. const EngineOptions& options(pData->options);
  1510. {
  1511. MemoryOutputStream outSettings(1024);
  1512. outSettings << " <EngineSettings>\n";
  1513. outSettings << " <ForceStereo>" << bool2str(options.forceStereo) << "</ForceStereo>\n";
  1514. outSettings << " <PreferPluginBridges>" << bool2str(options.preferPluginBridges) << "</PreferPluginBridges>\n";
  1515. outSettings << " <PreferUiBridges>" << bool2str(options.preferUiBridges) << "</PreferUiBridges>\n";
  1516. outSettings << " <UIsAlwaysOnTop>" << bool2str(options.uisAlwaysOnTop) << "</UIsAlwaysOnTop>\n";
  1517. outSettings << " <MaxParameters>" << String(options.maxParameters) << "</MaxParameters>\n";
  1518. outSettings << " <UIBridgesTimeout>" << String(options.uiBridgesTimeout) << "</UIBridgesTimeout>\n";
  1519. if (isPlugin)
  1520. {
  1521. outSettings << " <LADSPA_PATH>" << xmlSafeString(options.pathLADSPA, true) << "</LADSPA_PATH>\n";
  1522. outSettings << " <DSSI_PATH>" << xmlSafeString(options.pathDSSI, true) << "</DSSI_PATH>\n";
  1523. outSettings << " <LV2_PATH>" << xmlSafeString(options.pathLV2, true) << "</LV2_PATH>\n";
  1524. outSettings << " <VST2_PATH>" << xmlSafeString(options.pathVST2, true) << "</VST2_PATH>\n";
  1525. outSettings << " <VST3_PATH>" << xmlSafeString(options.pathVST3, true) << "</VST3_PATH>\n";
  1526. outSettings << " <SF2_PATH>" << xmlSafeString(options.pathSF2, true) << "</SF2_PATH>\n";
  1527. outSettings << " <SFZ_PATH>" << xmlSafeString(options.pathSFZ, true) << "</SFZ_PATH>\n";
  1528. }
  1529. outSettings << " </EngineSettings>\n";
  1530. outStream << outSettings;
  1531. }
  1532. if (pData->timeInfo.bbt.valid && ! isPlugin)
  1533. {
  1534. MemoryOutputStream outTransport(128);
  1535. outTransport << "\n <Transport>\n";
  1536. // outTransport << " <BeatsPerBar>" << pData->timeInfo.bbt.beatsPerBar << "</BeatsPerBar>\n";
  1537. outTransport << " <BeatsPerMinute>" << pData->timeInfo.bbt.beatsPerMinute << "</BeatsPerMinute>\n";
  1538. outTransport << " </Transport>\n";
  1539. outStream << outTransport;
  1540. }
  1541. char strBuf[STR_MAX+1];
  1542. for (uint i=0; i < pData->curPluginCount; ++i)
  1543. {
  1544. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1545. if (plugin != nullptr && plugin->isEnabled())
  1546. {
  1547. MemoryOutputStream outPlugin(4096), streamPlugin;
  1548. plugin->getStateSave(false).dumpToMemoryStream(streamPlugin);
  1549. outPlugin << "\n";
  1550. strBuf[0] = '\0';
  1551. plugin->getRealName(strBuf);
  1552. if (strBuf[0] != '\0')
  1553. outPlugin << " <!-- " << xmlSafeString(strBuf, true) << " -->\n";
  1554. outPlugin << " <Plugin>\n";
  1555. outPlugin << streamPlugin;
  1556. outPlugin << " </Plugin>\n";
  1557. outStream << outPlugin;
  1558. }
  1559. }
  1560. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1561. // tell bridges we're done saving
  1562. for (uint i=0; i < pData->curPluginCount; ++i)
  1563. {
  1564. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1565. if (plugin != nullptr && plugin->isEnabled() && (plugin->getHints() & PLUGIN_IS_BRIDGE) != 0)
  1566. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "true", false);
  1567. }
  1568. // save internal connections
  1569. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1570. {
  1571. if (const char* const* const patchbayConns = getPatchbayConnections(false))
  1572. {
  1573. MemoryOutputStream outPatchbay(2048);
  1574. outPatchbay << "\n <Patchbay>\n";
  1575. for (int i=0; patchbayConns[i] != nullptr && patchbayConns[i+1] != nullptr; ++i, ++i )
  1576. {
  1577. const char* const connSource(patchbayConns[i]);
  1578. const char* const connTarget(patchbayConns[i+1]);
  1579. CARLA_SAFE_ASSERT_CONTINUE(connSource != nullptr && connSource[0] != '\0');
  1580. CARLA_SAFE_ASSERT_CONTINUE(connTarget != nullptr && connTarget[0] != '\0');
  1581. outPatchbay << " <Connection>\n";
  1582. outPatchbay << " <Source>" << xmlSafeString(connSource, true) << "</Source>\n";
  1583. outPatchbay << " <Target>" << xmlSafeString(connTarget, true) << "</Target>\n";
  1584. outPatchbay << " </Connection>\n";
  1585. }
  1586. outPatchbay << " </Patchbay>\n";
  1587. outStream << outPatchbay;
  1588. }
  1589. }
  1590. // if we're running inside some session-manager (and using JACK), let them handle the connections
  1591. bool saveExternalConnections;
  1592. /**/ if (isPlugin)
  1593. saveExternalConnections = false;
  1594. else if (std::strcmp(getCurrentDriverName(), "JACK") != 0)
  1595. saveExternalConnections = true;
  1596. else if (std::getenv("CARLA_DONT_MANAGE_CONNECTIONS") != nullptr)
  1597. saveExternalConnections = false;
  1598. else if (std::getenv("LADISH_APP_NAME") != nullptr)
  1599. saveExternalConnections = false;
  1600. else if (std::getenv("NSM_URL") != nullptr)
  1601. saveExternalConnections = false;
  1602. else
  1603. saveExternalConnections = true;
  1604. if (saveExternalConnections)
  1605. {
  1606. if (const char* const* const patchbayConns = getPatchbayConnections(true))
  1607. {
  1608. MemoryOutputStream outPatchbay(2048);
  1609. outPatchbay << "\n <ExternalPatchbay>\n";
  1610. for (int i=0; patchbayConns[i] != nullptr && patchbayConns[i+1] != nullptr; ++i, ++i )
  1611. {
  1612. const char* const connSource(patchbayConns[i]);
  1613. const char* const connTarget(patchbayConns[i+1]);
  1614. CARLA_SAFE_ASSERT_CONTINUE(connSource != nullptr && connSource[0] != '\0');
  1615. CARLA_SAFE_ASSERT_CONTINUE(connTarget != nullptr && connTarget[0] != '\0');
  1616. outPatchbay << " <Connection>\n";
  1617. outPatchbay << " <Source>" << xmlSafeString(connSource, true) << "</Source>\n";
  1618. outPatchbay << " <Target>" << xmlSafeString(connTarget, true) << "</Target>\n";
  1619. outPatchbay << " </Connection>\n";
  1620. }
  1621. outPatchbay << " </ExternalPatchbay>\n";
  1622. outStream << outPatchbay;
  1623. }
  1624. }
  1625. #endif
  1626. outStream << "</CARLA-PROJECT>\n";
  1627. }
  1628. static String findBinaryInCustomPath(const char* const searchPath, const char* const binary)
  1629. {
  1630. const StringArray searchPaths(StringArray::fromTokens(searchPath, CARLA_OS_SPLIT_STR, ""));
  1631. // try direct filename first
  1632. String jbinary(binary);
  1633. // adjust for current platform
  1634. #ifdef CARLA_OS_WIN
  1635. if (jbinary[0] == '/')
  1636. jbinary = "C:" + jbinary.replaceCharacter('/', '\\');
  1637. #else
  1638. if (jbinary[1] == ':' && (jbinary[2] == '\\' || jbinary[2] == '/'))
  1639. jbinary = jbinary.substring(2).replaceCharacter('\\', '/');
  1640. #endif
  1641. String filename = File(jbinary).getFileName();
  1642. int searchFlags = File::findFiles|File::ignoreHiddenFiles;
  1643. #ifdef CARLA_OS_MAC
  1644. if (filename.endsWithIgnoreCase(".vst") || filename.endsWithIgnoreCase(".vst3"))
  1645. searchFlags |= File::findDirectories;
  1646. #endif
  1647. Array<File> results;
  1648. for (const String *it=searchPaths.begin(), *end=searchPaths.end(); it != end; ++it)
  1649. {
  1650. const File path(*it);
  1651. results.clear();
  1652. path.findChildFiles(results, searchFlags, true, filename);
  1653. if (results.size() > 0)
  1654. return results.getFirst().getFullPathName();
  1655. }
  1656. // try changing extension
  1657. #if defined(CARLA_OS_MAC)
  1658. if (filename.endsWithIgnoreCase(".dll") || filename.endsWithIgnoreCase(".so"))
  1659. filename = File(jbinary).getFileNameWithoutExtension() + ".dylib";
  1660. #elif defined(CARLA_OS_WIN)
  1661. if (filename.endsWithIgnoreCase(".dylib") || filename.endsWithIgnoreCase(".so"))
  1662. filename = File(jbinary).getFileNameWithoutExtension() + ".dll";
  1663. #else
  1664. if (filename.endsWithIgnoreCase(".dll") || filename.endsWithIgnoreCase(".dylib"))
  1665. filename = File(jbinary).getFileNameWithoutExtension() + ".so";
  1666. #endif
  1667. else
  1668. return String();
  1669. for (const String *it=searchPaths.begin(), *end=searchPaths.end(); it != end; ++it)
  1670. {
  1671. const File path(*it);
  1672. results.clear();
  1673. path.findChildFiles(results, searchFlags, true, filename);
  1674. if (results.size() > 0)
  1675. return results.getFirst().getFullPathName();
  1676. }
  1677. return String();
  1678. }
  1679. bool CarlaEngine::loadProjectInternal(water::XmlDocument& xmlDoc)
  1680. {
  1681. ScopedPointer<XmlElement> xmlElement(xmlDoc.getDocumentElement(true));
  1682. CARLA_SAFE_ASSERT_RETURN_ERR(xmlElement != nullptr, "Failed to parse project file");
  1683. const String& xmlType(xmlElement->getTagName());
  1684. const bool isPreset(xmlType.equalsIgnoreCase("carla-preset"));
  1685. if (! (xmlType.equalsIgnoreCase("carla-project") || isPreset))
  1686. {
  1687. callback(ENGINE_CALLBACK_PROJECT_LOAD_FINISHED, 0, 0, 0, 0.0f, nullptr);
  1688. setLastError("Not a valid Carla project or preset file");
  1689. return false;
  1690. }
  1691. pData->actionCanceled = false;
  1692. callback(ENGINE_CALLBACK_CANCELABLE_ACTION, 0, 1, 0, 0.0f, "Loading project");
  1693. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1694. const ScopedValueSetter<bool> _svs2(pData->loadingProject, true, false);
  1695. #endif
  1696. // completely load file
  1697. xmlElement = xmlDoc.getDocumentElement(false);
  1698. CARLA_SAFE_ASSERT_RETURN_ERR(xmlElement != nullptr, "Failed to completely parse project file");
  1699. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  1700. if (pData->aboutToClose)
  1701. return true;
  1702. if (pData->actionCanceled)
  1703. {
  1704. setLastError("Project load canceled");
  1705. return false;
  1706. }
  1707. const bool isPlugin(getType() == kEngineTypePlugin);
  1708. // load engine settings first of all
  1709. if (XmlElement* const elem = isPreset ? nullptr : xmlElement->getChildByName("EngineSettings"))
  1710. {
  1711. for (XmlElement* settElem = elem->getFirstChildElement(); settElem != nullptr; settElem = settElem->getNextElement())
  1712. {
  1713. const String& tag(settElem->getTagName());
  1714. const String text(settElem->getAllSubText().trim());
  1715. /** some settings might be incorrect or require extra work,
  1716. so we call setOption rather than modifying them direly */
  1717. int option = -1;
  1718. int value = 0;
  1719. const char* valueStr = nullptr;
  1720. /**/ if (tag == "ForceStereo")
  1721. {
  1722. option = ENGINE_OPTION_FORCE_STEREO;
  1723. value = text == "true" ? 1 : 0;
  1724. }
  1725. else if (tag == "PreferPluginBridges")
  1726. {
  1727. option = ENGINE_OPTION_PREFER_PLUGIN_BRIDGES;
  1728. value = text == "true" ? 1 : 0;
  1729. }
  1730. else if (tag == "PreferUiBridges")
  1731. {
  1732. option = ENGINE_OPTION_PREFER_UI_BRIDGES;
  1733. value = text == "true" ? 1 : 0;
  1734. }
  1735. else if (tag == "UIsAlwaysOnTop")
  1736. {
  1737. option = ENGINE_OPTION_UIS_ALWAYS_ON_TOP;
  1738. value = text == "true" ? 1 : 0;
  1739. }
  1740. else if (tag == "MaxParameters")
  1741. {
  1742. option = ENGINE_OPTION_MAX_PARAMETERS;
  1743. value = text.getIntValue();
  1744. }
  1745. else if (tag == "UIBridgesTimeout")
  1746. {
  1747. option = ENGINE_OPTION_UI_BRIDGES_TIMEOUT;
  1748. value = text.getIntValue();
  1749. }
  1750. else if (isPlugin)
  1751. {
  1752. /**/ if (tag == "LADSPA_PATH")
  1753. {
  1754. option = ENGINE_OPTION_PLUGIN_PATH;
  1755. value = PLUGIN_LADSPA;
  1756. valueStr = text.toRawUTF8();
  1757. }
  1758. else if (tag == "DSSI_PATH")
  1759. {
  1760. option = ENGINE_OPTION_PLUGIN_PATH;
  1761. value = PLUGIN_DSSI;
  1762. valueStr = text.toRawUTF8();
  1763. }
  1764. else if (tag == "LV2_PATH")
  1765. {
  1766. option = ENGINE_OPTION_PLUGIN_PATH;
  1767. value = PLUGIN_LV2;
  1768. valueStr = text.toRawUTF8();
  1769. }
  1770. else if (tag == "VST2_PATH")
  1771. {
  1772. option = ENGINE_OPTION_PLUGIN_PATH;
  1773. value = PLUGIN_VST2;
  1774. valueStr = text.toRawUTF8();
  1775. }
  1776. else if (tag.equalsIgnoreCase("VST3_PATH"))
  1777. {
  1778. option = ENGINE_OPTION_PLUGIN_PATH;
  1779. value = PLUGIN_VST3;
  1780. valueStr = text.toRawUTF8();
  1781. }
  1782. else if (tag == "SF2_PATH")
  1783. {
  1784. option = ENGINE_OPTION_PLUGIN_PATH;
  1785. value = PLUGIN_SF2;
  1786. valueStr = text.toRawUTF8();
  1787. }
  1788. else if (tag == "SFZ_PATH")
  1789. {
  1790. option = ENGINE_OPTION_PLUGIN_PATH;
  1791. value = PLUGIN_SFZ;
  1792. valueStr = text.toRawUTF8();
  1793. }
  1794. }
  1795. if (option == -1)
  1796. {
  1797. // check old stuff, unhandled now
  1798. if (tag == "GIG_PATH")
  1799. continue;
  1800. // ignored tags
  1801. if (tag == "LADSPA_PATH" || tag == "DSSI_PATH" || tag == "LV2_PATH" || tag == "VST2_PATH")
  1802. continue;
  1803. if (tag == "VST3_PATH" || tag == "AU_PATH")
  1804. continue;
  1805. if (tag == "SF2_PATH" || tag == "SFZ_PATH")
  1806. continue;
  1807. // hmm something is wrong..
  1808. carla_stderr2("CarlaEngine::loadProjectInternal() - Unhandled option '%s'", tag.toRawUTF8());
  1809. continue;
  1810. }
  1811. setOption(static_cast<EngineOption>(option), value, valueStr);
  1812. }
  1813. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  1814. if (pData->aboutToClose)
  1815. return true;
  1816. if (pData->actionCanceled)
  1817. {
  1818. setLastError("Project load canceled");
  1819. return false;
  1820. }
  1821. }
  1822. // now setup transport
  1823. if (XmlElement* const elem = (isPreset || isPlugin) ? nullptr : xmlElement->getChildByName("Transport"))
  1824. {
  1825. if (XmlElement* const bpmElem = elem->getChildByName("BeatsPerMinute"))
  1826. {
  1827. const String bpmText(bpmElem->getAllSubText().trim());
  1828. const double bpm = bpmText.getDoubleValue();
  1829. // some sane limits
  1830. if (bpm >= 20.0 && bpm < 400.0)
  1831. pData->time.setBPM(bpm);
  1832. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  1833. if (pData->aboutToClose)
  1834. return true;
  1835. if (pData->actionCanceled)
  1836. {
  1837. setLastError("Project load canceled");
  1838. return false;
  1839. }
  1840. }
  1841. }
  1842. // and we handle plugins
  1843. for (XmlElement* elem = xmlElement->getFirstChildElement(); elem != nullptr; elem = elem->getNextElement())
  1844. {
  1845. const String& tagName(elem->getTagName());
  1846. if (isPreset || tagName == "Plugin")
  1847. {
  1848. CarlaStateSave stateSave;
  1849. stateSave.fillFromXmlElement(isPreset ? xmlElement.get() : elem);
  1850. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  1851. if (pData->aboutToClose)
  1852. return true;
  1853. if (pData->actionCanceled)
  1854. {
  1855. setLastError("Project load canceled");
  1856. return false;
  1857. }
  1858. CARLA_SAFE_ASSERT_CONTINUE(stateSave.type != nullptr);
  1859. #ifndef BUILD_BRIDGE
  1860. // compatibility code to load projects with GIG files
  1861. // FIXME Remove on 2.1 release
  1862. if (std::strcmp(stateSave.type, "GIG") == 0)
  1863. {
  1864. if (addPlugin(PLUGIN_LV2, "", stateSave.name, "http://linuxsampler.org/plugins/linuxsampler", 0, nullptr))
  1865. {
  1866. const uint pluginId = pData->curPluginCount;
  1867. if (CarlaPlugin* const plugin = pData->plugins[pluginId].plugin)
  1868. {
  1869. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  1870. if (pData->aboutToClose)
  1871. return true;
  1872. if (pData->actionCanceled)
  1873. {
  1874. setLastError("Project load canceled");
  1875. return false;
  1876. }
  1877. String lsState;
  1878. lsState << "0.35\n";
  1879. lsState << "18 0 Chromatic\n";
  1880. lsState << "18 1 Drum Kits\n";
  1881. lsState << "20 0\n";
  1882. lsState << "0 1 " << stateSave.binary << "\n";
  1883. lsState << "0 0 0 0 1 0 GIG\n";
  1884. plugin->setCustomData(LV2_ATOM__String, "http://linuxsampler.org/schema#state-string", lsState.toRawUTF8(), true);
  1885. plugin->restoreLV2State();
  1886. plugin->setDryWet(stateSave.dryWet, true, true);
  1887. plugin->setVolume(stateSave.volume, true, true);
  1888. plugin->setBalanceLeft(stateSave.balanceLeft, true, true);
  1889. plugin->setBalanceRight(stateSave.balanceRight, true, true);
  1890. plugin->setPanning(stateSave.panning, true, true);
  1891. plugin->setCtrlChannel(stateSave.ctrlChannel, true, true);
  1892. plugin->setActive(stateSave.active, true, true);
  1893. ++pData->curPluginCount;
  1894. plugin->setEnabled(true);
  1895. callback(ENGINE_CALLBACK_PLUGIN_ADDED, pluginId, 0, 0, 0.0f, plugin->getName());
  1896. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  1897. pData->graph.addPlugin(plugin);
  1898. }
  1899. else
  1900. {
  1901. carla_stderr2("Failed to get new plugin, state will not be restored correctly\n");
  1902. }
  1903. }
  1904. else
  1905. {
  1906. carla_stderr2("Failed to load a linuxsampler LV2 plugin, GIG file won't be loaded");
  1907. }
  1908. continue;
  1909. }
  1910. #endif
  1911. const void* extraStuff = nullptr;
  1912. static const char kTrue[] = "true";
  1913. const PluginType ptype(getPluginTypeFromString(stateSave.type));
  1914. switch (ptype)
  1915. {
  1916. case PLUGIN_SF2:
  1917. if (CarlaString(stateSave.label).endsWith(" (16 outs)"))
  1918. extraStuff = kTrue;
  1919. // fall through
  1920. case PLUGIN_LADSPA:
  1921. case PLUGIN_DSSI:
  1922. case PLUGIN_VST2:
  1923. case PLUGIN_VST3:
  1924. case PLUGIN_SFZ:
  1925. if (stateSave.binary != nullptr && stateSave.binary[0] != '\0' &&
  1926. ! (File::isAbsolutePath(stateSave.binary) && File(stateSave.binary).exists()))
  1927. {
  1928. const char* searchPath;
  1929. switch (ptype)
  1930. {
  1931. case PLUGIN_LADSPA: searchPath = pData->options.pathLADSPA; break;
  1932. case PLUGIN_DSSI: searchPath = pData->options.pathDSSI; break;
  1933. case PLUGIN_VST2: searchPath = pData->options.pathVST2; break;
  1934. case PLUGIN_VST3: searchPath = pData->options.pathVST3; break;
  1935. case PLUGIN_SF2: searchPath = pData->options.pathSF2; break;
  1936. case PLUGIN_SFZ: searchPath = pData->options.pathSFZ; break;
  1937. default: searchPath = nullptr; break;
  1938. }
  1939. if (searchPath != nullptr && searchPath[0] != '\0')
  1940. {
  1941. carla_stderr("Plugin binary '%s' doesn't exist on this filesystem, let's look for it...",
  1942. stateSave.binary);
  1943. String result = findBinaryInCustomPath(searchPath, stateSave.binary);
  1944. if (result.isEmpty())
  1945. {
  1946. switch (ptype)
  1947. {
  1948. case PLUGIN_LADSPA: searchPath = std::getenv("LADSPA_PATH"); break;
  1949. case PLUGIN_DSSI: searchPath = std::getenv("DSSI_PATH"); break;
  1950. case PLUGIN_VST2: searchPath = std::getenv("VST_PATH"); break;
  1951. case PLUGIN_VST3: searchPath = std::getenv("VST3_PATH"); break;
  1952. case PLUGIN_SF2: searchPath = std::getenv("SF2_PATH"); break;
  1953. case PLUGIN_SFZ: searchPath = std::getenv("SFZ_PATH"); break;
  1954. default: searchPath = nullptr; break;
  1955. }
  1956. if (searchPath != nullptr && searchPath[0] != '\0')
  1957. result = findBinaryInCustomPath(searchPath, stateSave.binary);
  1958. }
  1959. if (result.isNotEmpty())
  1960. {
  1961. delete[] stateSave.binary;
  1962. stateSave.binary = carla_strdup(result.toRawUTF8());
  1963. carla_stderr("Found it! :)");
  1964. }
  1965. else
  1966. {
  1967. carla_stderr("Damn, we failed... :(");
  1968. }
  1969. }
  1970. }
  1971. break;
  1972. default:
  1973. break;
  1974. }
  1975. BinaryType btype;
  1976. switch (ptype)
  1977. {
  1978. case PLUGIN_LADSPA:
  1979. case PLUGIN_DSSI:
  1980. case PLUGIN_LV2:
  1981. case PLUGIN_VST2:
  1982. btype = getBinaryTypeFromFile(stateSave.binary);
  1983. break;
  1984. default:
  1985. btype = BINARY_NATIVE;
  1986. break;
  1987. }
  1988. if (addPlugin(btype, ptype, stateSave.binary,
  1989. stateSave.name, stateSave.label, stateSave.uniqueId, extraStuff, stateSave.options))
  1990. {
  1991. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1992. const uint pluginId = pData->curPluginCount;
  1993. #else
  1994. const uint pluginId = 0;
  1995. #endif
  1996. if (CarlaPlugin* const plugin = pData->plugins[pluginId].plugin)
  1997. {
  1998. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  1999. if (pData->aboutToClose)
  2000. return true;
  2001. if (pData->actionCanceled)
  2002. {
  2003. setLastError("Project load canceled");
  2004. return false;
  2005. }
  2006. // deactivate bridge client-side ping check, since some plugins block during load
  2007. if ((plugin->getHints() & PLUGIN_IS_BRIDGE) != 0 && ! isPreset)
  2008. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "false", false);
  2009. plugin->loadStateSave(stateSave);
  2010. /* NOTE: The following code is the same as the end of addPlugin().
  2011. * When project is loading we do not enable the plugin right away,
  2012. * as we want to load state first.
  2013. */
  2014. plugin->setEnabled(true);
  2015. ++pData->curPluginCount;
  2016. callback(ENGINE_CALLBACK_PLUGIN_ADDED, pluginId, 0, 0, 0.0f, plugin->getName());
  2017. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2018. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  2019. pData->graph.addPlugin(plugin);
  2020. #endif
  2021. }
  2022. else
  2023. {
  2024. carla_stderr2("Failed to get new plugin, state will not be restored correctly\n");
  2025. }
  2026. }
  2027. else
  2028. {
  2029. carla_stderr2("Failed to load a plugin '%s', error was:\n%s", stateSave.name, getLastError());
  2030. }
  2031. }
  2032. if (isPreset)
  2033. {
  2034. callback(ENGINE_CALLBACK_PROJECT_LOAD_FINISHED, 0, 0, 0, 0.0f, nullptr);
  2035. callback(ENGINE_CALLBACK_CANCELABLE_ACTION, 0, 0, 0, 0.0f, "Loading project");
  2036. return true;
  2037. }
  2038. }
  2039. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2040. // tell bridges we're done loading
  2041. for (uint i=0; i < pData->curPluginCount; ++i)
  2042. {
  2043. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  2044. if (plugin != nullptr && plugin->isEnabled() && (plugin->getHints() & PLUGIN_IS_BRIDGE) != 0)
  2045. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "__CarlaPingOnOff__", "true", false);
  2046. }
  2047. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  2048. if (pData->aboutToClose)
  2049. return true;
  2050. if (pData->actionCanceled)
  2051. {
  2052. setLastError("Project load canceled");
  2053. return false;
  2054. }
  2055. bool hasInternalConnections = false;
  2056. // and now we handle connections (internal)
  2057. if (XmlElement* const elem = xmlElement->getChildByName("Patchbay"))
  2058. {
  2059. hasInternalConnections = true;
  2060. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  2061. {
  2062. CarlaString sourcePort, targetPort;
  2063. const bool isUsingExternal(pData->graph.isUsingExternal());
  2064. for (XmlElement* patchElem = elem->getFirstChildElement(); patchElem != nullptr; patchElem = patchElem->getNextElement())
  2065. {
  2066. const String& patchTag(patchElem->getTagName());
  2067. if (patchTag != "Connection")
  2068. continue;
  2069. sourcePort.clear();
  2070. targetPort.clear();
  2071. for (XmlElement* connElem = patchElem->getFirstChildElement(); connElem != nullptr; connElem = connElem->getNextElement())
  2072. {
  2073. const String& tag(connElem->getTagName());
  2074. const String text(connElem->getAllSubText().trim());
  2075. /**/ if (tag == "Source")
  2076. sourcePort = xmlSafeString(text, false).toRawUTF8();
  2077. else if (tag == "Target")
  2078. targetPort = xmlSafeString(text, false).toRawUTF8();
  2079. }
  2080. if (sourcePort.isNotEmpty() && targetPort.isNotEmpty())
  2081. restorePatchbayConnection(false, sourcePort, targetPort, !isUsingExternal);
  2082. }
  2083. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  2084. if (pData->aboutToClose)
  2085. return true;
  2086. if (pData->actionCanceled)
  2087. {
  2088. setLastError("Project load canceled");
  2089. return false;
  2090. }
  2091. }
  2092. }
  2093. // if we're running inside some session-manager (and using JACK), let them handle the external connections
  2094. bool loadExternalConnections;
  2095. /**/ if (std::strcmp(getCurrentDriverName(), "JACK") != 0)
  2096. loadExternalConnections = true;
  2097. else if (std::getenv("CARLA_DONT_MANAGE_CONNECTIONS") != nullptr)
  2098. loadExternalConnections = false;
  2099. else if (std::getenv("LADISH_APP_NAME") != nullptr)
  2100. loadExternalConnections = false;
  2101. else if (std::getenv("NSM_URL") != nullptr)
  2102. loadExternalConnections = false;
  2103. else
  2104. loadExternalConnections = true;
  2105. // plus external connections too
  2106. if (loadExternalConnections)
  2107. {
  2108. const bool isUsingExternal = pData->options.processMode != ENGINE_PROCESS_MODE_PATCHBAY ||
  2109. pData->graph.isUsingExternal();
  2110. const bool loadingAsExternal = pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY &&
  2111. hasInternalConnections;
  2112. for (XmlElement* elem = xmlElement->getFirstChildElement(); elem != nullptr; elem = elem->getNextElement())
  2113. {
  2114. const String& tagName(elem->getTagName());
  2115. // check if we want to load patchbay-mode connections into an external (multi-client) graph
  2116. if (tagName == "Patchbay")
  2117. {
  2118. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  2119. continue;
  2120. }
  2121. // or load external patchbay connections
  2122. else if (tagName != "ExternalPatchbay")
  2123. {
  2124. continue;
  2125. }
  2126. CarlaString sourcePort, targetPort;
  2127. for (XmlElement* patchElem = elem->getFirstChildElement(); patchElem != nullptr; patchElem = patchElem->getNextElement())
  2128. {
  2129. const String& patchTag(patchElem->getTagName());
  2130. if (patchTag != "Connection")
  2131. continue;
  2132. sourcePort.clear();
  2133. targetPort.clear();
  2134. for (XmlElement* connElem = patchElem->getFirstChildElement(); connElem != nullptr; connElem = connElem->getNextElement())
  2135. {
  2136. const String& tag(connElem->getTagName());
  2137. const String text(connElem->getAllSubText().trim());
  2138. /**/ if (tag == "Source")
  2139. sourcePort = xmlSafeString(text, false).toRawUTF8();
  2140. else if (tag == "Target")
  2141. targetPort = xmlSafeString(text, false).toRawUTF8();
  2142. }
  2143. if (sourcePort.isNotEmpty() && targetPort.isNotEmpty())
  2144. restorePatchbayConnection(loadingAsExternal, sourcePort, targetPort, isUsingExternal);
  2145. }
  2146. break;
  2147. }
  2148. }
  2149. #endif
  2150. callback(ENGINE_CALLBACK_PROJECT_LOAD_FINISHED, 0, 0, 0, 0.0f, nullptr);
  2151. callback(ENGINE_CALLBACK_CANCELABLE_ACTION, 0, 0, 0, 0.0f, "Loading project");
  2152. return true;
  2153. }
  2154. // -----------------------------------------------------------------------
  2155. CARLA_BACKEND_END_NAMESPACE