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.

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