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.

1593 lines
50KB

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