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.

2270 lines
78KB

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