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.

1634 lines
52KB

  1. /*
  2. * Carla Plugin Host
  3. * Copyright (C) 2011-2014 Filipe Coelho <falktx@falktx.com>
  4. *
  5. * This program is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU General Public License as
  7. * published by the Free Software Foundation; either version 2 of
  8. * the License, or any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * For a full copy of the GNU General Public License see the doc/GPL.txt file.
  16. */
  17. /* TODO:
  18. * - complete processRack(): carefully add to input, sorted events
  19. * - implement processPatchbay()
  20. * - implement oscSend_control_switch_plugins()
  21. * - proper find&load plugins
  22. * - something about the peaks?
  23. */
  24. #include "CarlaEngineInternal.hpp"
  25. #include "CarlaPlugin.hpp"
  26. #include "CarlaBackendUtils.hpp"
  27. #include "CarlaBinaryUtils.hpp"
  28. #include "CarlaEngineUtils.hpp"
  29. #include "CarlaMathUtils.hpp"
  30. #include "CarlaStateUtils.hpp"
  31. #include "CarlaMIDI.h"
  32. #include "jackbridge/JackBridge.hpp"
  33. #include "juce_core.h"
  34. using juce::File;
  35. using juce::MemoryOutputStream;
  36. using juce::ScopedPointer;
  37. using juce::String;
  38. using juce::XmlDocument;
  39. using juce::XmlElement;
  40. CARLA_BACKEND_START_NAMESPACE
  41. // -----------------------------------------------------------------------
  42. // Carla Engine
  43. CarlaEngine::CarlaEngine()
  44. : pData(new ProtectedData(this))
  45. {
  46. carla_debug("CarlaEngine::CarlaEngine()");
  47. }
  48. CarlaEngine::~CarlaEngine()
  49. {
  50. carla_debug("CarlaEngine::~CarlaEngine()");
  51. delete pData;
  52. }
  53. // -----------------------------------------------------------------------
  54. // Static calls
  55. uint CarlaEngine::getDriverCount()
  56. {
  57. carla_debug("CarlaEngine::getDriverCount()");
  58. uint count = 0;
  59. if (jackbridge_is_ok())
  60. count += 1;
  61. #ifndef BUILD_BRIDGE
  62. # if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
  63. count += getJuceApiCount();
  64. # else
  65. count += getRtAudioApiCount();
  66. # endif
  67. #endif
  68. return count;
  69. }
  70. const char* CarlaEngine::getDriverName(const uint index2)
  71. {
  72. carla_debug("CarlaEngine::getDriverName(%i)", index2);
  73. uint index(index2);
  74. if (jackbridge_is_ok() && index-- == 0)
  75. return "JACK";
  76. #ifndef BUILD_BRIDGE
  77. # if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
  78. if (const uint count = getJuceApiCount())
  79. {
  80. if (index < count)
  81. return getJuceApiName(index);
  82. index -= count;
  83. }
  84. # else
  85. if (const uint count = getRtAudioApiCount())
  86. {
  87. if (index < count)
  88. return getRtAudioApiName(index);
  89. index -= count;
  90. }
  91. # endif
  92. #endif
  93. carla_stderr("CarlaEngine::getDriverName(%i) - invalid index", index2);
  94. return nullptr;
  95. }
  96. const char* const* CarlaEngine::getDriverDeviceNames(const uint index2)
  97. {
  98. carla_debug("CarlaEngine::getDriverDeviceNames(%i)", index2);
  99. uint index(index2);
  100. if (jackbridge_is_ok() && index-- == 0)
  101. {
  102. static const char* ret[3] = { "Auto-Connect OFF", "Auto-Connect ON", nullptr };
  103. return ret;
  104. }
  105. #ifndef BUILD_BRIDGE
  106. # if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
  107. if (const uint count = getJuceApiCount())
  108. {
  109. if (index < count)
  110. return getJuceApiDeviceNames(index);
  111. index -= count;
  112. }
  113. # else
  114. if (const uint count = getRtAudioApiCount())
  115. {
  116. if (index < count)
  117. return getRtAudioApiDeviceNames(index);
  118. index -= count;
  119. }
  120. # endif
  121. #endif
  122. carla_stderr("CarlaEngine::getDriverDeviceNames(%i) - invalid index", index2);
  123. return nullptr;
  124. }
  125. const EngineDriverDeviceInfo* CarlaEngine::getDriverDeviceInfo(const uint index2, const char* const deviceName)
  126. {
  127. carla_debug("CarlaEngine::getDriverDeviceInfo(%i, \"%s\")", index2, deviceName);
  128. uint index(index2);
  129. if (jackbridge_is_ok() && index-- == 0)
  130. {
  131. static uint32_t bufSizes[11] = { 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 0 };
  132. static EngineDriverDeviceInfo devInfo;
  133. devInfo.hints = ENGINE_DRIVER_DEVICE_VARIABLE_BUFFER_SIZE;
  134. devInfo.bufferSizes = bufSizes;
  135. devInfo.sampleRates = nullptr;
  136. return &devInfo;
  137. }
  138. #ifndef BUILD_BRIDGE
  139. # if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
  140. if (const uint count = getJuceApiCount())
  141. {
  142. if (index < count)
  143. return getJuceDeviceInfo(index, deviceName);
  144. index -= count;
  145. }
  146. # else
  147. if (const uint count = getRtAudioApiCount())
  148. {
  149. if (index < count)
  150. return getRtAudioDeviceInfo(index, deviceName);
  151. index -= count;
  152. }
  153. # endif
  154. #endif
  155. carla_stderr("CarlaEngine::getDriverDeviceNames(%i, \"%s\") - invalid index", index2, deviceName);
  156. return nullptr;
  157. }
  158. CarlaEngine* CarlaEngine::newDriverByName(const char* const driverName)
  159. {
  160. CARLA_SAFE_ASSERT_RETURN(driverName != nullptr && driverName[0] != '\0', nullptr);
  161. carla_debug("CarlaEngine::newDriverByName(\"%s\")", driverName);
  162. if (std::strcmp(driverName, "JACK") == 0)
  163. return newJack();
  164. #ifndef BUILD_BRIDGE
  165. # if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
  166. // -------------------------------------------------------------------
  167. // macos
  168. if (std::strcmp(driverName, "CoreAudio") == 0)
  169. return newJuce(AUDIO_API_CORE);
  170. // -------------------------------------------------------------------
  171. // windows
  172. if (std::strcmp(driverName, "ASIO") == 0)
  173. return newJuce(AUDIO_API_ASIO);
  174. if (std::strcmp(driverName, "DirectSound") == 0)
  175. return newJuce(AUDIO_API_DS);
  176. #else
  177. // -------------------------------------------------------------------
  178. // common
  179. if (std::strncmp(driverName, "JACK ", 5) == 0)
  180. return newRtAudio(AUDIO_API_JACK);
  181. // -------------------------------------------------------------------
  182. // linux
  183. if (std::strcmp(driverName, "ALSA") == 0)
  184. return newRtAudio(AUDIO_API_ALSA);
  185. if (std::strcmp(driverName, "OSS") == 0)
  186. return newRtAudio(AUDIO_API_OSS);
  187. if (std::strcmp(driverName, "PulseAudio") == 0)
  188. return newRtAudio(AUDIO_API_PULSE);
  189. # endif
  190. #endif
  191. carla_stderr("CarlaEngine::newDriverByName(\"%s\") - invalid driver name", driverName);
  192. return nullptr;
  193. }
  194. // -----------------------------------------------------------------------
  195. // Constant values
  196. uint CarlaEngine::getMaxClientNameSize() const noexcept
  197. {
  198. return STR_MAX/2;
  199. }
  200. uint CarlaEngine::getMaxPortNameSize() const noexcept
  201. {
  202. return STR_MAX;
  203. }
  204. uint CarlaEngine::getCurrentPluginCount() const noexcept
  205. {
  206. return pData->curPluginCount;
  207. }
  208. uint CarlaEngine::getMaxPluginNumber() const noexcept
  209. {
  210. return pData->maxPluginNumber;
  211. }
  212. // -----------------------------------------------------------------------
  213. // Virtual, per-engine type calls
  214. bool CarlaEngine::init(const char* const clientName)
  215. {
  216. carla_debug("CarlaEngine::init(\"%s\")", clientName);
  217. if (! pData->init(clientName))
  218. return false;
  219. callback(ENGINE_CALLBACK_ENGINE_STARTED, 0, pData->options.processMode, pData->options.transportMode, 0.0f, getCurrentDriverName());
  220. return true;
  221. }
  222. bool CarlaEngine::close()
  223. {
  224. carla_debug("CarlaEngine::close()");
  225. if (pData->curPluginCount != 0)
  226. {
  227. pData->aboutToClose = true;
  228. removeAllPlugins();
  229. }
  230. #ifndef BUILD_BRIDGE
  231. if (pData->osc.isControlRegistered())
  232. oscSend_control_exit();
  233. #endif
  234. pData->close();
  235. callback(ENGINE_CALLBACK_ENGINE_STOPPED, 0, 0, 0, 0.0f, nullptr);
  236. return true;
  237. }
  238. void CarlaEngine::idle() noexcept
  239. {
  240. CARLA_SAFE_ASSERT_RETURN(pData->nextAction.opcode == kEnginePostActionNull,); // FIXME REMOVE
  241. CARLA_SAFE_ASSERT_RETURN(pData->nextPluginId == pData->maxPluginNumber,);
  242. 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. try {
  248. plugin->idle();
  249. } CARLA_SAFE_EXCEPTION_CONTINUE("Plugin idle");
  250. }
  251. }
  252. pData->osc.idle();
  253. }
  254. CarlaEngineClient* CarlaEngine::addClient(CarlaPlugin* const)
  255. {
  256. return new CarlaEngineClient(*this);
  257. }
  258. // -----------------------------------------------------------------------
  259. // Plugin management
  260. bool CarlaEngine::addPlugin(const BinaryType btype, const PluginType ptype, const char* const filename, const char* const name, const char* const label, const int64_t uniqueId, const void* const extra)
  261. {
  262. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  263. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  264. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextPluginId <= pData->maxPluginNumber, "Invalid engine internal data");
  265. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  266. CARLA_SAFE_ASSERT_RETURN_ERR(btype != BINARY_NONE, "Invalid plugin binary mode");
  267. CARLA_SAFE_ASSERT_RETURN_ERR(ptype != PLUGIN_NONE, "Invalid plugin type");
  268. CARLA_SAFE_ASSERT_RETURN_ERR((filename != nullptr && filename[0] != '\0') || (label != nullptr && label[0] != '\0'), "Invalid plugin filename and label");
  269. carla_debug("CarlaEngine::addPlugin(%i:%s, %i:%s, \"%s\", \"%s\", \"%s\", " P_INT64 ", %p)", btype, BinaryType2Str(btype), ptype, PluginType2Str(ptype), filename, name, label, uniqueId, extra);
  270. uint id;
  271. #ifndef BUILD_BRIDGE
  272. CarlaPlugin* oldPlugin = nullptr;
  273. if (pData->nextPluginId < pData->curPluginCount)
  274. {
  275. id = pData->nextPluginId;
  276. pData->nextPluginId = pData->maxPluginNumber;
  277. oldPlugin = pData->plugins[id].plugin;
  278. CARLA_SAFE_ASSERT_RETURN_ERR(oldPlugin != nullptr, "Invalid replace plugin Id");
  279. }
  280. else
  281. #endif
  282. {
  283. id = pData->curPluginCount;
  284. if (id == pData->maxPluginNumber)
  285. {
  286. setLastError("Maximum number of plugins reached");
  287. return false;
  288. }
  289. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins[id].plugin == nullptr, "Invalid engine internal data");
  290. }
  291. CarlaPlugin::Initializer initializer = {
  292. this,
  293. id,
  294. filename,
  295. name,
  296. label,
  297. uniqueId
  298. };
  299. CarlaPlugin* plugin = nullptr;
  300. #ifndef BUILD_BRIDGE
  301. CarlaString bridgeBinary(pData->options.binaryDir);
  302. if (bridgeBinary.isNotEmpty())
  303. {
  304. # ifndef CARLA_OS_WIN
  305. if (btype == BINARY_NATIVE)
  306. {
  307. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-native";
  308. }
  309. else
  310. # endif
  311. {
  312. switch (btype)
  313. {
  314. case BINARY_POSIX32:
  315. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-posix32";
  316. break;
  317. case BINARY_POSIX64:
  318. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-posix64";
  319. break;
  320. case BINARY_WIN32:
  321. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-win32.exe";
  322. break;
  323. case BINARY_WIN64:
  324. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-win64.exe";
  325. break;
  326. default:
  327. bridgeBinary.clear();
  328. break;
  329. }
  330. }
  331. if (! File(bridgeBinary.buffer()).existsAsFile())
  332. bridgeBinary.clear();
  333. }
  334. if (ptype != PLUGIN_INTERNAL && (btype != BINARY_NATIVE || (pData->options.preferPluginBridges && bridgeBinary.isNotEmpty())))
  335. {
  336. if (bridgeBinary.isNotEmpty())
  337. {
  338. plugin = CarlaPlugin::newBridge(initializer, btype, ptype, bridgeBinary);
  339. }
  340. # ifdef CARLA_OS_LINUX
  341. // fallback to dssi-vst if possible
  342. else if (btype == BINARY_WIN32 && File("/usr/lib/dssi/dssi-vst.so").existsAsFile())
  343. {
  344. File file(filename);
  345. CarlaString label2(file.getFileName().toRawUTF8());
  346. label2.replace(' ', '*');
  347. CarlaPlugin::Initializer init2 = {
  348. this,
  349. id,
  350. "/usr/lib/dssi/dssi-vst.so",
  351. name,
  352. label2,
  353. uniqueId
  354. };
  355. char* const oldVstPath(getenv("VST_PATH"));
  356. carla_setenv("VST_PATH", file.getParentDirectory().getFullPathName().toRawUTF8());
  357. plugin = CarlaPlugin::newDSSI(init2);
  358. if (oldVstPath != nullptr)
  359. carla_setenv("VST_PATH", oldVstPath);
  360. }
  361. # endif
  362. else
  363. {
  364. setLastError("This Carla build cannot handle this binary");
  365. return false;
  366. }
  367. }
  368. else
  369. #endif // ! BUILD_BRIDGE
  370. {
  371. bool use16Outs;
  372. setLastError("Invalid or unsupported plugin type");
  373. switch (ptype)
  374. {
  375. case PLUGIN_NONE:
  376. break;
  377. case PLUGIN_INTERNAL:
  378. /*if (std::strcmp(label, "FluidSynth") == 0)
  379. {
  380. use16Outs = (extra != nullptr && std::strcmp((const char*)extra, "true") == 0);
  381. plugin = CarlaPlugin::newFluidSynth(initializer, use16Outs);
  382. }
  383. else if (std::strcmp(label, "LinuxSampler (GIG)") == 0)
  384. {
  385. use16Outs = (extra != nullptr && std::strcmp((const char*)extra, "true") == 0);
  386. plugin = CarlaPlugin::newLinuxSampler(initializer, "GIG", use16Outs);
  387. }
  388. else if (std::strcmp(label, "LinuxSampler (SF2)") == 0)
  389. {
  390. use16Outs = (extra != nullptr && std::strcmp((const char*)extra, "true") == 0);
  391. plugin = CarlaPlugin::newLinuxSampler(initializer, "SF2", use16Outs);
  392. }
  393. else if (std::strcmp(label, "LinuxSampler (SFZ)") == 0)
  394. {
  395. use16Outs = (extra != nullptr && std::strcmp((const char*)extra, "true") == 0);
  396. plugin = CarlaPlugin::newLinuxSampler(initializer, "SFZ", use16Outs);
  397. }*/
  398. plugin = CarlaPlugin::newNative(initializer);
  399. break;
  400. case PLUGIN_LADSPA:
  401. plugin = CarlaPlugin::newLADSPA(initializer, (const LADSPA_RDF_Descriptor*)extra);
  402. break;
  403. case PLUGIN_DSSI:
  404. plugin = CarlaPlugin::newDSSI(initializer);
  405. break;
  406. case PLUGIN_LV2:
  407. plugin = CarlaPlugin::newLV2(initializer);
  408. break;
  409. case PLUGIN_VST:
  410. plugin = CarlaPlugin::newVST(initializer);
  411. break;
  412. case PLUGIN_VST3:
  413. plugin = CarlaPlugin::newVST3(initializer);
  414. break;
  415. case PLUGIN_AU:
  416. plugin = CarlaPlugin::newAU(initializer);
  417. break;
  418. case PLUGIN_GIG:
  419. use16Outs = (extra != nullptr && std::strcmp((const char*)extra, "true") == 0);
  420. plugin = CarlaPlugin::newFileGIG(initializer, use16Outs);
  421. break;
  422. case PLUGIN_SF2:
  423. use16Outs = (extra != nullptr && std::strcmp((const char*)extra, "true") == 0);
  424. plugin = CarlaPlugin::newFileSF2(initializer, use16Outs);
  425. break;
  426. case PLUGIN_SFZ:
  427. plugin = CarlaPlugin::newFileSFZ(initializer);
  428. break;
  429. }
  430. }
  431. if (plugin == nullptr)
  432. return false;
  433. plugin->registerToOscClient();
  434. EnginePluginData& pluginData(pData->plugins[id]);
  435. pluginData.plugin = plugin;
  436. pluginData.insPeak[0] = 0.0f;
  437. pluginData.insPeak[1] = 0.0f;
  438. pluginData.outsPeak[0] = 0.0f;
  439. pluginData.outsPeak[1] = 0.0f;
  440. #ifndef BUILD_BRIDGE
  441. if (oldPlugin != nullptr)
  442. {
  443. // the engine thread might be reading from the old plugin
  444. pData->thread.stopThread(500);
  445. pData->thread.startThread();
  446. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  447. pData->graph.replacePlugin(oldPlugin, plugin);
  448. const bool wasActive = oldPlugin->getInternalParameterValue(PARAMETER_ACTIVE) >= 0.5f;
  449. const float oldDryWet = oldPlugin->getInternalParameterValue(PARAMETER_DRYWET);
  450. const float oldVolume = oldPlugin->getInternalParameterValue(PARAMETER_VOLUME);
  451. delete oldPlugin;
  452. if (plugin->getHints() & PLUGIN_CAN_DRYWET)
  453. plugin->setDryWet(oldDryWet, true, true);
  454. if (plugin->getHints() & PLUGIN_CAN_VOLUME)
  455. plugin->setVolume(oldVolume, true, true);
  456. if (wasActive)
  457. plugin->setActive(true, true, true);
  458. callback(ENGINE_CALLBACK_RELOAD_ALL, id, 0, 0, 0.0f, nullptr);
  459. }
  460. else
  461. #endif
  462. {
  463. ++pData->curPluginCount;
  464. callback(ENGINE_CALLBACK_PLUGIN_ADDED, id, 0, 0, 0.0f, plugin->getName());
  465. #ifndef BUILD_BRIDGE
  466. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  467. pData->graph.addPlugin(plugin);
  468. #endif
  469. }
  470. return true;
  471. }
  472. 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)
  473. {
  474. return addPlugin(BINARY_NATIVE, ptype, filename, name, label, uniqueId, extra);
  475. }
  476. bool CarlaEngine::removePlugin(const uint id)
  477. {
  478. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  479. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  480. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount != 0, "Invalid engine internal data");
  481. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  482. CARLA_SAFE_ASSERT_RETURN_ERR(id < pData->curPluginCount, "Invalid plugin Id");
  483. carla_debug("CarlaEngine::removePlugin(%i)", id);
  484. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  485. CARLA_SAFE_ASSERT_RETURN_ERR(plugin != nullptr, "Could not find plugin to remove");
  486. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  487. pData->thread.stopThread(500);
  488. #ifndef BUILD_BRIDGE
  489. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  490. pData->graph.removePlugin(plugin);
  491. const bool lockWait(isRunning() /*&& pData->options.processMode != ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS*/);
  492. const ScopedActionLock sal(pData, kEnginePostActionRemovePlugin, id, 0, lockWait);
  493. for (uint i=id; i < pData->curPluginCount; ++i)
  494. {
  495. CarlaPlugin* const plugin2(pData->plugins[i].plugin);
  496. CARLA_SAFE_ASSERT_BREAK(plugin2 != nullptr);
  497. plugin2->updateOscURL();
  498. }
  499. if (isOscControlRegistered())
  500. oscSend_control_remove_plugin(id);
  501. #else
  502. pData->curPluginCount = 0;
  503. carla_zeroStruct(pData->plugins, 1);
  504. #endif
  505. delete plugin;
  506. if (isRunning() && ! pData->aboutToClose)
  507. pData->thread.startThread();
  508. callback(ENGINE_CALLBACK_PLUGIN_REMOVED, id, 0, 0, 0.0f, nullptr);
  509. return true;
  510. }
  511. bool CarlaEngine::removeAllPlugins()
  512. {
  513. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  514. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  515. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextPluginId == pData->maxPluginNumber, "Invalid engine internal data");
  516. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  517. carla_debug("CarlaEngine::removeAllPlugins()");
  518. if (pData->curPluginCount == 0)
  519. return true;
  520. pData->thread.stopThread(500);
  521. #ifndef BUILD_BRIDGE
  522. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  523. pData->graph.removeAllPlugins(this);
  524. #endif
  525. const uint32_t curPluginCount(pData->curPluginCount);
  526. const bool lockWait(isRunning());
  527. const ScopedActionLock sal(pData, kEnginePostActionZeroCount, 0, 0, lockWait);
  528. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  529. for (uint i=0; i < curPluginCount; ++i)
  530. {
  531. EnginePluginData& pluginData(pData->plugins[i]);
  532. if (pluginData.plugin != nullptr)
  533. {
  534. delete pluginData.plugin;
  535. pluginData.plugin = nullptr;
  536. }
  537. pluginData.insPeak[0] = 0.0f;
  538. pluginData.insPeak[1] = 0.0f;
  539. pluginData.outsPeak[0] = 0.0f;
  540. pluginData.outsPeak[1] = 0.0f;
  541. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  542. }
  543. if (isRunning() && ! pData->aboutToClose)
  544. pData->thread.startThread();
  545. return true;
  546. }
  547. #ifndef BUILD_BRIDGE
  548. const char* CarlaEngine::renamePlugin(const uint id, const char* const newName)
  549. {
  550. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  551. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->plugins != nullptr, "Invalid engine internal data");
  552. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->curPluginCount != 0, "Invalid engine internal data");
  553. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  554. CARLA_SAFE_ASSERT_RETURN_ERRN(id < pData->curPluginCount, "Invalid plugin Id");
  555. CARLA_SAFE_ASSERT_RETURN_ERRN(newName != nullptr && newName[0] != '\0', "Invalid plugin name");
  556. carla_debug("CarlaEngine::renamePlugin(%i, \"%s\")", id, newName);
  557. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  558. CARLA_SAFE_ASSERT_RETURN_ERRN(plugin != nullptr, "Could not find plugin to rename");
  559. CARLA_SAFE_ASSERT_RETURN_ERRN(plugin->getId() == id, "Invalid engine internal data");
  560. if (const char* const name = getUniquePluginName(newName))
  561. {
  562. plugin->setName(name);
  563. return name;
  564. }
  565. setLastError("Unable to get new unique plugin name");
  566. return nullptr;
  567. }
  568. bool CarlaEngine::clonePlugin(const uint id)
  569. {
  570. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  571. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  572. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount != 0, "Invalid engine internal data");
  573. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  574. CARLA_SAFE_ASSERT_RETURN_ERR(id < pData->curPluginCount, "Invalid plugin Id");
  575. carla_debug("CarlaEngine::clonePlugin(%i)", id);
  576. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  577. CARLA_SAFE_ASSERT_RETURN_ERR(plugin != nullptr, "Could not find plugin to clone");
  578. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  579. char label[STR_MAX+1];
  580. carla_zeroChar(label, STR_MAX+1);
  581. plugin->getLabel(label);
  582. const uint pluginCountBefore(pData->curPluginCount);
  583. if (! addPlugin(plugin->getBinaryType(), plugin->getType(), plugin->getFilename(), plugin->getName(), label, plugin->getUniqueId(), plugin->getExtraStuff()))
  584. return false;
  585. CARLA_SAFE_ASSERT_RETURN_ERR(pluginCountBefore+1 == pData->curPluginCount, "No new plugin found");
  586. if (CarlaPlugin* const newPlugin = pData->plugins[pluginCountBefore].plugin)
  587. newPlugin->loadStateSave(plugin->getStateSave());
  588. return true;
  589. }
  590. bool CarlaEngine::replacePlugin(const uint id) noexcept
  591. {
  592. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  593. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  594. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount != 0, "Invalid engine internal data");
  595. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  596. carla_debug("CarlaEngine::replacePlugin(%i)", id);
  597. // might use this to reset
  598. if (id == pData->curPluginCount || id == pData->maxPluginNumber)
  599. {
  600. pData->nextPluginId = pData->maxPluginNumber;
  601. return true;
  602. }
  603. CARLA_SAFE_ASSERT_RETURN_ERR(id < pData->curPluginCount, "Invalid plugin Id");
  604. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  605. CARLA_SAFE_ASSERT_RETURN_ERR(plugin != nullptr, "Could not find plugin to replace");
  606. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  607. pData->nextPluginId = id;
  608. return true;
  609. }
  610. bool CarlaEngine::switchPlugins(const uint idA, const uint idB) noexcept
  611. {
  612. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  613. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  614. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount >= 2, "Invalid engine internal data");
  615. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  616. CARLA_SAFE_ASSERT_RETURN_ERR(idA != idB, "Invalid operation, cannot switch plugin with itself");
  617. CARLA_SAFE_ASSERT_RETURN_ERR(idA < pData->curPluginCount, "Invalid plugin Id");
  618. CARLA_SAFE_ASSERT_RETURN_ERR(idB < pData->curPluginCount, "Invalid plugin Id");
  619. carla_debug("CarlaEngine::switchPlugins(%i)", idA, idB);
  620. {
  621. CarlaPlugin* const pluginA(pData->plugins[idA].plugin);
  622. CarlaPlugin* const pluginB(pData->plugins[idB].plugin);
  623. CARLA_SAFE_ASSERT_RETURN_ERR(pluginA != nullptr, "Could not find plugin to switch");
  624. CARLA_SAFE_ASSERT_RETURN_ERR(pluginA != nullptr, "Could not find plugin to switch");
  625. CARLA_SAFE_ASSERT_RETURN_ERR(pluginA->getId() == idA, "Invalid engine internal data");
  626. CARLA_SAFE_ASSERT_RETURN_ERR(pluginB->getId() == idB, "Invalid engine internal data");
  627. pData->thread.stopThread(500);
  628. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  629. pData->graph.replacePlugin(pluginA, pluginB);
  630. }
  631. const bool lockWait(isRunning() /*&& pData->options.processMode != ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS*/);
  632. const ScopedActionLock sal(pData, kEnginePostActionSwitchPlugins, idA, idB, lockWait);
  633. CarlaPlugin* const pluginA(pData->plugins[idA].plugin);
  634. CarlaPlugin* const pluginB(pData->plugins[idB].plugin);
  635. if (pluginA != nullptr && pluginB != nullptr)
  636. {
  637. pluginA->updateOscURL();
  638. pluginB->updateOscURL();
  639. }
  640. // TODO
  641. //if (isOscControlRegistered())
  642. // oscSend_control_switch_plugins(idA, idB);
  643. if (isRunning() && ! pData->aboutToClose)
  644. pData->thread.startThread();
  645. return true;
  646. }
  647. #endif
  648. CarlaPlugin* CarlaEngine::getPlugin(const uint id) const noexcept
  649. {
  650. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->plugins != nullptr, "Invalid engine internal data");
  651. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->curPluginCount != 0, "Invalid engine internal data");
  652. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  653. CARLA_SAFE_ASSERT_RETURN_ERRN(id < pData->curPluginCount, "Invalid plugin Id");
  654. return pData->plugins[id].plugin;
  655. }
  656. CarlaPlugin* CarlaEngine::getPluginUnchecked(const uint id) const noexcept
  657. {
  658. return pData->plugins[id].plugin;
  659. }
  660. const char* CarlaEngine::getUniquePluginName(const char* const name) const
  661. {
  662. CARLA_SAFE_ASSERT_RETURN(pData->nextAction.opcode == kEnginePostActionNull, nullptr);
  663. CARLA_SAFE_ASSERT_RETURN(name != nullptr && name[0] != '\0', nullptr);
  664. carla_debug("CarlaEngine::getUniquePluginName(\"%s\")", name);
  665. CarlaString sname;
  666. sname = name;
  667. if (sname.isEmpty())
  668. {
  669. sname = "(No name)";
  670. return sname.dup();
  671. }
  672. const size_t maxNameSize(carla_min<uint>(getMaxClientNameSize(), 0xff, 6) - 6); // 6 = strlen(" (10)") + 1
  673. if (maxNameSize == 0 || ! isRunning())
  674. return sname.dup();
  675. sname.truncate(maxNameSize);
  676. sname.replace(':', '.'); // ':' is used in JACK1 to split client/port names
  677. for (uint i=0; i < pData->curPluginCount; ++i)
  678. {
  679. CARLA_SAFE_ASSERT_BREAK(pData->plugins[i].plugin != nullptr);
  680. // Check if unique name doesn't exist
  681. if (const char* const pluginName = pData->plugins[i].plugin->getName())
  682. {
  683. if (sname != pluginName)
  684. continue;
  685. }
  686. // Check if string has already been modified
  687. {
  688. const size_t len(sname.length());
  689. // 1 digit, ex: " (2)"
  690. if (sname[len-4] == ' ' && sname[len-3] == '(' && sname.isDigit(len-2) && sname[len-1] == ')')
  691. {
  692. int number = sname[len-2] - '0';
  693. if (number == 9)
  694. {
  695. // next number is 10, 2 digits
  696. sname.truncate(len-4);
  697. sname += " (10)";
  698. //sname.replace(" (9)", " (10)");
  699. }
  700. else
  701. sname[len-2] = char('0' + number + 1);
  702. continue;
  703. }
  704. // 2 digits, ex: " (11)"
  705. if (sname[len-5] == ' ' && sname[len-4] == '(' && sname.isDigit(len-3) && sname.isDigit(len-2) && sname[len-1] == ')')
  706. {
  707. char n2 = sname[len-2];
  708. char n3 = sname[len-3];
  709. if (n2 == '9')
  710. {
  711. n2 = '0';
  712. n3 = static_cast<char>(n3 + 1);
  713. }
  714. else
  715. n2 = static_cast<char>(n2 + 1);
  716. sname[len-2] = n2;
  717. sname[len-3] = n3;
  718. continue;
  719. }
  720. }
  721. // Modify string if not
  722. sname += " (2)";
  723. }
  724. return sname.dup();
  725. }
  726. // -----------------------------------------------------------------------
  727. // Project management
  728. bool CarlaEngine::loadFile(const char* const filename)
  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(filename != nullptr && filename[0] != '\0', "Invalid filename");
  732. carla_debug("CarlaEngine::loadFile(\"%s\")", filename);
  733. File file(filename);
  734. CARLA_SAFE_ASSERT_RETURN_ERR(file.existsAsFile(), "Requested file does not exist or is not a readable file");
  735. CarlaString baseName(file.getFileName().toRawUTF8());
  736. CarlaString extension(file.getFileExtension().replace(".","").toLowerCase().toRawUTF8());
  737. // -------------------------------------------------------------------
  738. if (extension == "carxp" || extension == "carxs")
  739. return loadProject(filename);
  740. // -------------------------------------------------------------------
  741. if (extension == "gig")
  742. return addPlugin(PLUGIN_GIG, filename, baseName, baseName, 0, nullptr);
  743. if (extension == "sf2")
  744. return addPlugin(PLUGIN_SF2, filename, baseName, baseName, 0, nullptr);
  745. if (extension == "sfz")
  746. return addPlugin(PLUGIN_SFZ, filename, baseName, baseName, 0, nullptr);
  747. // -------------------------------------------------------------------
  748. if (extension == "aif" || extension == "aiff" || extension == "bwf" || extension == "flac" || extension == "ogg" || extension == "wav")
  749. {
  750. if (addPlugin(PLUGIN_INTERNAL, nullptr, baseName, "audiofile", 0, nullptr))
  751. {
  752. if (CarlaPlugin* const plugin = getPlugin(pData->curPluginCount-1))
  753. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "file", filename, true);
  754. return true;
  755. }
  756. return false;
  757. }
  758. // -------------------------------------------------------------------
  759. if (extension == "mid" || extension == "midi")
  760. {
  761. if (addPlugin(PLUGIN_INTERNAL, nullptr, baseName, "midifile", 0, nullptr))
  762. {
  763. if (CarlaPlugin* const plugin = getPlugin(pData->curPluginCount-1))
  764. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "file", filename, true);
  765. return true;
  766. }
  767. return false;
  768. }
  769. // -------------------------------------------------------------------
  770. // ZynAddSubFX
  771. if (extension == "xmz" || extension == "xiz")
  772. {
  773. #ifdef WANT_ZYNADDSUBFX
  774. if (addPlugin(PLUGIN_INTERNAL, nullptr, baseName, "zynaddsubfx", 0, nullptr))
  775. {
  776. if (CarlaPlugin* const plugin = getPlugin(pData->curPluginCount-1))
  777. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, (extension == "xmz") ? "CarlaAlternateFile1" : "CarlaAlternateFile2", filename, true);
  778. return true;
  779. }
  780. return false;
  781. #else
  782. setLastError("This Carla build does not have ZynAddSubFX support");
  783. return false;
  784. #endif
  785. }
  786. // -------------------------------------------------------------------
  787. setLastError("Unknown file extension");
  788. return false;
  789. }
  790. bool CarlaEngine::loadProject(const char* const filename)
  791. {
  792. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  793. CARLA_SAFE_ASSERT_RETURN_ERR(filename != nullptr && filename[0] != '\0', "Invalid filename");
  794. carla_debug("CarlaEngine::loadProject(\"%s\")", filename);
  795. File file(filename);
  796. CARLA_SAFE_ASSERT_RETURN_ERR(file.existsAsFile(), "Requested file does not exist or is not a readable file");
  797. XmlDocument xml(file);
  798. ScopedPointer<XmlElement> xmlElement(xml.getDocumentElement(true));
  799. CARLA_SAFE_ASSERT_RETURN_ERR(xmlElement != nullptr, "Failed to parse project file");
  800. const String& xmlType(xmlElement->getTagName());
  801. const bool isPreset(xmlType.equalsIgnoreCase("carla-preset"));
  802. if (! (xmlType.equalsIgnoreCase("carla-project") || isPreset))
  803. {
  804. setLastError("Not a valid Carla project or preset file");
  805. return false;
  806. }
  807. // completely load file
  808. xmlElement = xml.getDocumentElement(false);
  809. CARLA_SAFE_ASSERT_RETURN_ERR(xmlElement != nullptr, "Failed to completely parse project file");
  810. // handle plugins first
  811. for (XmlElement* elem = xmlElement->getFirstChildElement(); elem != nullptr; elem = elem->getNextElement())
  812. {
  813. const String& tagName(elem->getTagName());
  814. if (isPreset || tagName.equalsIgnoreCase("plugin"))
  815. {
  816. StateSave stateSave;
  817. stateSave.fillFromXmlElement(isPreset ? xmlElement.get() : elem);
  818. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  819. CARLA_SAFE_ASSERT_CONTINUE(stateSave.type != nullptr);
  820. const void* extraStuff = nullptr;
  821. // check if using GIG or SF2 16outs
  822. static const char kUse16OutsSuffix[] = " (16 outs)";
  823. const BinaryType btype(getBinaryTypeFromFile(stateSave.binary));
  824. const PluginType ptype(getPluginTypeFromString(stateSave.type));
  825. if (CarlaString(stateSave.label).endsWith(kUse16OutsSuffix))
  826. {
  827. if (ptype == PLUGIN_GIG || ptype == PLUGIN_SF2)
  828. extraStuff = "true";
  829. }
  830. // TODO - proper find&load plugins
  831. if (addPlugin(btype, ptype, stateSave.binary, stateSave.name, stateSave.label, stateSave.uniqueId, extraStuff))
  832. {
  833. if (CarlaPlugin* const plugin = getPlugin(pData->curPluginCount-1))
  834. plugin->loadStateSave(stateSave);
  835. }
  836. else
  837. carla_stderr2("Failed to load a plugin, error was:\n%s", getLastError());
  838. }
  839. if (isPreset)
  840. return true;
  841. }
  842. #ifndef BUILD_BRIDGE
  843. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  844. // if we're running inside some session-manager, let them handle the connections
  845. if (pData->options.processMode != ENGINE_PROCESS_MODE_PATCHBAY)
  846. {
  847. if (std::getenv("CARLA_DONT_MANAGE_CONNECTIONS") != nullptr || std::getenv("LADISH_APP_NAME") != nullptr || std::getenv("NSM_URL") != nullptr)
  848. return true;
  849. }
  850. // now handle connections
  851. for (XmlElement* elem = xmlElement->getFirstChildElement(); elem != nullptr; elem = elem->getNextElement())
  852. {
  853. const String& tagName(elem->getTagName());
  854. if (tagName.equalsIgnoreCase("patchbay"))
  855. {
  856. CarlaString sourcePort, targetPort;
  857. for (XmlElement* patchElem = elem->getFirstChildElement(); patchElem != nullptr; patchElem = patchElem->getNextElement())
  858. {
  859. const String& patchTag(patchElem->getTagName());
  860. sourcePort.clear();
  861. targetPort.clear();
  862. if (! patchTag.equalsIgnoreCase("connection"))
  863. continue;
  864. for (XmlElement* connElem = patchElem->getFirstChildElement(); connElem != nullptr; connElem = connElem->getNextElement())
  865. {
  866. const String& tag(connElem->getTagName());
  867. const String text(connElem->getAllSubText().trim());
  868. if (tag.equalsIgnoreCase("source"))
  869. sourcePort = text.toRawUTF8();
  870. else if (tag.equalsIgnoreCase("target"))
  871. targetPort = text.toRawUTF8();
  872. }
  873. if (sourcePort.isNotEmpty() && targetPort.isNotEmpty())
  874. restorePatchbayConnection(sourcePort, targetPort);
  875. }
  876. break;
  877. }
  878. }
  879. #endif
  880. return true;
  881. }
  882. bool CarlaEngine::saveProject(const char* const filename)
  883. {
  884. CARLA_SAFE_ASSERT_RETURN_ERR(filename != nullptr && filename[0] != '\0', "Invalid filename");
  885. carla_debug("CarlaEngine::saveProject(\"%s\")", filename);
  886. MemoryOutputStream out;
  887. out << "<?xml version='1.0' encoding='UTF-8'?>\n";
  888. out << "<!DOCTYPE CARLA-PROJECT>\n";
  889. out << "<CARLA-PROJECT VERSION='2.0'>\n";
  890. bool firstPlugin = true;
  891. char strBuf[STR_MAX+1];
  892. for (uint i=0; i < pData->curPluginCount; ++i)
  893. {
  894. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  895. if (plugin != nullptr && plugin->isEnabled())
  896. {
  897. if (! firstPlugin)
  898. out << "\n";
  899. strBuf[0] = '\0';
  900. plugin->getRealName(strBuf);
  901. //if (strBuf[0] != '\0')
  902. // out << QString(" <!-- %1 -->\n").arg(xmlSafeString(strBuf, true));
  903. out << " <Plugin>\n";
  904. out << plugin->getStateSave().toString();
  905. out << " </Plugin>\n";
  906. firstPlugin = false;
  907. }
  908. }
  909. #ifndef BUILD_BRIDGE
  910. bool saveConnections = true;
  911. // if we're running inside some session-manager, let them handle the connections
  912. if (pData->options.processMode != ENGINE_PROCESS_MODE_PATCHBAY)
  913. {
  914. if (std::getenv("CARLA_DONT_MANAGE_CONNECTIONS") != nullptr || std::getenv("LADISH_APP_NAME") != nullptr || std::getenv("NSM_URL") != nullptr)
  915. saveConnections = false;
  916. }
  917. if (saveConnections)
  918. {
  919. if (const char* const* const patchbayConns = getPatchbayConnections())
  920. {
  921. if (! firstPlugin)
  922. out << "\n";
  923. out << " <Patchbay>\n";
  924. for (int i=0; patchbayConns[i] != nullptr && patchbayConns[i+1] != nullptr; ++i, ++i )
  925. {
  926. const char* const connSource(patchbayConns[i]);
  927. const char* const connTarget(patchbayConns[i+1]);
  928. CARLA_SAFE_ASSERT_CONTINUE(connSource != nullptr && connSource[0] != '\0');
  929. CARLA_SAFE_ASSERT_CONTINUE(connTarget != nullptr && connTarget[0] != '\0');
  930. out << " <Connection>\n";
  931. out << " <Source>" << connSource << "</Source>\n";
  932. out << " <Target>" << connTarget << "</Target>\n";
  933. out << " </Connection>\n";
  934. }
  935. out << " </Patchbay>\n";
  936. }
  937. }
  938. #endif
  939. out << "</CARLA-PROJECT>\n";
  940. File file(filename);
  941. if (file.replaceWithData(out.getData(), out.getDataSize()))
  942. return true;
  943. setLastError("Failed to write file");
  944. return false;
  945. }
  946. // -----------------------------------------------------------------------
  947. // Information (base)
  948. uint CarlaEngine::getHints() const noexcept
  949. {
  950. return pData->hints;
  951. }
  952. uint32_t CarlaEngine::getBufferSize() const noexcept
  953. {
  954. return pData->bufferSize;
  955. }
  956. double CarlaEngine::getSampleRate() const noexcept
  957. {
  958. return pData->sampleRate;
  959. }
  960. const char* CarlaEngine::getName() const noexcept
  961. {
  962. return pData->name;
  963. }
  964. EngineProcessMode CarlaEngine::getProccessMode() const noexcept
  965. {
  966. return pData->options.processMode;
  967. }
  968. const EngineOptions& CarlaEngine::getOptions() const noexcept
  969. {
  970. return pData->options;
  971. }
  972. const EngineTimeInfo& CarlaEngine::getTimeInfo() const noexcept
  973. {
  974. return pData->timeInfo;
  975. }
  976. // -----------------------------------------------------------------------
  977. // Information (peaks)
  978. float CarlaEngine::getInputPeak(const uint pluginId, const bool isLeft) const noexcept
  979. {
  980. CARLA_SAFE_ASSERT_RETURN(pluginId < pData->curPluginCount, 0.0f);
  981. return pData->plugins[pluginId].insPeak[isLeft ? 0 : 1];
  982. }
  983. float CarlaEngine::getOutputPeak(const uint pluginId, const bool isLeft) const noexcept
  984. {
  985. CARLA_SAFE_ASSERT_RETURN(pluginId < pData->curPluginCount, 0.0f);
  986. return pData->plugins[pluginId].outsPeak[isLeft ? 0 : 1];
  987. }
  988. // -----------------------------------------------------------------------
  989. // Callback
  990. void CarlaEngine::callback(const EngineCallbackOpcode action, const uint pluginId, const int value1, const int value2, const float value3, const char* const valueStr) noexcept
  991. {
  992. carla_debug("CarlaEngine::callback(%i:%s, %i, %i, %i, %f, \"%s\")", action, EngineCallbackOpcode2Str(action), pluginId, value1, value2, value3, valueStr);
  993. #ifdef BUILD_BRIDGE
  994. if (pData->isIdling)
  995. #else
  996. if (pData->isIdling && action != ENGINE_CALLBACK_PATCHBAY_CLIENT_DATA_CHANGED)
  997. #endif
  998. {
  999. carla_stdout("callback while idling (%i:%s, %i, %i, %i, %f, \"%s\")", action, EngineCallbackOpcode2Str(action), pluginId, value1, value2, value3, valueStr);
  1000. }
  1001. if (action == ENGINE_CALLBACK_IDLE)
  1002. {
  1003. ++pData->isIdling;
  1004. }
  1005. #ifdef BUILD_BRIDGE
  1006. else if (pData->oscData != nullptr)
  1007. {
  1008. switch (action)
  1009. {
  1010. case ENGINE_CALLBACK_PARAMETER_VALUE_CHANGED:
  1011. CARLA_SAFE_ASSERT_BREAK(value1 >= 0);
  1012. oscSend_bridge_parameter_value(static_cast<uint>(value1), value3);
  1013. break;
  1014. case ENGINE_CALLBACK_PARAMETER_DEFAULT_CHANGED:
  1015. CARLA_SAFE_ASSERT_BREAK(value1 >= 0);
  1016. oscSend_bridge_default_value(static_cast<uint>(value1), value3);
  1017. break;
  1018. case ENGINE_CALLBACK_PROGRAM_CHANGED:
  1019. CARLA_SAFE_ASSERT_BREAK(value1 >= -1);
  1020. oscSend_bridge_current_program(value1);
  1021. break;
  1022. case ENGINE_CALLBACK_MIDI_PROGRAM_CHANGED:
  1023. CARLA_SAFE_ASSERT_BREAK(value1 >= -1);
  1024. oscSend_bridge_current_midi_program(value1);
  1025. break;
  1026. case ENGINE_CALLBACK_UI_STATE_CHANGED:
  1027. if (value1 != 1)
  1028. oscSend_bridge_configure("CarlaBridgeHideGUI", "");
  1029. break;
  1030. default:
  1031. break;
  1032. }
  1033. }
  1034. #endif
  1035. if (pData->callback != nullptr)
  1036. {
  1037. try {
  1038. pData->callback(pData->callbackPtr, action, pluginId, value1, value2, value3, valueStr);
  1039. } CARLA_SAFE_EXCEPTION("callback");
  1040. }
  1041. if (action == ENGINE_CALLBACK_IDLE)
  1042. --pData->isIdling;
  1043. }
  1044. void CarlaEngine::setCallback(const EngineCallbackFunc func, void* const ptr) noexcept
  1045. {
  1046. carla_debug("CarlaEngine::setCallback(%p, %p)", func, ptr);
  1047. pData->callback = func;
  1048. pData->callbackPtr = ptr;
  1049. }
  1050. // -----------------------------------------------------------------------
  1051. // File Callback
  1052. const char* CarlaEngine::runFileCallback(const FileCallbackOpcode action, const bool isDir, const char* const title, const char* const filter) noexcept
  1053. {
  1054. CARLA_SAFE_ASSERT_RETURN(title != nullptr && title[0] != '\0', nullptr);
  1055. CARLA_SAFE_ASSERT_RETURN(filter != nullptr, nullptr);
  1056. carla_debug("CarlaEngine::runFileCallback(%i:%s, %s, \"%s\", \"%s\")", action, FileCallbackOpcode2Str(action), bool2str(isDir), title, filter);
  1057. const char* ret = nullptr;
  1058. if (pData->fileCallback != nullptr)
  1059. {
  1060. try {
  1061. ret = pData->fileCallback(pData->fileCallbackPtr, action, isDir, title, filter);
  1062. } CARLA_SAFE_EXCEPTION("runFileCallback");
  1063. }
  1064. return ret;
  1065. }
  1066. void CarlaEngine::setFileCallback(const FileCallbackFunc func, void* const ptr) noexcept
  1067. {
  1068. carla_debug("CarlaEngine::setFileCallback(%p, %p)", func, ptr);
  1069. pData->fileCallback = func;
  1070. pData->fileCallbackPtr = ptr;
  1071. }
  1072. // -----------------------------------------------------------------------
  1073. // Transport
  1074. void CarlaEngine::transportPlay() noexcept
  1075. {
  1076. pData->time.playing = true;
  1077. }
  1078. void CarlaEngine::transportPause() noexcept
  1079. {
  1080. pData->time.playing = false;
  1081. }
  1082. void CarlaEngine::transportRelocate(const uint64_t frame) noexcept
  1083. {
  1084. pData->time.frame = frame;
  1085. }
  1086. // -----------------------------------------------------------------------
  1087. // Error handling
  1088. const char* CarlaEngine::getLastError() const noexcept
  1089. {
  1090. return pData->lastError;
  1091. }
  1092. void CarlaEngine::setLastError(const char* const error) const noexcept
  1093. {
  1094. pData->lastError = error;
  1095. }
  1096. void CarlaEngine::setAboutToClose() noexcept
  1097. {
  1098. carla_debug("CarlaEngine::setAboutToClose()");
  1099. pData->aboutToClose = true;
  1100. }
  1101. // -----------------------------------------------------------------------
  1102. // Global options
  1103. void CarlaEngine::setOption(const EngineOption option, const int value, const char* const valueStr) noexcept
  1104. {
  1105. carla_debug("CarlaEngine::setOption(%i:%s, %i, \"%s\")", option, EngineOption2Str(option), value, valueStr);
  1106. if (isRunning() && (option == ENGINE_OPTION_PROCESS_MODE || option == ENGINE_OPTION_AUDIO_NUM_PERIODS || option == ENGINE_OPTION_AUDIO_DEVICE))
  1107. return carla_stderr("CarlaEngine::setOption(%i:%s, %i, \"%s\") - Cannot set this option while engine is running!", option, EngineOption2Str(option), value, valueStr);
  1108. switch (option)
  1109. {
  1110. case ENGINE_OPTION_DEBUG:
  1111. case ENGINE_OPTION_NSM_INIT:
  1112. break;
  1113. case ENGINE_OPTION_PROCESS_MODE:
  1114. CARLA_SAFE_ASSERT_RETURN(value >= ENGINE_PROCESS_MODE_SINGLE_CLIENT && value <= ENGINE_PROCESS_MODE_BRIDGE,);
  1115. pData->options.processMode = static_cast<EngineProcessMode>(value);
  1116. break;
  1117. case ENGINE_OPTION_TRANSPORT_MODE:
  1118. CARLA_SAFE_ASSERT_RETURN(value >= ENGINE_TRANSPORT_MODE_INTERNAL && value <= ENGINE_TRANSPORT_MODE_BRIDGE,);
  1119. pData->options.transportMode = static_cast<EngineTransportMode>(value);
  1120. break;
  1121. case ENGINE_OPTION_FORCE_STEREO:
  1122. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1123. pData->options.forceStereo = (value != 0);
  1124. break;
  1125. case ENGINE_OPTION_PREFER_PLUGIN_BRIDGES:
  1126. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1127. pData->options.preferPluginBridges = (value != 0);
  1128. break;
  1129. case ENGINE_OPTION_PREFER_UI_BRIDGES:
  1130. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1131. pData->options.preferUiBridges = (value != 0);
  1132. break;
  1133. case ENGINE_OPTION_UIS_ALWAYS_ON_TOP:
  1134. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1135. pData->options.uisAlwaysOnTop = (value != 0);
  1136. break;
  1137. case ENGINE_OPTION_MAX_PARAMETERS:
  1138. CARLA_SAFE_ASSERT_RETURN(value >= 0,);
  1139. pData->options.maxParameters = static_cast<uint>(value);
  1140. break;
  1141. case ENGINE_OPTION_UI_BRIDGES_TIMEOUT:
  1142. CARLA_SAFE_ASSERT_RETURN(value >= 0,);
  1143. pData->options.uiBridgesTimeout = static_cast<uint>(value);
  1144. break;
  1145. case ENGINE_OPTION_AUDIO_NUM_PERIODS:
  1146. CARLA_SAFE_ASSERT_RETURN(value >= 2 && value <= 3,);
  1147. pData->options.audioNumPeriods = static_cast<uint>(value);
  1148. break;
  1149. case ENGINE_OPTION_AUDIO_BUFFER_SIZE:
  1150. CARLA_SAFE_ASSERT_RETURN(value >= 8,);
  1151. pData->options.audioBufferSize = static_cast<uint>(value);
  1152. break;
  1153. case ENGINE_OPTION_AUDIO_SAMPLE_RATE:
  1154. CARLA_SAFE_ASSERT_RETURN(value >= 22050,);
  1155. pData->options.audioSampleRate = static_cast<uint>(value);
  1156. break;
  1157. case ENGINE_OPTION_AUDIO_DEVICE:
  1158. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr,);
  1159. if (pData->options.audioDevice != nullptr)
  1160. delete[] pData->options.audioDevice;
  1161. pData->options.audioDevice = carla_strdup_safe(valueStr);
  1162. break;
  1163. case ENGINE_OPTION_PATH_BINARIES:
  1164. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1165. if (pData->options.binaryDir != nullptr)
  1166. delete[] pData->options.binaryDir;
  1167. pData->options.binaryDir = carla_strdup_safe(valueStr);
  1168. break;
  1169. case ENGINE_OPTION_PATH_RESOURCES:
  1170. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1171. if (pData->options.resourceDir != nullptr)
  1172. delete[] pData->options.resourceDir;
  1173. pData->options.resourceDir = carla_strdup_safe(valueStr);
  1174. break;
  1175. case ENGINE_OPTION_FRONTEND_WIN_ID:
  1176. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1177. const long long winId(std::strtoll(valueStr, nullptr, 16));
  1178. CARLA_SAFE_ASSERT_RETURN(winId >= 0,);
  1179. pData->options.frontendWinId = static_cast<uintptr_t>(winId);
  1180. break;
  1181. }
  1182. }
  1183. // -----------------------------------------------------------------------
  1184. // OSC Stuff
  1185. #ifdef BUILD_BRIDGE
  1186. bool CarlaEngine::isOscBridgeRegistered() const noexcept
  1187. {
  1188. return (pData->oscData != nullptr);
  1189. }
  1190. #else
  1191. bool CarlaEngine::isOscControlRegistered() const noexcept
  1192. {
  1193. return pData->osc.isControlRegistered();
  1194. }
  1195. #endif
  1196. void CarlaEngine::idleOsc() const noexcept
  1197. {
  1198. pData->osc.idle();
  1199. }
  1200. const char* CarlaEngine::getOscServerPathTCP() const noexcept
  1201. {
  1202. return pData->osc.getServerPathTCP();
  1203. }
  1204. const char* CarlaEngine::getOscServerPathUDP() const noexcept
  1205. {
  1206. return pData->osc.getServerPathUDP();
  1207. }
  1208. #ifdef BUILD_BRIDGE
  1209. void CarlaEngine::setOscBridgeData(CarlaOscData* const oscData) const noexcept
  1210. {
  1211. pData->oscData = oscData;
  1212. }
  1213. #endif
  1214. // -----------------------------------------------------------------------
  1215. // Helper functions
  1216. EngineEvent* CarlaEngine::getInternalEventBuffer(const bool isInput) const noexcept
  1217. {
  1218. return isInput ? pData->events.in : pData->events.out;
  1219. }
  1220. void CarlaEngine::registerEnginePlugin(const uint id, CarlaPlugin* const plugin) noexcept
  1221. {
  1222. CARLA_SAFE_ASSERT_RETURN(id == pData->curPluginCount,);
  1223. carla_debug("CarlaEngine::registerEnginePlugin(%i, %p)", id, plugin);
  1224. pData->plugins[id].plugin = plugin;
  1225. }
  1226. // -----------------------------------------------------------------------
  1227. // Internal stuff
  1228. void CarlaEngine::bufferSizeChanged(const uint32_t newBufferSize)
  1229. {
  1230. carla_debug("CarlaEngine::bufferSizeChanged(%i)", newBufferSize);
  1231. #ifndef BUILD_BRIDGE
  1232. pData->graph.setBufferSize(newBufferSize);
  1233. #endif
  1234. for (uint i=0; i < pData->curPluginCount; ++i)
  1235. {
  1236. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1237. if (plugin != nullptr && plugin->isEnabled())
  1238. plugin->bufferSizeChanged(newBufferSize);
  1239. }
  1240. callback(ENGINE_CALLBACK_BUFFER_SIZE_CHANGED, 0, static_cast<int>(newBufferSize), 0, 0.0f, nullptr);
  1241. }
  1242. void CarlaEngine::sampleRateChanged(const double newSampleRate)
  1243. {
  1244. carla_debug("CarlaEngine::sampleRateChanged(%g)", newSampleRate);
  1245. #ifndef BUILD_BRIDGE
  1246. pData->graph.setSampleRate(newSampleRate);
  1247. #endif
  1248. for (uint i=0; i < pData->curPluginCount; ++i)
  1249. {
  1250. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1251. if (plugin != nullptr && plugin->isEnabled())
  1252. plugin->sampleRateChanged(newSampleRate);
  1253. }
  1254. callback(ENGINE_CALLBACK_SAMPLE_RATE_CHANGED, 0, 0, 0, static_cast<float>(newSampleRate), nullptr);
  1255. }
  1256. void CarlaEngine::offlineModeChanged(const bool isOfflineNow)
  1257. {
  1258. carla_debug("CarlaEngine::offlineModeChanged(%s)", bool2str(isOfflineNow));
  1259. #ifndef BUILD_BRIDGE
  1260. pData->graph.setOffline(isOfflineNow);
  1261. #endif
  1262. for (uint i=0; i < pData->curPluginCount; ++i)
  1263. {
  1264. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1265. if (plugin != nullptr && plugin->isEnabled())
  1266. plugin->offlineModeChanged(isOfflineNow);
  1267. }
  1268. }
  1269. void CarlaEngine::runPendingRtEvents() noexcept
  1270. {
  1271. pData->doNextPluginAction(true);
  1272. if (pData->time.playing)
  1273. pData->time.frame += pData->bufferSize;
  1274. if (pData->options.transportMode == ENGINE_TRANSPORT_MODE_INTERNAL)
  1275. {
  1276. pData->timeInfo.playing = pData->time.playing;
  1277. pData->timeInfo.frame = pData->time.frame;
  1278. }
  1279. }
  1280. void CarlaEngine::setPluginPeaks(const uint pluginId, float const inPeaks[2], float const outPeaks[2]) noexcept
  1281. {
  1282. EnginePluginData& pluginData(pData->plugins[pluginId]);
  1283. pluginData.insPeak[0] = inPeaks[0];
  1284. pluginData.insPeak[1] = inPeaks[1];
  1285. pluginData.outsPeak[0] = outPeaks[0];
  1286. pluginData.outsPeak[1] = outPeaks[1];
  1287. }
  1288. // -----------------------------------------------------------------------
  1289. CARLA_BACKEND_END_NAMESPACE