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.

1610 lines
51KB

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