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.

2127 lines
73KB

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