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.

2874 lines
95KB

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