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.

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