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.

2777 lines
92KB

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