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.

2333 lines
80KB

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