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.

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