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.

1599 lines
50KB

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