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.

2394 lines
80KB

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