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.

2284 lines
78KB

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