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.

1630 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. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  466. pData->graph.addPlugin(plugin);
  467. }
  468. return true;
  469. }
  470. 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)
  471. {
  472. return addPlugin(BINARY_NATIVE, ptype, filename, name, label, uniqueId, extra);
  473. }
  474. bool CarlaEngine::removePlugin(const uint id)
  475. {
  476. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  477. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  478. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount != 0, "Invalid engine internal data");
  479. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  480. CARLA_SAFE_ASSERT_RETURN_ERR(id < pData->curPluginCount, "Invalid plugin Id");
  481. carla_debug("CarlaEngine::removePlugin(%i)", id);
  482. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  483. CARLA_SAFE_ASSERT_RETURN_ERR(plugin != nullptr, "Could not find plugin to remove");
  484. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  485. pData->thread.stopThread(500);
  486. #ifndef BUILD_BRIDGE
  487. const bool lockWait(isRunning() /*&& pData->options.processMode != ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS*/);
  488. const ScopedActionLock sal(pData, kEnginePostActionRemovePlugin, id, 0, lockWait);
  489. for (uint i=id; i < pData->curPluginCount; ++i)
  490. {
  491. CarlaPlugin* const plugin2(pData->plugins[i].plugin);
  492. CARLA_SAFE_ASSERT_BREAK(plugin2 != nullptr);
  493. plugin2->updateOscURL();
  494. }
  495. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  496. pData->graph.removePlugin(plugin);
  497. if (isOscControlRegistered())
  498. oscSend_control_remove_plugin(id);
  499. #else
  500. pData->curPluginCount = 0;
  501. carla_zeroStruct(pData->plugins, 1);
  502. #endif
  503. delete plugin;
  504. if (isRunning() && ! pData->aboutToClose)
  505. pData->thread.startThread();
  506. callback(ENGINE_CALLBACK_PLUGIN_REMOVED, id, 0, 0, 0.0f, nullptr);
  507. return true;
  508. }
  509. bool CarlaEngine::removeAllPlugins()
  510. {
  511. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  512. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  513. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextPluginId == pData->maxPluginNumber, "Invalid engine internal data");
  514. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  515. carla_debug("CarlaEngine::removeAllPlugins()");
  516. if (pData->curPluginCount == 0)
  517. return true;
  518. pData->thread.stopThread(500);
  519. const uint32_t curPluginCount(pData->curPluginCount);
  520. const bool lockWait(isRunning());
  521. const ScopedActionLock sal(pData, kEnginePostActionZeroCount, 0, 0, lockWait);
  522. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  523. pData->graph.removeAllPlugins();
  524. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  525. for (uint i=0; i < curPluginCount; ++i)
  526. {
  527. EnginePluginData& pluginData(pData->plugins[i]);
  528. if (pluginData.plugin != nullptr)
  529. {
  530. delete pluginData.plugin;
  531. pluginData.plugin = nullptr;
  532. }
  533. pluginData.insPeak[0] = 0.0f;
  534. pluginData.insPeak[1] = 0.0f;
  535. pluginData.outsPeak[0] = 0.0f;
  536. pluginData.outsPeak[1] = 0.0f;
  537. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  538. }
  539. if (isRunning() && ! pData->aboutToClose)
  540. pData->thread.startThread();
  541. return true;
  542. }
  543. #ifndef BUILD_BRIDGE
  544. const char* CarlaEngine::renamePlugin(const uint id, const char* const newName)
  545. {
  546. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  547. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->plugins != nullptr, "Invalid engine internal data");
  548. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->curPluginCount != 0, "Invalid engine internal data");
  549. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  550. CARLA_SAFE_ASSERT_RETURN_ERRN(id < pData->curPluginCount, "Invalid plugin Id");
  551. CARLA_SAFE_ASSERT_RETURN_ERRN(newName != nullptr && newName[0] != '\0', "Invalid plugin name");
  552. carla_debug("CarlaEngine::renamePlugin(%i, \"%s\")", id, newName);
  553. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  554. CARLA_SAFE_ASSERT_RETURN_ERRN(plugin != nullptr, "Could not find plugin to rename");
  555. CARLA_SAFE_ASSERT_RETURN_ERRN(plugin->getId() == id, "Invalid engine internal data");
  556. if (const char* const name = getUniquePluginName(newName))
  557. {
  558. plugin->setName(name);
  559. return name;
  560. }
  561. setLastError("Unable to get new unique plugin name");
  562. return nullptr;
  563. }
  564. bool CarlaEngine::clonePlugin(const uint id)
  565. {
  566. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  567. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  568. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount != 0, "Invalid engine internal data");
  569. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  570. CARLA_SAFE_ASSERT_RETURN_ERR(id < pData->curPluginCount, "Invalid plugin Id");
  571. carla_debug("CarlaEngine::clonePlugin(%i)", id);
  572. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  573. CARLA_SAFE_ASSERT_RETURN_ERR(plugin != nullptr, "Could not find plugin to clone");
  574. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  575. char label[STR_MAX+1];
  576. carla_zeroChar(label, STR_MAX+1);
  577. plugin->getLabel(label);
  578. const uint pluginCountBefore(pData->curPluginCount);
  579. if (! addPlugin(plugin->getBinaryType(), plugin->getType(), plugin->getFilename(), plugin->getName(), label, plugin->getUniqueId(), plugin->getExtraStuff()))
  580. return false;
  581. CARLA_SAFE_ASSERT_RETURN_ERR(pluginCountBefore+1 == pData->curPluginCount, "No new plugin found");
  582. if (CarlaPlugin* const newPlugin = pData->plugins[pluginCountBefore].plugin)
  583. newPlugin->loadStateSave(plugin->getStateSave());
  584. return true;
  585. }
  586. bool CarlaEngine::replacePlugin(const uint id) noexcept
  587. {
  588. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  589. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  590. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount != 0, "Invalid engine internal data");
  591. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  592. carla_debug("CarlaEngine::replacePlugin(%i)", id);
  593. // might use this to reset
  594. if (id == pData->curPluginCount || id == pData->maxPluginNumber)
  595. {
  596. pData->nextPluginId = pData->maxPluginNumber;
  597. return true;
  598. }
  599. CARLA_SAFE_ASSERT_RETURN_ERR(id < pData->curPluginCount, "Invalid plugin Id");
  600. CarlaPlugin* const plugin(pData->plugins[id].plugin);
  601. CARLA_SAFE_ASSERT_RETURN_ERR(plugin != nullptr, "Could not find plugin to replace");
  602. CARLA_SAFE_ASSERT_RETURN_ERR(plugin->getId() == id, "Invalid engine internal data");
  603. pData->nextPluginId = id;
  604. return true;
  605. }
  606. bool CarlaEngine::switchPlugins(const uint idA, const uint idB) noexcept
  607. {
  608. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  609. CARLA_SAFE_ASSERT_RETURN_ERR(pData->plugins != nullptr, "Invalid engine internal data");
  610. CARLA_SAFE_ASSERT_RETURN_ERR(pData->curPluginCount >= 2, "Invalid engine internal data");
  611. CARLA_SAFE_ASSERT_RETURN_ERR(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  612. CARLA_SAFE_ASSERT_RETURN_ERR(idA != idB, "Invalid operation, cannot switch plugin with itself");
  613. CARLA_SAFE_ASSERT_RETURN_ERR(idA < pData->curPluginCount, "Invalid plugin Id");
  614. CARLA_SAFE_ASSERT_RETURN_ERR(idB < pData->curPluginCount, "Invalid plugin Id");
  615. carla_debug("CarlaEngine::switchPlugins(%i)", idA, idB);
  616. {
  617. CarlaPlugin* const pluginA(pData->plugins[idA].plugin);
  618. CarlaPlugin* const pluginB(pData->plugins[idB].plugin);
  619. CARLA_SAFE_ASSERT_RETURN_ERR(pluginA != nullptr, "Could not find plugin to switch");
  620. CARLA_SAFE_ASSERT_RETURN_ERR(pluginA != nullptr, "Could not find plugin to switch");
  621. CARLA_SAFE_ASSERT_RETURN_ERR(pluginA->getId() == idA, "Invalid engine internal data");
  622. CARLA_SAFE_ASSERT_RETURN_ERR(pluginB->getId() == idB, "Invalid engine internal data");
  623. }
  624. pData->thread.stopThread(500);
  625. const bool lockWait(isRunning() /*&& pData->options.processMode != ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS*/);
  626. const ScopedActionLock sal(pData, kEnginePostActionSwitchPlugins, idA, idB, lockWait);
  627. CarlaPlugin* const pluginA(pData->plugins[idA].plugin);
  628. CarlaPlugin* const pluginB(pData->plugins[idB].plugin);
  629. if (pluginA != nullptr && pluginB != nullptr)
  630. {
  631. pluginA->updateOscURL();
  632. pluginB->updateOscURL();
  633. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  634. pData->graph.replacePlugin(pluginA, pluginB);
  635. }
  636. // TODO
  637. //if (isOscControlRegistered())
  638. // oscSend_control_switch_plugins(idA, idB);
  639. if (isRunning() && ! pData->aboutToClose)
  640. pData->thread.startThread();
  641. return true;
  642. }
  643. #endif
  644. CarlaPlugin* CarlaEngine::getPlugin(const uint id) const noexcept
  645. {
  646. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->plugins != nullptr, "Invalid engine internal data");
  647. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->curPluginCount != 0, "Invalid engine internal data");
  648. CARLA_SAFE_ASSERT_RETURN_ERRN(pData->nextAction.opcode == kEnginePostActionNull, "Invalid engine internal data");
  649. CARLA_SAFE_ASSERT_RETURN_ERRN(id < pData->curPluginCount, "Invalid plugin Id");
  650. return pData->plugins[id].plugin;
  651. }
  652. CarlaPlugin* CarlaEngine::getPluginUnchecked(const uint id) const noexcept
  653. {
  654. return pData->plugins[id].plugin;
  655. }
  656. const char* CarlaEngine::getUniquePluginName(const char* const name) const
  657. {
  658. CARLA_SAFE_ASSERT_RETURN(pData->nextAction.opcode == kEnginePostActionNull, nullptr);
  659. CARLA_SAFE_ASSERT_RETURN(name != nullptr && name[0] != '\0', nullptr);
  660. carla_debug("CarlaEngine::getUniquePluginName(\"%s\")", name);
  661. CarlaString sname;
  662. sname = name;
  663. if (sname.isEmpty())
  664. {
  665. sname = "(No name)";
  666. return sname.dup();
  667. }
  668. const size_t maxNameSize(carla_min<uint>(getMaxClientNameSize(), 0xff, 6) - 6); // 6 = strlen(" (10)") + 1
  669. if (maxNameSize == 0 || ! isRunning())
  670. return sname.dup();
  671. sname.truncate(maxNameSize);
  672. sname.replace(':', '.'); // ':' is used in JACK1 to split client/port names
  673. for (uint i=0; i < pData->curPluginCount; ++i)
  674. {
  675. CARLA_SAFE_ASSERT_BREAK(pData->plugins[i].plugin != nullptr);
  676. // Check if unique name doesn't exist
  677. if (const char* const pluginName = pData->plugins[i].plugin->getName())
  678. {
  679. if (sname != pluginName)
  680. continue;
  681. }
  682. // Check if string has already been modified
  683. {
  684. const size_t len(sname.length());
  685. // 1 digit, ex: " (2)"
  686. if (sname[len-4] == ' ' && sname[len-3] == '(' && sname.isDigit(len-2) && sname[len-1] == ')')
  687. {
  688. int number = sname[len-2] - '0';
  689. if (number == 9)
  690. {
  691. // next number is 10, 2 digits
  692. sname.truncate(len-4);
  693. sname += " (10)";
  694. //sname.replace(" (9)", " (10)");
  695. }
  696. else
  697. sname[len-2] = char('0' + number + 1);
  698. continue;
  699. }
  700. // 2 digits, ex: " (11)"
  701. if (sname[len-5] == ' ' && sname[len-4] == '(' && sname.isDigit(len-3) && sname.isDigit(len-2) && sname[len-1] == ')')
  702. {
  703. char n2 = sname[len-2];
  704. char n3 = sname[len-3];
  705. if (n2 == '9')
  706. {
  707. n2 = '0';
  708. n3 = static_cast<char>(n3 + 1);
  709. }
  710. else
  711. n2 = static_cast<char>(n2 + 1);
  712. sname[len-2] = n2;
  713. sname[len-3] = n3;
  714. continue;
  715. }
  716. }
  717. // Modify string if not
  718. sname += " (2)";
  719. }
  720. return sname.dup();
  721. }
  722. // -----------------------------------------------------------------------
  723. // Project management
  724. bool CarlaEngine::loadFile(const char* const filename)
  725. {
  726. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  727. CARLA_SAFE_ASSERT_RETURN_ERR(filename != nullptr && filename[0] != '\0', "Invalid filename");
  728. carla_debug("CarlaEngine::loadFile(\"%s\")", filename);
  729. File file(filename);
  730. CARLA_SAFE_ASSERT_RETURN_ERR(file.existsAsFile(), "Requested file does not exist or is not a readable file");
  731. CarlaString baseName(file.getFileName().toRawUTF8());
  732. CarlaString extension(file.getFileExtension().replace(".","").toLowerCase().toRawUTF8());
  733. // -------------------------------------------------------------------
  734. if (extension == "carxp" || extension == "carxs")
  735. return loadProject(filename);
  736. // -------------------------------------------------------------------
  737. if (extension == "gig")
  738. return addPlugin(PLUGIN_GIG, filename, baseName, baseName, 0, nullptr);
  739. if (extension == "sf2")
  740. return addPlugin(PLUGIN_SF2, filename, baseName, baseName, 0, nullptr);
  741. if (extension == "sfz")
  742. return addPlugin(PLUGIN_SFZ, filename, baseName, baseName, 0, nullptr);
  743. // -------------------------------------------------------------------
  744. if (extension == "aif" || extension == "aiff" || extension == "bwf" || extension == "flac" || extension == "ogg" || extension == "wav")
  745. {
  746. if (addPlugin(PLUGIN_INTERNAL, nullptr, baseName, "audiofile", 0, nullptr))
  747. {
  748. if (CarlaPlugin* const plugin = getPlugin(pData->curPluginCount-1))
  749. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "file", filename, true);
  750. return true;
  751. }
  752. return false;
  753. }
  754. // -------------------------------------------------------------------
  755. if (extension == "mid" || extension == "midi")
  756. {
  757. if (addPlugin(PLUGIN_INTERNAL, nullptr, baseName, "midifile", 0, nullptr))
  758. {
  759. if (CarlaPlugin* const plugin = getPlugin(pData->curPluginCount-1))
  760. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, "file", filename, true);
  761. return true;
  762. }
  763. return false;
  764. }
  765. // -------------------------------------------------------------------
  766. // ZynAddSubFX
  767. if (extension == "xmz" || extension == "xiz")
  768. {
  769. #ifdef WANT_ZYNADDSUBFX
  770. if (addPlugin(PLUGIN_INTERNAL, nullptr, baseName, "zynaddsubfx", 0, nullptr))
  771. {
  772. if (CarlaPlugin* const plugin = getPlugin(pData->curPluginCount-1))
  773. plugin->setCustomData(CUSTOM_DATA_TYPE_STRING, (extension == "xmz") ? "CarlaAlternateFile1" : "CarlaAlternateFile2", filename, true);
  774. return true;
  775. }
  776. return false;
  777. #else
  778. setLastError("This Carla build does not have ZynAddSubFX support");
  779. return false;
  780. #endif
  781. }
  782. // -------------------------------------------------------------------
  783. setLastError("Unknown file extension");
  784. return false;
  785. }
  786. bool CarlaEngine::loadProject(const char* const filename)
  787. {
  788. CARLA_SAFE_ASSERT_RETURN_ERR(pData->isIdling == 0, "An operation is still being processed, please wait for it to finish");
  789. CARLA_SAFE_ASSERT_RETURN_ERR(filename != nullptr && filename[0] != '\0', "Invalid filename");
  790. carla_debug("CarlaEngine::loadProject(\"%s\")", filename);
  791. File file(filename);
  792. CARLA_SAFE_ASSERT_RETURN_ERR(file.existsAsFile(), "Requested file does not exist or is not a readable file");
  793. XmlDocument xml(file);
  794. ScopedPointer<XmlElement> xmlElement(xml.getDocumentElement(true));
  795. CARLA_SAFE_ASSERT_RETURN_ERR(xmlElement != nullptr, "Failed to parse project file");
  796. const String& xmlType(xmlElement->getTagName());
  797. const bool isPreset(xmlType.equalsIgnoreCase("carla-preset"));
  798. if (! (xmlType.equalsIgnoreCase("carla-project") || isPreset))
  799. {
  800. setLastError("Not a valid Carla project or preset file");
  801. return false;
  802. }
  803. // completely load file
  804. xmlElement = xml.getDocumentElement(false);
  805. CARLA_SAFE_ASSERT_RETURN_ERR(xmlElement != nullptr, "Failed to completely parse project file");
  806. // handle plugins first
  807. for (XmlElement* elem = xmlElement->getFirstChildElement(); elem != nullptr; elem = elem->getNextElement())
  808. {
  809. const String& tagName(elem->getTagName());
  810. if (isPreset || tagName.equalsIgnoreCase("plugin"))
  811. {
  812. StateSave stateSave;
  813. stateSave.fillFromXmlElement(isPreset ? xmlElement.get() : elem);
  814. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  815. CARLA_SAFE_ASSERT_CONTINUE(stateSave.type != nullptr);
  816. const void* extraStuff = nullptr;
  817. // check if using GIG or SF2 16outs
  818. static const char kUse16OutsSuffix[] = " (16 outs)";
  819. const BinaryType btype(getBinaryTypeFromFile(stateSave.binary));
  820. const PluginType ptype(getPluginTypeFromString(stateSave.type));
  821. if (CarlaString(stateSave.label).endsWith(kUse16OutsSuffix))
  822. {
  823. if (ptype == PLUGIN_GIG || ptype == PLUGIN_SF2)
  824. extraStuff = "true";
  825. }
  826. // TODO - proper find&load plugins
  827. if (addPlugin(btype, ptype, stateSave.binary, stateSave.name, stateSave.label, stateSave.uniqueId, extraStuff))
  828. {
  829. if (CarlaPlugin* const plugin = getPlugin(pData->curPluginCount-1))
  830. plugin->loadStateSave(stateSave);
  831. }
  832. else
  833. carla_stderr2("Failed to load a plugin, error was:\n%s", getLastError());
  834. }
  835. if (isPreset)
  836. return true;
  837. }
  838. #ifndef BUILD_BRIDGE
  839. callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  840. // if we're running inside some session-manager, let them handle the connections
  841. if (pData->options.processMode != ENGINE_PROCESS_MODE_PATCHBAY)
  842. {
  843. if (std::getenv("CARLA_DONT_MANAGE_CONNECTIONS") != nullptr || std::getenv("LADISH_APP_NAME") != nullptr || std::getenv("NSM_URL") != nullptr)
  844. return true;
  845. }
  846. // now handle connections
  847. for (XmlElement* elem = xmlElement->getFirstChildElement(); elem != nullptr; elem = elem->getNextElement())
  848. {
  849. const String& tagName(elem->getTagName());
  850. if (tagName.equalsIgnoreCase("patchbay"))
  851. {
  852. CarlaString sourcePort, targetPort;
  853. for (XmlElement* patchElem = elem->getFirstChildElement(); patchElem != nullptr; patchElem = patchElem->getNextElement())
  854. {
  855. const String& patchTag(patchElem->getTagName());
  856. sourcePort.clear();
  857. targetPort.clear();
  858. if (! patchTag.equalsIgnoreCase("connection"))
  859. continue;
  860. for (XmlElement* connElem = patchElem->getFirstChildElement(); connElem != nullptr; connElem = connElem->getNextElement())
  861. {
  862. const String& tag(connElem->getTagName());
  863. const String text(connElem->getAllSubText().trim());
  864. if (tag.equalsIgnoreCase("source"))
  865. sourcePort = text.toRawUTF8();
  866. else if (tag.equalsIgnoreCase("target"))
  867. targetPort = text.toRawUTF8();
  868. }
  869. if (sourcePort.isNotEmpty() && targetPort.isNotEmpty())
  870. restorePatchbayConnection(sourcePort, targetPort);
  871. }
  872. break;
  873. }
  874. }
  875. #endif
  876. return true;
  877. }
  878. bool CarlaEngine::saveProject(const char* const filename)
  879. {
  880. CARLA_SAFE_ASSERT_RETURN_ERR(filename != nullptr && filename[0] != '\0', "Invalid filename");
  881. carla_debug("CarlaEngine::saveProject(\"%s\")", filename);
  882. MemoryOutputStream out;
  883. out << "<?xml version='1.0' encoding='UTF-8'?>\n";
  884. out << "<!DOCTYPE CARLA-PROJECT>\n";
  885. out << "<CARLA-PROJECT VERSION='2.0'>\n";
  886. bool firstPlugin = true;
  887. char strBuf[STR_MAX+1];
  888. for (uint i=0; i < pData->curPluginCount; ++i)
  889. {
  890. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  891. if (plugin != nullptr && plugin->isEnabled())
  892. {
  893. if (! firstPlugin)
  894. out << "\n";
  895. strBuf[0] = '\0';
  896. plugin->getRealName(strBuf);
  897. //if (strBuf[0] != '\0')
  898. // out << QString(" <!-- %1 -->\n").arg(xmlSafeString(strBuf, true));
  899. out << " <Plugin>\n";
  900. out << plugin->getStateSave().toString();
  901. out << " </Plugin>\n";
  902. firstPlugin = false;
  903. }
  904. }
  905. #ifndef BUILD_BRIDGE
  906. bool saveConnections = true;
  907. // if we're running inside some session-manager, let them handle the connections
  908. if (pData->options.processMode != ENGINE_PROCESS_MODE_PATCHBAY)
  909. {
  910. if (std::getenv("CARLA_DONT_MANAGE_CONNECTIONS") != nullptr || std::getenv("LADISH_APP_NAME") != nullptr || std::getenv("NSM_URL") != nullptr)
  911. saveConnections = false;
  912. }
  913. if (saveConnections)
  914. {
  915. if (const char* const* patchbayConns = getPatchbayConnections())
  916. {
  917. if (! firstPlugin)
  918. out << "\n";
  919. out << " <Patchbay>\n";
  920. for (int i=0; patchbayConns[i] != nullptr && patchbayConns[i+1] != nullptr; ++i, ++i )
  921. {
  922. const char* const connSource(patchbayConns[i]);
  923. const char* const connTarget(patchbayConns[i+1]);
  924. CARLA_SAFE_ASSERT_CONTINUE(connSource != nullptr && connSource[0] != '\0');
  925. CARLA_SAFE_ASSERT_CONTINUE(connTarget != nullptr && connTarget[0] != '\0');
  926. out << " <Connection>\n";
  927. out << " <Source>" << connSource << "</Source>\n";
  928. out << " <Target>" << connTarget << "</Target>\n";
  929. out << " </Connection>\n";
  930. }
  931. out << " </Patchbay>\n";
  932. }
  933. }
  934. #endif
  935. out << "</CARLA-PROJECT>\n";
  936. File file(filename);
  937. if (file.replaceWithData(out.getData(), out.getDataSize()))
  938. return true;
  939. setLastError("Failed to write file");
  940. return false;
  941. }
  942. // -----------------------------------------------------------------------
  943. // Information (base)
  944. uint CarlaEngine::getHints() const noexcept
  945. {
  946. return pData->hints;
  947. }
  948. uint32_t CarlaEngine::getBufferSize() const noexcept
  949. {
  950. return pData->bufferSize;
  951. }
  952. double CarlaEngine::getSampleRate() const noexcept
  953. {
  954. return pData->sampleRate;
  955. }
  956. const char* CarlaEngine::getName() const noexcept
  957. {
  958. return pData->name;
  959. }
  960. EngineProcessMode CarlaEngine::getProccessMode() const noexcept
  961. {
  962. return pData->options.processMode;
  963. }
  964. const EngineOptions& CarlaEngine::getOptions() const noexcept
  965. {
  966. return pData->options;
  967. }
  968. const EngineTimeInfo& CarlaEngine::getTimeInfo() const noexcept
  969. {
  970. return pData->timeInfo;
  971. }
  972. // -----------------------------------------------------------------------
  973. // Information (peaks)
  974. float CarlaEngine::getInputPeak(const uint pluginId, const bool isLeft) const noexcept
  975. {
  976. CARLA_SAFE_ASSERT_RETURN(pluginId < pData->curPluginCount, 0.0f);
  977. return pData->plugins[pluginId].insPeak[isLeft ? 0 : 1];
  978. }
  979. float CarlaEngine::getOutputPeak(const uint pluginId, const bool isLeft) const noexcept
  980. {
  981. CARLA_SAFE_ASSERT_RETURN(pluginId < pData->curPluginCount, 0.0f);
  982. return pData->plugins[pluginId].outsPeak[isLeft ? 0 : 1];
  983. }
  984. // -----------------------------------------------------------------------
  985. // Callback
  986. void CarlaEngine::callback(const EngineCallbackOpcode action, const uint pluginId, const int value1, const int value2, const float value3, const char* const valueStr) noexcept
  987. {
  988. carla_debug("CarlaEngine::callback(%i:%s, %i, %i, %i, %f, \"%s\")", action, EngineCallbackOpcode2Str(action), pluginId, value1, value2, value3, valueStr);
  989. #ifdef BUILD_BRIDGE
  990. if (pData->isIdling)
  991. #else
  992. if (pData->isIdling && action != ENGINE_CALLBACK_PATCHBAY_CLIENT_DATA_CHANGED)
  993. #endif
  994. {
  995. carla_stdout("callback while idling (%i:%s, %i, %i, %i, %f, \"%s\")", action, EngineCallbackOpcode2Str(action), pluginId, value1, value2, value3, valueStr);
  996. }
  997. if (action == ENGINE_CALLBACK_IDLE)
  998. {
  999. ++pData->isIdling;
  1000. }
  1001. #ifdef BUILD_BRIDGE
  1002. else if (pData->oscData != nullptr)
  1003. {
  1004. switch (action)
  1005. {
  1006. case ENGINE_CALLBACK_PARAMETER_VALUE_CHANGED:
  1007. CARLA_SAFE_ASSERT_BREAK(value1 >= 0);
  1008. oscSend_bridge_parameter_value(static_cast<uint>(value1), value3);
  1009. break;
  1010. case ENGINE_CALLBACK_PARAMETER_DEFAULT_CHANGED:
  1011. CARLA_SAFE_ASSERT_BREAK(value1 >= 0);
  1012. oscSend_bridge_default_value(static_cast<uint>(value1), value3);
  1013. break;
  1014. case ENGINE_CALLBACK_PROGRAM_CHANGED:
  1015. CARLA_SAFE_ASSERT_BREAK(value1 >= -1);
  1016. oscSend_bridge_current_program(value1);
  1017. break;
  1018. case ENGINE_CALLBACK_MIDI_PROGRAM_CHANGED:
  1019. CARLA_SAFE_ASSERT_BREAK(value1 >= -1);
  1020. oscSend_bridge_current_midi_program(value1);
  1021. break;
  1022. case ENGINE_CALLBACK_UI_STATE_CHANGED:
  1023. if (value1 != 1)
  1024. oscSend_bridge_configure("CarlaBridgeHideGUI", "");
  1025. break;
  1026. default:
  1027. break;
  1028. }
  1029. }
  1030. #endif
  1031. if (pData->callback != nullptr)
  1032. {
  1033. try {
  1034. pData->callback(pData->callbackPtr, action, pluginId, value1, value2, value3, valueStr);
  1035. } CARLA_SAFE_EXCEPTION("callback");
  1036. }
  1037. if (action == ENGINE_CALLBACK_IDLE)
  1038. --pData->isIdling;
  1039. }
  1040. void CarlaEngine::setCallback(const EngineCallbackFunc func, void* const ptr) noexcept
  1041. {
  1042. carla_debug("CarlaEngine::setCallback(%p, %p)", func, ptr);
  1043. pData->callback = func;
  1044. pData->callbackPtr = ptr;
  1045. }
  1046. // -----------------------------------------------------------------------
  1047. // File Callback
  1048. const char* CarlaEngine::runFileCallback(const FileCallbackOpcode action, const bool isDir, const char* const title, const char* const filter) noexcept
  1049. {
  1050. CARLA_SAFE_ASSERT_RETURN(title != nullptr && title[0] != '\0', nullptr);
  1051. CARLA_SAFE_ASSERT_RETURN(filter != nullptr, nullptr);
  1052. carla_debug("CarlaEngine::runFileCallback(%i:%s, %s, \"%s\", \"%s\")", action, FileCallbackOpcode2Str(action), bool2str(isDir), title, filter);
  1053. const char* ret = nullptr;
  1054. if (pData->fileCallback != nullptr)
  1055. {
  1056. try {
  1057. ret = pData->fileCallback(pData->fileCallbackPtr, action, isDir, title, filter);
  1058. } CARLA_SAFE_EXCEPTION("runFileCallback");
  1059. }
  1060. return ret;
  1061. }
  1062. void CarlaEngine::setFileCallback(const FileCallbackFunc func, void* const ptr) noexcept
  1063. {
  1064. carla_debug("CarlaEngine::setFileCallback(%p, %p)", func, ptr);
  1065. pData->fileCallback = func;
  1066. pData->fileCallbackPtr = ptr;
  1067. }
  1068. // -----------------------------------------------------------------------
  1069. // Transport
  1070. void CarlaEngine::transportPlay() noexcept
  1071. {
  1072. pData->time.playing = true;
  1073. }
  1074. void CarlaEngine::transportPause() noexcept
  1075. {
  1076. pData->time.playing = false;
  1077. }
  1078. void CarlaEngine::transportRelocate(const uint64_t frame) noexcept
  1079. {
  1080. pData->time.frame = frame;
  1081. }
  1082. // -----------------------------------------------------------------------
  1083. // Error handling
  1084. const char* CarlaEngine::getLastError() const noexcept
  1085. {
  1086. return pData->lastError;
  1087. }
  1088. void CarlaEngine::setLastError(const char* const error) const noexcept
  1089. {
  1090. pData->lastError = error;
  1091. }
  1092. void CarlaEngine::setAboutToClose() noexcept
  1093. {
  1094. carla_debug("CarlaEngine::setAboutToClose()");
  1095. pData->aboutToClose = true;
  1096. }
  1097. // -----------------------------------------------------------------------
  1098. // Global options
  1099. void CarlaEngine::setOption(const EngineOption option, const int value, const char* const valueStr) noexcept
  1100. {
  1101. carla_debug("CarlaEngine::setOption(%i:%s, %i, \"%s\")", option, EngineOption2Str(option), value, valueStr);
  1102. if (isRunning() && (option == ENGINE_OPTION_PROCESS_MODE || option == ENGINE_OPTION_AUDIO_NUM_PERIODS || option == ENGINE_OPTION_AUDIO_DEVICE))
  1103. return carla_stderr("CarlaEngine::setOption(%i:%s, %i, \"%s\") - Cannot set this option while engine is running!", option, EngineOption2Str(option), value, valueStr);
  1104. switch (option)
  1105. {
  1106. case ENGINE_OPTION_DEBUG:
  1107. case ENGINE_OPTION_NSM_INIT:
  1108. break;
  1109. case ENGINE_OPTION_PROCESS_MODE:
  1110. CARLA_SAFE_ASSERT_RETURN(value >= ENGINE_PROCESS_MODE_SINGLE_CLIENT && value <= ENGINE_PROCESS_MODE_BRIDGE,);
  1111. pData->options.processMode = static_cast<EngineProcessMode>(value);
  1112. break;
  1113. case ENGINE_OPTION_TRANSPORT_MODE:
  1114. CARLA_SAFE_ASSERT_RETURN(value >= ENGINE_TRANSPORT_MODE_INTERNAL && value <= ENGINE_TRANSPORT_MODE_BRIDGE,);
  1115. pData->options.transportMode = static_cast<EngineTransportMode>(value);
  1116. break;
  1117. case ENGINE_OPTION_FORCE_STEREO:
  1118. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1119. pData->options.forceStereo = (value != 0);
  1120. break;
  1121. case ENGINE_OPTION_PREFER_PLUGIN_BRIDGES:
  1122. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1123. pData->options.preferPluginBridges = (value != 0);
  1124. break;
  1125. case ENGINE_OPTION_PREFER_UI_BRIDGES:
  1126. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1127. pData->options.preferUiBridges = (value != 0);
  1128. break;
  1129. case ENGINE_OPTION_UIS_ALWAYS_ON_TOP:
  1130. CARLA_SAFE_ASSERT_RETURN(value == 0 || value == 1,);
  1131. pData->options.uisAlwaysOnTop = (value != 0);
  1132. break;
  1133. case ENGINE_OPTION_MAX_PARAMETERS:
  1134. CARLA_SAFE_ASSERT_RETURN(value >= 0,);
  1135. pData->options.maxParameters = static_cast<uint>(value);
  1136. break;
  1137. case ENGINE_OPTION_UI_BRIDGES_TIMEOUT:
  1138. CARLA_SAFE_ASSERT_RETURN(value >= 0,);
  1139. pData->options.uiBridgesTimeout = static_cast<uint>(value);
  1140. break;
  1141. case ENGINE_OPTION_AUDIO_NUM_PERIODS:
  1142. CARLA_SAFE_ASSERT_RETURN(value >= 2 && value <= 3,);
  1143. pData->options.audioNumPeriods = static_cast<uint>(value);
  1144. break;
  1145. case ENGINE_OPTION_AUDIO_BUFFER_SIZE:
  1146. CARLA_SAFE_ASSERT_RETURN(value >= 8,);
  1147. pData->options.audioBufferSize = static_cast<uint>(value);
  1148. break;
  1149. case ENGINE_OPTION_AUDIO_SAMPLE_RATE:
  1150. CARLA_SAFE_ASSERT_RETURN(value >= 22050,);
  1151. pData->options.audioSampleRate = static_cast<uint>(value);
  1152. break;
  1153. case ENGINE_OPTION_AUDIO_DEVICE:
  1154. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr,);
  1155. if (pData->options.audioDevice != nullptr)
  1156. delete[] pData->options.audioDevice;
  1157. pData->options.audioDevice = carla_strdup_safe(valueStr);
  1158. break;
  1159. case ENGINE_OPTION_PATH_BINARIES:
  1160. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1161. if (pData->options.binaryDir != nullptr)
  1162. delete[] pData->options.binaryDir;
  1163. pData->options.binaryDir = carla_strdup_safe(valueStr);
  1164. break;
  1165. case ENGINE_OPTION_PATH_RESOURCES:
  1166. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1167. if (pData->options.resourceDir != nullptr)
  1168. delete[] pData->options.resourceDir;
  1169. pData->options.resourceDir = carla_strdup_safe(valueStr);
  1170. break;
  1171. case ENGINE_OPTION_FRONTEND_WIN_ID:
  1172. CARLA_SAFE_ASSERT_RETURN(valueStr != nullptr && valueStr[0] != '\0',);
  1173. const long long winId(std::strtoll(valueStr, nullptr, 16));
  1174. CARLA_SAFE_ASSERT_RETURN(winId >= 0,);
  1175. pData->options.frontendWinId = static_cast<uintptr_t>(winId);
  1176. break;
  1177. }
  1178. }
  1179. // -----------------------------------------------------------------------
  1180. // OSC Stuff
  1181. #ifdef BUILD_BRIDGE
  1182. bool CarlaEngine::isOscBridgeRegistered() const noexcept
  1183. {
  1184. return (pData->oscData != nullptr);
  1185. }
  1186. #else
  1187. bool CarlaEngine::isOscControlRegistered() const noexcept
  1188. {
  1189. return pData->osc.isControlRegistered();
  1190. }
  1191. #endif
  1192. void CarlaEngine::idleOsc() const noexcept
  1193. {
  1194. pData->osc.idle();
  1195. }
  1196. const char* CarlaEngine::getOscServerPathTCP() const noexcept
  1197. {
  1198. return pData->osc.getServerPathTCP();
  1199. }
  1200. const char* CarlaEngine::getOscServerPathUDP() const noexcept
  1201. {
  1202. return pData->osc.getServerPathUDP();
  1203. }
  1204. #ifdef BUILD_BRIDGE
  1205. void CarlaEngine::setOscBridgeData(CarlaOscData* const oscData) const noexcept
  1206. {
  1207. pData->oscData = oscData;
  1208. }
  1209. #endif
  1210. // -----------------------------------------------------------------------
  1211. // Helper functions
  1212. EngineEvent* CarlaEngine::getInternalEventBuffer(const bool isInput) const noexcept
  1213. {
  1214. return isInput ? pData->events.in : pData->events.out;
  1215. }
  1216. void CarlaEngine::registerEnginePlugin(const uint id, CarlaPlugin* const plugin) noexcept
  1217. {
  1218. CARLA_SAFE_ASSERT_RETURN(id == pData->curPluginCount,);
  1219. carla_debug("CarlaEngine::registerEnginePlugin(%i, %p)", id, plugin);
  1220. pData->plugins[id].plugin = plugin;
  1221. }
  1222. // -----------------------------------------------------------------------
  1223. // Internal stuff
  1224. void CarlaEngine::bufferSizeChanged(const uint32_t newBufferSize)
  1225. {
  1226. carla_debug("CarlaEngine::bufferSizeChanged(%i)", newBufferSize);
  1227. #ifndef BUILD_BRIDGE
  1228. pData->graph.setBufferSize(newBufferSize);
  1229. #endif
  1230. for (uint i=0; i < pData->curPluginCount; ++i)
  1231. {
  1232. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1233. if (plugin != nullptr && plugin->isEnabled())
  1234. plugin->bufferSizeChanged(newBufferSize);
  1235. }
  1236. callback(ENGINE_CALLBACK_BUFFER_SIZE_CHANGED, 0, static_cast<int>(newBufferSize), 0, 0.0f, nullptr);
  1237. }
  1238. void CarlaEngine::sampleRateChanged(const double newSampleRate)
  1239. {
  1240. carla_debug("CarlaEngine::sampleRateChanged(%g)", newSampleRate);
  1241. #ifndef BUILD_BRIDGE
  1242. pData->graph.setSampleRate(newSampleRate);
  1243. #endif
  1244. for (uint i=0; i < pData->curPluginCount; ++i)
  1245. {
  1246. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1247. if (plugin != nullptr && plugin->isEnabled())
  1248. plugin->sampleRateChanged(newSampleRate);
  1249. }
  1250. callback(ENGINE_CALLBACK_SAMPLE_RATE_CHANGED, 0, 0, 0, static_cast<float>(newSampleRate), nullptr);
  1251. }
  1252. void CarlaEngine::offlineModeChanged(const bool isOfflineNow)
  1253. {
  1254. carla_debug("CarlaEngine::offlineModeChanged(%s)", bool2str(isOfflineNow));
  1255. #ifndef BUILD_BRIDGE
  1256. pData->graph.setOffline(isOfflineNow);
  1257. #endif
  1258. for (uint i=0; i < pData->curPluginCount; ++i)
  1259. {
  1260. CarlaPlugin* const plugin(pData->plugins[i].plugin);
  1261. if (plugin != nullptr && plugin->isEnabled())
  1262. plugin->offlineModeChanged(isOfflineNow);
  1263. }
  1264. }
  1265. void CarlaEngine::runPendingRtEvents() noexcept
  1266. {
  1267. pData->doNextPluginAction(true);
  1268. if (pData->time.playing)
  1269. pData->time.frame += pData->bufferSize;
  1270. if (pData->options.transportMode == ENGINE_TRANSPORT_MODE_INTERNAL)
  1271. {
  1272. pData->timeInfo.playing = pData->time.playing;
  1273. pData->timeInfo.frame = pData->time.frame;
  1274. }
  1275. }
  1276. void CarlaEngine::setPluginPeaks(const uint pluginId, float const inPeaks[2], float const outPeaks[2]) noexcept
  1277. {
  1278. EnginePluginData& pluginData(pData->plugins[pluginId]);
  1279. pluginData.insPeak[0] = inPeaks[0];
  1280. pluginData.insPeak[1] = inPeaks[1];
  1281. pluginData.outsPeak[0] = outPeaks[0];
  1282. pluginData.outsPeak[1] = outPeaks[1];
  1283. }
  1284. // -----------------------------------------------------------------------
  1285. CARLA_BACKEND_END_NAMESPACE