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.

2667 lines
88KB

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