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.

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