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.

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