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.

1704 lines
67KB

  1. // SPDX-FileCopyrightText: 2011-2024 Filipe Coelho <falktx@falktx.com>
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #ifndef BUILD_BRIDGE
  4. # error This file should not be compiled if not building bridge
  5. #endif
  6. // must be first so we can undef CARLA_SAFE_*_RETURN_ERR* macros
  7. #include "CarlaPluginInternal.hpp"
  8. #undef CARLA_SAFE_ASSERT_RETURN_ERR
  9. #undef CARLA_SAFE_ASSERT_RETURN_ERRN
  10. #undef CARLA_SAFE_EXCEPTION_RETURN_ERR
  11. #undef CARLA_SAFE_EXCEPTION_RETURN_ERRN
  12. #include "CarlaEngineClient.hpp"
  13. #include "CarlaEngineInit.hpp"
  14. #include "CarlaBackendUtils.hpp"
  15. #include "CarlaBase64Utils.hpp"
  16. #include "CarlaBridgeUtils.hpp"
  17. #include "CarlaTimeUtils.hpp"
  18. #include "CarlaMIDI.h"
  19. #ifdef __SSE2_MATH__
  20. # include <xmmintrin.h>
  21. #endif
  22. #include "water/files/File.h"
  23. #include "water/misc/Time.h"
  24. // must be last
  25. #include "jackbridge/JackBridge.hpp"
  26. using water::File;
  27. using water::MemoryBlock;
  28. using water::String;
  29. CARLA_BACKEND_START_NAMESPACE
  30. // -----------------------------------------------------------------------
  31. // Bridge Engine client
  32. struct LatencyChangedCallback {
  33. virtual ~LatencyChangedCallback() noexcept {}
  34. virtual void latencyChanged(const uint32_t samples) noexcept = 0;
  35. };
  36. class CarlaEngineBridgeClient : public CarlaEngineClientForSubclassing
  37. {
  38. public:
  39. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  40. CarlaEngineBridgeClient(const CarlaEngine& engine,
  41. EngineInternalGraph& egraph,
  42. const CarlaPluginPtr plugin,
  43. LatencyChangedCallback* const cb)
  44. : CarlaEngineClientForSubclassing(engine, egraph, plugin),
  45. fLatencyCallback(cb) {}
  46. #else
  47. CarlaEngineBridgeClient(const CarlaEngine& engine, LatencyChangedCallback* const cb)
  48. : CarlaEngineClientForSubclassing(engine),
  49. fLatencyCallback(cb) {}
  50. #endif
  51. protected:
  52. void setLatency(const uint32_t samples) noexcept override
  53. {
  54. if (getLatency() == samples)
  55. return;
  56. fLatencyCallback->latencyChanged(samples);
  57. CarlaEngineClient::setLatency(samples);
  58. }
  59. private:
  60. LatencyChangedCallback* const fLatencyCallback;
  61. CARLA_DECLARE_NON_COPYABLE(CarlaEngineBridgeClient)
  62. };
  63. // -------------------------------------------------------------------
  64. struct BridgeTextReader {
  65. char* text;
  66. BridgeTextReader(BridgeNonRtClientControl& nonRtClientCtrl)
  67. : text(nullptr)
  68. {
  69. const uint32_t size = nonRtClientCtrl.readUInt();
  70. CARLA_SAFE_ASSERT_RETURN(size != 0,);
  71. text = new char[size + 1];
  72. nonRtClientCtrl.readCustomData(text, size);
  73. text[size] = '\0';
  74. }
  75. BridgeTextReader(BridgeNonRtClientControl& nonRtClientCtrl, const uint32_t size)
  76. : text(nullptr)
  77. {
  78. text = new char[size + 1];
  79. if (size != 0)
  80. nonRtClientCtrl.readCustomData(text, size);
  81. text[size] = '\0';
  82. }
  83. ~BridgeTextReader() noexcept
  84. {
  85. delete[] text;
  86. }
  87. CARLA_DECLARE_NON_COPYABLE(BridgeTextReader)
  88. };
  89. // -------------------------------------------------------------------
  90. class CarlaEngineBridge : public CarlaEngine,
  91. private CarlaThread,
  92. private LatencyChangedCallback
  93. {
  94. public:
  95. CarlaEngineBridge(const char* const audioPoolBaseName, const char* const rtClientBaseName, const char* const nonRtClientBaseName, const char* const nonRtServerBaseName)
  96. : CarlaEngine(),
  97. CarlaThread("CarlaEngineBridge"),
  98. fShmAudioPool(),
  99. fShmRtClientControl(),
  100. fShmNonRtClientControl(),
  101. fShmNonRtServerControl(),
  102. fBaseNameAudioPool(audioPoolBaseName),
  103. fBaseNameRtClientControl(rtClientBaseName),
  104. fBaseNameNonRtClientControl(nonRtClientBaseName),
  105. fBaseNameNonRtServerControl(nonRtServerBaseName),
  106. fClosingDown(false),
  107. fIsOffline(false),
  108. fFirstIdle(true),
  109. fBridgeVersion(0),
  110. fLastPingTime(UINT32_MAX)
  111. {
  112. carla_debug("CarlaEngineBridge::CarlaEngineBridge(\"%s\", \"%s\", \"%s\", \"%s\")", audioPoolBaseName, rtClientBaseName, nonRtClientBaseName, nonRtServerBaseName);
  113. }
  114. ~CarlaEngineBridge() noexcept override
  115. {
  116. carla_debug("CarlaEngineBridge::~CarlaEngineBridge()");
  117. clear();
  118. }
  119. // -------------------------------------
  120. // CarlaEngine virtual calls
  121. bool init(const char* const clientName) override
  122. {
  123. carla_debug("CarlaEngineBridge::init(\"%s\")", clientName);
  124. if (! pData->init(clientName))
  125. {
  126. setLastError("Failed to init internal data");
  127. return false;
  128. }
  129. if (! fShmAudioPool.attachClient(fBaseNameAudioPool))
  130. {
  131. pData->close();
  132. setLastError("Failed to attach to audio pool shared memory");
  133. return false;
  134. }
  135. if (! fShmRtClientControl.attachClient(fBaseNameRtClientControl))
  136. {
  137. pData->close();
  138. clear();
  139. setLastError("Failed to attach to rt client control shared memory");
  140. return false;
  141. }
  142. if (! fShmRtClientControl.mapData())
  143. {
  144. pData->close();
  145. clear();
  146. setLastError("Failed to map rt client control shared memory");
  147. return false;
  148. }
  149. if (! fShmNonRtClientControl.attachClient(fBaseNameNonRtClientControl))
  150. {
  151. pData->close();
  152. clear();
  153. setLastError("Failed to attach to non-rt client control shared memory");
  154. return false;
  155. }
  156. if (! fShmNonRtClientControl.mapData())
  157. {
  158. pData->close();
  159. clear();
  160. setLastError("Failed to map non-rt control client shared memory");
  161. return false;
  162. }
  163. if (! fShmNonRtServerControl.attachClient(fBaseNameNonRtServerControl))
  164. {
  165. pData->close();
  166. clear();
  167. setLastError("Failed to attach to non-rt server control shared memory");
  168. return false;
  169. }
  170. if (! fShmNonRtServerControl.mapData())
  171. {
  172. pData->close();
  173. clear();
  174. setLastError("Failed to map non-rt control server shared memory");
  175. return false;
  176. }
  177. PluginBridgeNonRtClientOpcode opcode;
  178. opcode = fShmNonRtClientControl.readOpcode();
  179. CARLA_SAFE_ASSERT_RETURN(opcode == kPluginBridgeNonRtClientVersion, false);
  180. const uint32_t apiVersion = fShmNonRtClientControl.readUInt();
  181. CARLA_SAFE_ASSERT_RETURN(apiVersion >= CARLA_PLUGIN_BRIDGE_API_VERSION_MINIMUM, false);
  182. const uint32_t shmRtClientDataSize = fShmNonRtClientControl.readUInt();
  183. CARLA_SAFE_ASSERT_INT2(shmRtClientDataSize == sizeof(BridgeRtClientData), shmRtClientDataSize, sizeof(BridgeRtClientData));
  184. const uint32_t shmNonRtClientDataSize = fShmNonRtClientControl.readUInt();
  185. CARLA_SAFE_ASSERT_INT2(shmNonRtClientDataSize == sizeof(BridgeNonRtClientData), shmNonRtClientDataSize, sizeof(BridgeNonRtClientData));
  186. const uint32_t shmNonRtServerDataSize = fShmNonRtClientControl.readUInt();
  187. CARLA_SAFE_ASSERT_INT2(shmNonRtServerDataSize == sizeof(BridgeNonRtServerData), shmNonRtServerDataSize, sizeof(BridgeNonRtServerData));
  188. if (shmRtClientDataSize != sizeof(BridgeRtClientData) ||
  189. shmNonRtClientDataSize != sizeof(BridgeNonRtClientData) ||
  190. shmNonRtServerDataSize != sizeof(BridgeNonRtServerData))
  191. {
  192. pData->close();
  193. clear();
  194. setLastError("Shared memory data size mismatch");
  195. return false;
  196. }
  197. opcode = fShmNonRtClientControl.readOpcode();
  198. CARLA_SAFE_ASSERT_RETURN(opcode == kPluginBridgeNonRtClientInitialSetup, false);
  199. pData->bufferSize = fShmNonRtClientControl.readUInt();
  200. pData->sampleRate = fShmNonRtClientControl.readDouble();
  201. if (pData->bufferSize == 0 || carla_isZero(pData->sampleRate))
  202. {
  203. pData->close();
  204. clear();
  205. setLastError("Shared memory has invalid data");
  206. return false;
  207. }
  208. pData->initTime(nullptr);
  209. // tell backend we're live
  210. {
  211. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  212. // kPluginBridgeNonRtServerVersion was added in API 7
  213. if (apiVersion >= 7)
  214. {
  215. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerVersion);
  216. fShmNonRtServerControl.writeUInt(CARLA_PLUGIN_BRIDGE_API_VERSION_CURRENT);
  217. }
  218. else
  219. {
  220. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerPong);
  221. }
  222. fShmNonRtServerControl.commitWrite();
  223. }
  224. startThread(true);
  225. return true;
  226. }
  227. bool close() override
  228. {
  229. carla_debug("CarlaEngineBridge::close()");
  230. fLastPingTime = UINT32_MAX;
  231. CarlaEngine::close();
  232. stopThread(5000);
  233. clear();
  234. return true;
  235. }
  236. bool hasIdleOnMainThread() const noexcept override
  237. {
  238. return true;
  239. }
  240. bool isRunning() const noexcept override
  241. {
  242. if (fClosingDown)
  243. return false;
  244. return isThreadRunning() || ! fFirstIdle;
  245. }
  246. bool isOffline() const noexcept override
  247. {
  248. return fIsOffline;
  249. }
  250. EngineType getType() const noexcept override
  251. {
  252. return kEngineTypeBridge;
  253. }
  254. const char* getCurrentDriverName() const noexcept override
  255. {
  256. return "Bridge";
  257. }
  258. void touchPluginParameter(const uint id, const uint32_t parameterId, const bool touch) noexcept override
  259. {
  260. CARLA_SAFE_ASSERT_RETURN(id == 0,);
  261. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  262. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerParameterTouch);
  263. fShmNonRtServerControl.writeUInt(parameterId);
  264. fShmNonRtServerControl.writeBool(touch);
  265. fShmNonRtServerControl.commitWrite();
  266. }
  267. CarlaEngineClient* addClient(const CarlaPluginPtr plugin) override
  268. {
  269. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  270. return new CarlaEngineBridgeClient(*this, pData->graph, plugin, this);
  271. #else
  272. return new CarlaEngineBridgeClient(*this, this);
  273. // unused
  274. (void)plugin;
  275. #endif
  276. }
  277. void idle() noexcept override
  278. {
  279. const CarlaPluginPtr plugin = pData->plugins[0].plugin;
  280. if (plugin.get() == nullptr)
  281. {
  282. if (const uint32_t length = static_cast<uint32_t>(pData->lastError.length()))
  283. {
  284. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  285. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerError);
  286. fShmNonRtServerControl.writeUInt(length);
  287. fShmNonRtServerControl.writeCustomData(pData->lastError.buffer(), length);
  288. fShmNonRtServerControl.commitWrite();
  289. }
  290. signalThreadShouldExit();
  291. callback(true, true, ENGINE_CALLBACK_QUIT, 0, 0, 0, 0, 0.0f, nullptr);
  292. return;
  293. }
  294. const bool wasFirstIdle = fFirstIdle;
  295. if (wasFirstIdle)
  296. {
  297. fFirstIdle = false;
  298. fLastPingTime = carla_gettime_ms();
  299. char bufStr[STR_MAX+1];
  300. carla_zeroChars(bufStr, STR_MAX+1);
  301. uint32_t bufStrSize;
  302. const CarlaEngineClient* const client(plugin->getEngineClient());
  303. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  304. // kPluginBridgeNonRtServerPluginInfo1
  305. {
  306. // uint/category, uint/hints, uint/optionsAvailable, uint/optionsEnabled, long/uniqueId
  307. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerPluginInfo1);
  308. fShmNonRtServerControl.writeUInt(plugin->getCategory());
  309. fShmNonRtServerControl.writeUInt(plugin->getHints());
  310. fShmNonRtServerControl.writeUInt(plugin->getOptionsAvailable());
  311. fShmNonRtServerControl.writeUInt(plugin->getOptionsEnabled());
  312. fShmNonRtServerControl.writeLong(plugin->getUniqueId());
  313. fShmNonRtServerControl.commitWrite();
  314. }
  315. // kPluginBridgeNonRtServerPluginInfo2
  316. {
  317. // uint/size, str[] (realName), uint/size, str[] (label), uint/size, str[] (maker), uint/size, str[] (copyright)
  318. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerPluginInfo2);
  319. if (! plugin->getRealName(bufStr))
  320. bufStr[0] = '\0';
  321. bufStrSize = carla_fixedValue(1U, 64U, static_cast<uint32_t>(std::strlen(bufStr)));
  322. fShmNonRtServerControl.writeUInt(bufStrSize);
  323. fShmNonRtServerControl.writeCustomData(bufStr, bufStrSize);
  324. if (! plugin->getLabel(bufStr))
  325. bufStr[0] = '\0';
  326. bufStrSize = carla_fixedValue(1U, 256U, static_cast<uint32_t>(std::strlen(bufStr)));
  327. fShmNonRtServerControl.writeUInt(bufStrSize);
  328. fShmNonRtServerControl.writeCustomData(bufStr, bufStrSize);
  329. if (! plugin->getMaker(bufStr))
  330. bufStr[0] = '\0';
  331. bufStrSize = carla_fixedValue(1U, 64U, static_cast<uint32_t>(std::strlen(bufStr)));
  332. fShmNonRtServerControl.writeUInt(bufStrSize);
  333. fShmNonRtServerControl.writeCustomData(bufStr, bufStrSize);
  334. if (! plugin->getCopyright(bufStr))
  335. bufStr[0] = '\0';
  336. bufStrSize = carla_fixedValue(1U, 64U, static_cast<uint32_t>(std::strlen(bufStr)));
  337. fShmNonRtServerControl.writeUInt(bufStrSize);
  338. fShmNonRtServerControl.writeCustomData(bufStr, bufStrSize);
  339. fShmNonRtServerControl.commitWrite();
  340. }
  341. fShmNonRtServerControl.waitIfDataIsReachingLimit();
  342. // kPluginBridgeNonRtServerAudioCount
  343. {
  344. const uint32_t aIns = plugin->getAudioInCount();
  345. const uint32_t aOuts = plugin->getAudioOutCount();
  346. // uint/ins, uint/outs
  347. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerAudioCount);
  348. fShmNonRtServerControl.writeUInt(aIns);
  349. fShmNonRtServerControl.writeUInt(aOuts);
  350. fShmNonRtServerControl.commitWrite();
  351. // kPluginBridgeNonRtServerPortName
  352. for (uint32_t i=0; i<aIns; ++i)
  353. {
  354. const char* const portName(client->getAudioPortName(true, i));
  355. CARLA_SAFE_ASSERT_CONTINUE(portName != nullptr && portName[0] != '\0');
  356. // byte/type, uint/index, uint/size, str[] (name)
  357. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerPortName);
  358. fShmNonRtServerControl.writeByte(kPluginBridgePortAudioInput);
  359. fShmNonRtServerControl.writeUInt(i);
  360. bufStrSize = static_cast<uint32_t>(std::strlen(portName));
  361. fShmNonRtServerControl.writeUInt(bufStrSize);
  362. fShmNonRtServerControl.writeCustomData(portName, bufStrSize);
  363. }
  364. // kPluginBridgeNonRtServerPortName
  365. for (uint32_t i=0; i<aOuts; ++i)
  366. {
  367. const char* const portName(client->getAudioPortName(false, i));
  368. CARLA_SAFE_ASSERT_CONTINUE(portName != nullptr && portName[0] != '\0');
  369. // byte/type, uint/index, uint/size, str[] (name)
  370. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerPortName);
  371. fShmNonRtServerControl.writeByte(kPluginBridgePortAudioOutput);
  372. fShmNonRtServerControl.writeUInt(i);
  373. bufStrSize = static_cast<uint32_t>(std::strlen(portName));
  374. fShmNonRtServerControl.writeUInt(bufStrSize);
  375. fShmNonRtServerControl.writeCustomData(portName, bufStrSize);
  376. }
  377. }
  378. fShmNonRtServerControl.waitIfDataIsReachingLimit();
  379. // kPluginBridgeNonRtServerMidiCount
  380. {
  381. // uint/ins, uint/outs
  382. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerMidiCount);
  383. fShmNonRtServerControl.writeUInt(plugin->getMidiInCount());
  384. fShmNonRtServerControl.writeUInt(plugin->getMidiOutCount());
  385. fShmNonRtServerControl.commitWrite();
  386. }
  387. fShmNonRtServerControl.waitIfDataIsReachingLimit();
  388. // kPluginBridgeNonRtServerCvCount
  389. {
  390. // uint/ins, uint/outs
  391. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerCvCount);
  392. fShmNonRtServerControl.writeUInt(plugin->getCVInCount());
  393. fShmNonRtServerControl.writeUInt(plugin->getCVOutCount());
  394. fShmNonRtServerControl.commitWrite();
  395. }
  396. fShmNonRtServerControl.waitIfDataIsReachingLimit();
  397. // kPluginBridgeNonRtServerParameter*
  398. if (const uint32_t count = plugin->getParameterCount())
  399. {
  400. // uint/count
  401. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerParameterCount);
  402. fShmNonRtServerControl.writeUInt(count);
  403. fShmNonRtServerControl.commitWrite();
  404. for (uint32_t i=0; i<count; ++i)
  405. {
  406. const ParameterData& paramData(plugin->getParameterData(i));
  407. if (paramData.type != PARAMETER_INPUT && paramData.type != PARAMETER_OUTPUT)
  408. continue;
  409. if ((paramData.hints & PARAMETER_IS_ENABLED) == 0)
  410. continue;
  411. // kPluginBridgeNonRtServerParameterData1
  412. {
  413. // uint/index, int/rindex, uint/type, uint/hints, short/cc
  414. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerParameterData1);
  415. fShmNonRtServerControl.writeUInt(i);
  416. fShmNonRtServerControl.writeInt(paramData.rindex);
  417. fShmNonRtServerControl.writeUInt(paramData.type);
  418. fShmNonRtServerControl.writeUInt(paramData.hints);
  419. fShmNonRtServerControl.writeShort(paramData.mappedControlIndex);
  420. fShmNonRtServerControl.commitWrite();
  421. }
  422. // kPluginBridgeNonRtServerParameterData2
  423. {
  424. // uint/index, uint/size, str[] (name), uint/size, str[] (symbol), uint/size, str[] (unit)
  425. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerParameterData2);
  426. fShmNonRtServerControl.writeUInt(i);
  427. if (! plugin->getParameterName(i, bufStr))
  428. std::snprintf(bufStr, STR_MAX, "Param %u", i+1);
  429. bufStrSize = carla_fixedValue(1U, 32U, static_cast<uint32_t>(std::strlen(bufStr)));
  430. fShmNonRtServerControl.writeUInt(bufStrSize);
  431. fShmNonRtServerControl.writeCustomData(bufStr, bufStrSize);
  432. if (! plugin->getParameterSymbol(i, bufStr))
  433. bufStr[0] = '\0';
  434. bufStrSize = carla_fixedValue(1U, 64U, static_cast<uint32_t>(std::strlen(bufStr)));
  435. fShmNonRtServerControl.writeUInt(bufStrSize);
  436. fShmNonRtServerControl.writeCustomData(bufStr, bufStrSize);
  437. if (! plugin->getParameterUnit(i, bufStr))
  438. bufStr[0] = '\0';
  439. bufStrSize = carla_fixedValue(1U, 32U, static_cast<uint32_t>(std::strlen(bufStr)));
  440. fShmNonRtServerControl.writeUInt(bufStrSize);
  441. fShmNonRtServerControl.writeCustomData(bufStr, bufStrSize);
  442. fShmNonRtServerControl.commitWrite();
  443. }
  444. // kPluginBridgeNonRtServerParameterRanges
  445. {
  446. const ParameterRanges& paramRanges(plugin->getParameterRanges(i));
  447. // uint/index, float/def, float/min, float/max, float/step, float/stepSmall, float/stepLarge
  448. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerParameterRanges);
  449. fShmNonRtServerControl.writeUInt(i);
  450. fShmNonRtServerControl.writeFloat(paramRanges.def);
  451. fShmNonRtServerControl.writeFloat(paramRanges.min);
  452. fShmNonRtServerControl.writeFloat(paramRanges.max);
  453. fShmNonRtServerControl.writeFloat(paramRanges.step);
  454. fShmNonRtServerControl.writeFloat(paramRanges.stepSmall);
  455. fShmNonRtServerControl.writeFloat(paramRanges.stepLarge);
  456. fShmNonRtServerControl.commitWrite();
  457. }
  458. // kPluginBridgeNonRtServerParameterValue2
  459. {
  460. // uint/index float/value (used for init/output parameters only, don't resend values)
  461. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerParameterValue2);
  462. fShmNonRtServerControl.writeUInt(i);
  463. fShmNonRtServerControl.writeFloat(plugin->getParameterValue(i));
  464. fShmNonRtServerControl.commitWrite();
  465. }
  466. fShmNonRtServerControl.waitIfDataIsReachingLimit();
  467. }
  468. }
  469. // kPluginBridgeNonRtServerProgram*
  470. if (const uint32_t count = plugin->getProgramCount())
  471. {
  472. // uint/count
  473. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerProgramCount);
  474. fShmNonRtServerControl.writeUInt(count);
  475. fShmNonRtServerControl.commitWrite();
  476. for (uint32_t i=0; i < count; ++i)
  477. {
  478. // uint/index, uint/size, str[] (name)
  479. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerProgramName);
  480. fShmNonRtServerControl.writeUInt(i);
  481. if (! plugin->getProgramName(i, bufStr))
  482. bufStr[0] = '\0';
  483. bufStrSize = carla_fixedValue(1U, 32U, static_cast<uint32_t>(std::strlen(bufStr)));
  484. fShmNonRtServerControl.writeUInt(bufStrSize);
  485. fShmNonRtServerControl.writeCustomData(bufStr, bufStrSize);
  486. fShmNonRtServerControl.commitWrite();
  487. fShmNonRtServerControl.waitIfDataIsReachingLimit();
  488. }
  489. }
  490. // kPluginBridgeNonRtServerMidiProgram*
  491. if (const uint32_t count = plugin->getMidiProgramCount())
  492. {
  493. // uint/count
  494. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerMidiProgramCount);
  495. fShmNonRtServerControl.writeUInt(count);
  496. fShmNonRtServerControl.commitWrite();
  497. for (uint32_t i=0; i < count; ++i)
  498. {
  499. const MidiProgramData& mpData(plugin->getMidiProgramData(i));
  500. CARLA_SAFE_ASSERT_CONTINUE(mpData.name != nullptr);
  501. // uint/index, uint/bank, uint/program, uint/size, str[] (name)
  502. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerMidiProgramData);
  503. fShmNonRtServerControl.writeUInt(i);
  504. fShmNonRtServerControl.writeUInt(mpData.bank);
  505. fShmNonRtServerControl.writeUInt(mpData.program);
  506. bufStrSize = carla_fixedValue(1U, 32U, static_cast<uint32_t>(std::strlen(mpData.name)));
  507. fShmNonRtServerControl.writeUInt(bufStrSize);
  508. fShmNonRtServerControl.writeCustomData(mpData.name, bufStrSize);
  509. fShmNonRtServerControl.commitWrite();
  510. fShmNonRtServerControl.waitIfDataIsReachingLimit();
  511. }
  512. }
  513. if (const uint32_t latency = plugin->getLatencyInFrames())
  514. {
  515. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerSetLatency);
  516. fShmNonRtServerControl.writeUInt(latency);
  517. fShmNonRtServerControl.commitWrite();
  518. }
  519. // ready!
  520. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerReady);
  521. fShmNonRtServerControl.commitWrite();
  522. fShmNonRtServerControl.waitIfDataIsReachingLimit();
  523. carla_stdout("Carla Bridge Ready!");
  524. fLastPingTime = carla_gettime_ms();
  525. }
  526. // send parameter outputs
  527. if (const uint32_t count = plugin->getParameterCount())
  528. {
  529. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  530. for (uint32_t i=0; i < count; ++i)
  531. {
  532. if (! plugin->isParameterOutput(i))
  533. continue;
  534. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerParameterValue2);
  535. fShmNonRtServerControl.writeUInt(i);
  536. fShmNonRtServerControl.writeFloat(plugin->getParameterValue(i));
  537. // parameter outputs are not that important, we can skip some
  538. if (! fShmNonRtServerControl.commitWrite())
  539. break;
  540. }
  541. }
  542. CarlaEngine::idle();
  543. try {
  544. handleNonRtData();
  545. } CARLA_SAFE_EXCEPTION("handleNonRtData");
  546. if (fLastPingTime != UINT32_MAX && carla_gettime_ms() > fLastPingTime + 30000 && ! wasFirstIdle)
  547. {
  548. carla_stderr("Did not receive ping message from server for 30 secs, closing...");
  549. signalThreadShouldExit();
  550. callback(true, true, ENGINE_CALLBACK_QUIT, 0, 0, 0, 0, 0.0f, nullptr);
  551. }
  552. }
  553. void callback(const bool sendHost, const bool sendOsc,
  554. const EngineCallbackOpcode action, const uint pluginId,
  555. const int value1, const int value2, const int value3,
  556. const float valuef, const char* const valueStr) noexcept override
  557. {
  558. CarlaEngine::callback(sendHost, sendOsc, action, pluginId, value1, value2, value3, valuef, valueStr);
  559. if (fClosingDown || ! sendHost)
  560. return;
  561. switch (action)
  562. {
  563. // uint/index float/value
  564. case ENGINE_CALLBACK_PARAMETER_VALUE_CHANGED: {
  565. CARLA_SAFE_ASSERT_BREAK(value1 >= 0);
  566. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  567. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerParameterValue);
  568. fShmNonRtServerControl.writeUInt(static_cast<uint>(value1));
  569. fShmNonRtServerControl.writeFloat(valuef);
  570. fShmNonRtServerControl.commitWrite();
  571. } break;
  572. // uint/index float/value
  573. case ENGINE_CALLBACK_PARAMETER_DEFAULT_CHANGED: {
  574. CARLA_SAFE_ASSERT_BREAK(value1 >= 0);
  575. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  576. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerDefaultValue);
  577. fShmNonRtServerControl.writeUInt(static_cast<uint>(value1));
  578. fShmNonRtServerControl.writeFloat(valuef);
  579. fShmNonRtServerControl.commitWrite();
  580. } break;
  581. // int/index
  582. case ENGINE_CALLBACK_PROGRAM_CHANGED: {
  583. CARLA_SAFE_ASSERT_BREAK(value1 >= -1);
  584. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  585. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerCurrentProgram);
  586. fShmNonRtServerControl.writeInt(value1);
  587. fShmNonRtServerControl.commitWrite();
  588. } break;
  589. // int/index
  590. case ENGINE_CALLBACK_MIDI_PROGRAM_CHANGED: {
  591. CARLA_SAFE_ASSERT_BREAK(value1 >= -1);
  592. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  593. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerCurrentMidiProgram);
  594. fShmNonRtServerControl.writeInt(value1);
  595. fShmNonRtServerControl.commitWrite();
  596. } break;
  597. case ENGINE_CALLBACK_UI_STATE_CHANGED:
  598. if (value1 != 1)
  599. {
  600. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  601. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerUiClosed);
  602. fShmNonRtServerControl.commitWrite();
  603. }
  604. break;
  605. case ENGINE_CALLBACK_EMBED_UI_RESIZED: {
  606. CARLA_SAFE_ASSERT_BREAK(value1 > 1);
  607. CARLA_SAFE_ASSERT_BREAK(value2 > 1);
  608. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  609. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerResizeEmbedUI);
  610. fShmNonRtServerControl.writeUInt(static_cast<uint>(value1));
  611. fShmNonRtServerControl.writeUInt(static_cast<uint>(value2));
  612. fShmNonRtServerControl.commitWrite();
  613. } break;
  614. case ENGINE_CALLBACK_RELOAD_PARAMETERS:
  615. if (const CarlaPluginPtr plugin = pData->plugins[0].plugin)
  616. {
  617. if (const uint32_t count = plugin->getParameterCount())
  618. {
  619. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  620. for (uint32_t i=0; i<count; ++i)
  621. {
  622. const ParameterData& paramData(plugin->getParameterData(i));
  623. if (paramData.type != PARAMETER_INPUT && paramData.type != PARAMETER_OUTPUT)
  624. continue;
  625. if ((paramData.hints & PARAMETER_IS_ENABLED) == 0)
  626. continue;
  627. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerParameterValue);
  628. fShmNonRtServerControl.writeUInt(i);
  629. fShmNonRtServerControl.writeFloat(plugin->getParameterValue(i));
  630. fShmNonRtServerControl.commitWrite();
  631. fShmNonRtServerControl.waitIfDataIsReachingLimit();
  632. }
  633. }
  634. }
  635. break;
  636. default:
  637. break;
  638. }
  639. }
  640. // -------------------------------------------------------------------
  641. void clear() noexcept
  642. {
  643. fShmAudioPool.clear();
  644. fShmRtClientControl.clear();
  645. fShmNonRtClientControl.clear();
  646. fShmNonRtServerControl.clear();
  647. }
  648. void handleNonRtData()
  649. {
  650. const CarlaPluginPtr plugin = pData->plugins[0].plugin;
  651. CARLA_SAFE_ASSERT_RETURN(plugin.get() != nullptr,);
  652. for (; fShmNonRtClientControl.isDataAvailableForReading();)
  653. {
  654. const PluginBridgeNonRtClientOpcode opcode = fShmNonRtClientControl.readOpcode();
  655. #ifdef DEBUG
  656. if (opcode != kPluginBridgeNonRtClientPing) {
  657. carla_debug("CarlaEngineBridge::handleNonRtData() - got opcode: %i:%s",
  658. opcode, PluginBridgeNonRtClientOpcode2str(opcode));
  659. }
  660. #endif
  661. if (opcode != kPluginBridgeNonRtClientNull &&
  662. opcode != kPluginBridgeNonRtClientPingOnOff && fLastPingTime != UINT32_MAX)
  663. fLastPingTime = carla_gettime_ms();
  664. switch (opcode)
  665. {
  666. case kPluginBridgeNonRtClientNull:
  667. break;
  668. case kPluginBridgeNonRtClientVersion: {
  669. fBridgeVersion = fShmNonRtServerControl.readUInt();
  670. CARLA_SAFE_ASSERT_UINT2(fBridgeVersion >= CARLA_PLUGIN_BRIDGE_API_VERSION_MINIMUM,
  671. fBridgeVersion, CARLA_PLUGIN_BRIDGE_API_VERSION_MINIMUM);
  672. } break;
  673. case kPluginBridgeNonRtClientPing: {
  674. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  675. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerPong);
  676. fShmNonRtServerControl.commitWrite();
  677. } break;
  678. case kPluginBridgeNonRtClientPingOnOff:
  679. fLastPingTime = fShmNonRtClientControl.readBool() ? carla_gettime_ms() : UINT32_MAX;
  680. break;
  681. case kPluginBridgeNonRtClientActivate:
  682. if (plugin->isEnabled())
  683. plugin->setActive(true, false, false);
  684. break;
  685. case kPluginBridgeNonRtClientDeactivate:
  686. if (plugin->isEnabled())
  687. plugin->setActive(false, false, false);
  688. break;
  689. case kPluginBridgeNonRtClientInitialSetup:
  690. // should never happen!!
  691. fShmNonRtServerControl.readUInt();
  692. fShmNonRtServerControl.readDouble();
  693. break;
  694. case kPluginBridgeNonRtClientSetParameterValue: {
  695. const uint32_t index(fShmNonRtClientControl.readUInt());
  696. const float value(fShmNonRtClientControl.readFloat());
  697. if (plugin->isEnabled())
  698. plugin->setParameterValue(index, value, false, false, false);
  699. break;
  700. }
  701. case kPluginBridgeNonRtClientSetParameterMidiChannel: {
  702. const uint32_t index(fShmNonRtClientControl.readUInt());
  703. const uint8_t channel(fShmNonRtClientControl.readByte());
  704. if (plugin->isEnabled())
  705. plugin->setParameterMidiChannel(index, channel, false, false);
  706. break;
  707. }
  708. case kPluginBridgeNonRtClientSetParameterMappedControlIndex: {
  709. const uint32_t index(fShmNonRtClientControl.readUInt());
  710. const int16_t ctrl(fShmNonRtClientControl.readShort());
  711. if (plugin->isEnabled())
  712. plugin->setParameterMappedControlIndex(index, ctrl, false, false, true);
  713. break;
  714. }
  715. case kPluginBridgeNonRtClientSetParameterMappedRange: {
  716. const uint32_t index = fShmNonRtClientControl.readUInt();
  717. const float minimum = fShmNonRtClientControl.readFloat();
  718. const float maximum = fShmNonRtClientControl.readFloat();
  719. if (plugin->isEnabled())
  720. plugin->setParameterMappedRange(index, minimum, maximum, false, false);
  721. break;
  722. }
  723. case kPluginBridgeNonRtClientSetProgram: {
  724. const int32_t index(fShmNonRtClientControl.readInt());
  725. if (plugin->isEnabled())
  726. plugin->setProgram(index, true, false, false);
  727. break;
  728. }
  729. case kPluginBridgeNonRtClientSetMidiProgram: {
  730. const int32_t index(fShmNonRtClientControl.readInt());
  731. if (plugin->isEnabled())
  732. plugin->setMidiProgram(index, true, false, false);
  733. break;
  734. }
  735. case kPluginBridgeNonRtClientSetCustomData: {
  736. const uint32_t maxLocalValueLen = fBridgeVersion >= 10 ? 4096 : 16384;
  737. // type
  738. const BridgeTextReader type(fShmNonRtClientControl);
  739. // key
  740. const BridgeTextReader key(fShmNonRtClientControl);
  741. // value
  742. const uint32_t valueSize = fShmNonRtClientControl.readUInt();
  743. if (valueSize > 0)
  744. {
  745. if (valueSize > maxLocalValueLen)
  746. {
  747. const BridgeTextReader bigValueFilePathTry(fShmNonRtClientControl);
  748. CARLA_SAFE_ASSERT_BREAK(bigValueFilePathTry.text[0] != '\0');
  749. if (! plugin->isEnabled()) break;
  750. String bigValueFilePath(bigValueFilePathTry.text);
  751. #ifdef CARLA_OS_WIN
  752. // check if running under Wine
  753. if (bigValueFilePath.startsWith("/"))
  754. bigValueFilePath = bigValueFilePath.replaceSection(0, 1, "Z:\\").replace("/", "\\");
  755. #endif
  756. File bigValueFile(bigValueFilePath.toRawUTF8());
  757. CARLA_SAFE_ASSERT_BREAK(bigValueFile.existsAsFile());
  758. plugin->setCustomData(type.text, key.text, bigValueFile.loadFileAsString().toRawUTF8(), true);
  759. bigValueFile.deleteFile();
  760. }
  761. else
  762. {
  763. const BridgeTextReader value(fShmNonRtClientControl, valueSize);
  764. if (plugin->isEnabled())
  765. plugin->setCustomData(type.text, key.text, value.text, true);
  766. }
  767. }
  768. else
  769. {
  770. if (plugin->isEnabled())
  771. plugin->setCustomData(type.text, key.text, "", true);
  772. }
  773. break;
  774. }
  775. case kPluginBridgeNonRtClientSetChunkDataFile: {
  776. const uint32_t size = fShmNonRtClientControl.readUInt();
  777. CARLA_SAFE_ASSERT_BREAK(size > 0);
  778. const BridgeTextReader chunkFilePathTry(fShmNonRtClientControl, size);
  779. CARLA_SAFE_ASSERT_BREAK(chunkFilePathTry.text[0] != '\0');
  780. if (! plugin->isEnabled()) break;
  781. String chunkFilePath(chunkFilePathTry.text);
  782. #ifdef CARLA_OS_WIN
  783. // check if running under Wine
  784. if (chunkFilePath.startsWith("/"))
  785. chunkFilePath = chunkFilePath.replaceSection(0, 1, "Z:\\").replace("/", "\\");
  786. #endif
  787. File chunkFile(chunkFilePath.toRawUTF8());
  788. CARLA_SAFE_ASSERT_BREAK(chunkFile.existsAsFile());
  789. String chunkDataBase64(chunkFile.loadFileAsString());
  790. chunkFile.deleteFile();
  791. CARLA_SAFE_ASSERT_BREAK(chunkDataBase64.isNotEmpty());
  792. std::vector<uint8_t> chunk(carla_getChunkFromBase64String(chunkDataBase64.toRawUTF8()));
  793. #ifdef CARLA_PROPER_CPP11_SUPPORT
  794. plugin->setChunkData(chunk.data(), chunk.size());
  795. #else
  796. plugin->setChunkData(&chunk.front(), chunk.size());
  797. #endif
  798. break;
  799. }
  800. case kPluginBridgeNonRtClientSetCtrlChannel: {
  801. const int16_t channel(fShmNonRtClientControl.readShort());
  802. CARLA_SAFE_ASSERT_BREAK(channel >= -1 && channel < MAX_MIDI_CHANNELS);
  803. if (plugin->isEnabled())
  804. plugin->setCtrlChannel(static_cast<int8_t>(channel), false, false);
  805. break;
  806. }
  807. case kPluginBridgeNonRtClientSetOption: {
  808. const uint32_t option(fShmNonRtClientControl.readUInt());
  809. const bool yesNo(fShmNonRtClientControl.readBool());
  810. if (plugin->isEnabled())
  811. plugin->setOption(option, yesNo, false);
  812. break;
  813. }
  814. case kPluginBridgeNonRtClientSetOptions: {
  815. const uint32_t options(fShmNonRtClientControl.readUInt());
  816. plugin->pData->options = options;
  817. break;
  818. }
  819. case kPluginBridgeNonRtClientSetWindowTitle: {
  820. const BridgeTextReader title(fShmNonRtClientControl);
  821. plugin->setCustomUITitle(title.text);
  822. break;
  823. }
  824. case kPluginBridgeNonRtClientGetParameterText: {
  825. const int32_t index = fShmNonRtClientControl.readInt();
  826. if (index >= 0 && plugin->isEnabled())
  827. {
  828. char bufStr[STR_MAX+1];
  829. carla_zeroChars(bufStr, STR_MAX+1);
  830. if (! plugin->getParameterText(static_cast<uint32_t>(index), bufStr))
  831. bufStr[0] = '\0';
  832. const uint32_t bufStrLen = static_cast<uint32_t>(std::strlen(bufStr));
  833. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  834. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerSetParameterText);
  835. fShmNonRtServerControl.writeInt(index);
  836. fShmNonRtServerControl.writeUInt(bufStrLen);
  837. fShmNonRtServerControl.writeCustomData(bufStr, bufStrLen);
  838. fShmNonRtServerControl.commitWrite();
  839. fShmNonRtServerControl.waitIfDataIsReachingLimit();
  840. }
  841. else
  842. {
  843. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  844. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerSetParameterText);
  845. fShmNonRtServerControl.writeInt(index);
  846. fShmNonRtServerControl.writeUInt(0);
  847. fShmNonRtServerControl.commitWrite();
  848. }
  849. break;
  850. }
  851. case kPluginBridgeNonRtClientPrepareForSave: {
  852. if (! plugin->isEnabled())
  853. {
  854. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  855. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerSaved);
  856. fShmNonRtServerControl.commitWrite();
  857. return;
  858. }
  859. plugin->prepareForSave(false);
  860. const uint32_t maxLocalValueLen = fBridgeVersion >= 10 ? 4096 : 16384;
  861. for (uint32_t i=0, count=plugin->getCustomDataCount(); i<count; ++i)
  862. {
  863. const CustomData& cdata(plugin->getCustomData(i));
  864. if (std::strcmp(cdata.type, CUSTOM_DATA_TYPE_PROPERTY) == 0)
  865. continue;
  866. const uint32_t typeLen = static_cast<uint32_t>(std::strlen(cdata.type));
  867. const uint32_t keyLen = static_cast<uint32_t>(std::strlen(cdata.key));
  868. const uint32_t valueLen = static_cast<uint32_t>(std::strlen(cdata.value));
  869. {
  870. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  871. if (valueLen > maxLocalValueLen)
  872. fShmNonRtServerControl.waitIfDataIsReachingLimit();
  873. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerSetCustomData);
  874. fShmNonRtServerControl.writeUInt(typeLen);
  875. fShmNonRtServerControl.writeCustomData(cdata.type, typeLen);
  876. fShmNonRtServerControl.writeUInt(keyLen);
  877. fShmNonRtServerControl.writeCustomData(cdata.key, keyLen);
  878. fShmNonRtServerControl.writeUInt(valueLen);
  879. if (valueLen > 0)
  880. {
  881. if (valueLen > maxLocalValueLen)
  882. {
  883. String filePath(File::getSpecialLocation(File::tempDirectory).getFullPathName());
  884. filePath += CARLA_OS_SEP_STR ".CarlaCustomData_";
  885. filePath += fShmAudioPool.getFilenameSuffix();
  886. if (File(filePath.toRawUTF8()).replaceWithText(cdata.value))
  887. {
  888. const uint32_t ulength(static_cast<uint32_t>(filePath.length()));
  889. fShmNonRtServerControl.writeUInt(ulength);
  890. fShmNonRtServerControl.writeCustomData(filePath.toRawUTF8(), ulength);
  891. }
  892. else
  893. {
  894. fShmNonRtServerControl.writeUInt(0);
  895. }
  896. }
  897. else
  898. {
  899. fShmNonRtServerControl.writeCustomData(cdata.value, valueLen);
  900. }
  901. }
  902. fShmNonRtServerControl.commitWrite();
  903. fShmNonRtServerControl.waitIfDataIsReachingLimit();
  904. }
  905. }
  906. if (plugin->getOptionsEnabled() & PLUGIN_OPTION_USE_CHUNKS)
  907. {
  908. void* data = nullptr;
  909. if (const std::size_t dataSize = plugin->getChunkData(&data))
  910. {
  911. CARLA_SAFE_ASSERT_BREAK(data != nullptr);
  912. CarlaString dataBase64 = CarlaString::asBase64(data, dataSize);
  913. CARLA_SAFE_ASSERT_BREAK(dataBase64.length() > 0);
  914. String filePath(File::getSpecialLocation(File::tempDirectory).getFullPathName());
  915. filePath += CARLA_OS_SEP_STR ".CarlaChunk_";
  916. filePath += fShmAudioPool.getFilenameSuffix();
  917. if (File(filePath.toRawUTF8()).replaceWithText(dataBase64.buffer()))
  918. {
  919. const uint32_t ulength(static_cast<uint32_t>(filePath.length()));
  920. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  921. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerSetChunkDataFile);
  922. fShmNonRtServerControl.writeUInt(ulength);
  923. fShmNonRtServerControl.writeCustomData(filePath.toRawUTF8(), ulength);
  924. fShmNonRtServerControl.commitWrite();
  925. }
  926. }
  927. }
  928. {
  929. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  930. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerSaved);
  931. fShmNonRtServerControl.commitWrite();
  932. }
  933. break;
  934. }
  935. case kPluginBridgeNonRtClientRestoreLV2State:
  936. if (plugin->isEnabled())
  937. plugin->restoreLV2State(false);
  938. break;
  939. case kPluginBridgeNonRtClientShowUI:
  940. if (plugin->isEnabled())
  941. plugin->showCustomUI(true);
  942. break;
  943. case kPluginBridgeNonRtClientHideUI:
  944. if (plugin->isEnabled())
  945. plugin->showCustomUI(false);
  946. break;
  947. case kPluginBridgeNonRtClientEmbedUI: {
  948. const uint64_t winId = fShmNonRtClientControl.readULong();
  949. uint64_t resp = 0;
  950. if (plugin->isEnabled())
  951. resp = reinterpret_cast<uint64_t>(plugin->embedCustomUI(reinterpret_cast<void*>(winId)));
  952. if (resp == 0)
  953. resp = 1;
  954. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  955. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerRespEmbedUI);
  956. fShmNonRtServerControl.writeULong(resp);
  957. fShmNonRtServerControl.commitWrite();
  958. break;
  959. }
  960. case kPluginBridgeNonRtClientUiParameterChange: {
  961. const uint32_t index = fShmNonRtClientControl.readUInt();
  962. const float value = fShmNonRtClientControl.readFloat();
  963. if (plugin->isEnabled())
  964. plugin->uiParameterChange(index, value);
  965. break;
  966. }
  967. case kPluginBridgeNonRtClientUiProgramChange: {
  968. const uint32_t index(fShmNonRtClientControl.readUInt());
  969. if (plugin->isEnabled())
  970. plugin->uiProgramChange(index);
  971. break;
  972. }
  973. case kPluginBridgeNonRtClientUiMidiProgramChange: {
  974. const uint32_t index(fShmNonRtClientControl.readUInt());
  975. if (plugin->isEnabled())
  976. plugin->uiMidiProgramChange(index);
  977. break;
  978. }
  979. case kPluginBridgeNonRtClientUiNoteOn: {
  980. const uint8_t chnl(fShmNonRtClientControl.readByte());
  981. const uint8_t note(fShmNonRtClientControl.readByte());
  982. const uint8_t velo(fShmNonRtClientControl.readByte());
  983. if (plugin->isEnabled())
  984. plugin->uiNoteOn(chnl, note, velo);
  985. break;
  986. }
  987. case kPluginBridgeNonRtClientUiNoteOff: {
  988. const uint8_t chnl(fShmNonRtClientControl.readByte());
  989. const uint8_t note(fShmNonRtClientControl.readByte());
  990. if (plugin->isEnabled())
  991. plugin->uiNoteOff(chnl, note);
  992. break;
  993. }
  994. case kPluginBridgeNonRtClientQuit:
  995. fClosingDown = true;
  996. signalThreadShouldExit();
  997. callback(true, true, ENGINE_CALLBACK_QUIT, 0, 0, 0, 0, 0.0f, nullptr);
  998. break;
  999. case kPluginBridgeNonRtClientReload:
  1000. fFirstIdle = true;
  1001. break;
  1002. }
  1003. }
  1004. }
  1005. // -------------------------------------------------------------------
  1006. protected:
  1007. void run() override
  1008. {
  1009. #ifdef __SSE2_MATH__
  1010. // Set FTZ and DAZ flags
  1011. _mm_setcsr(_mm_getcsr() | 0x8040);
  1012. #endif
  1013. bool quitReceived = false;
  1014. for (; ! shouldThreadExit();)
  1015. {
  1016. const BridgeRtClientControl::WaitHelper helper(fShmRtClientControl);
  1017. if (! helper.ok)
  1018. continue;
  1019. for (; fShmRtClientControl.isDataAvailableForReading();)
  1020. {
  1021. const PluginBridgeRtClientOpcode opcode(fShmRtClientControl.readOpcode());
  1022. const CarlaPluginPtr plugin = pData->plugins[0].plugin;
  1023. #ifdef DEBUG
  1024. if (opcode != kPluginBridgeRtClientProcess && opcode != kPluginBridgeRtClientMidiEvent) {
  1025. carla_debug("CarlaEngineBridgeRtThread::run() - got opcode: %s", PluginBridgeRtClientOpcode2str(opcode));
  1026. }
  1027. #endif
  1028. switch (opcode)
  1029. {
  1030. case kPluginBridgeRtClientNull:
  1031. break;
  1032. case kPluginBridgeRtClientSetAudioPool: {
  1033. if (fShmAudioPool.data != nullptr)
  1034. {
  1035. jackbridge_shm_unmap(fShmAudioPool.shm, fShmAudioPool.data);
  1036. fShmAudioPool.data = nullptr;
  1037. }
  1038. const uint64_t poolSize(fShmRtClientControl.readULong());
  1039. CARLA_SAFE_ASSERT_BREAK(poolSize > 0);
  1040. fShmAudioPool.data = (float*)jackbridge_shm_map(fShmAudioPool.shm, static_cast<size_t>(poolSize));
  1041. break;
  1042. }
  1043. case kPluginBridgeRtClientSetBufferSize: {
  1044. const uint32_t bufferSize(fShmRtClientControl.readUInt());
  1045. pData->bufferSize = bufferSize;
  1046. bufferSizeChanged(bufferSize);
  1047. break;
  1048. }
  1049. case kPluginBridgeRtClientSetSampleRate: {
  1050. const double sampleRate(fShmRtClientControl.readDouble());
  1051. pData->sampleRate = sampleRate;
  1052. sampleRateChanged(sampleRate);
  1053. break;
  1054. }
  1055. case kPluginBridgeRtClientSetOnline:
  1056. fIsOffline = fShmRtClientControl.readBool();
  1057. offlineModeChanged(fIsOffline);
  1058. break;
  1059. // NOTE this is never used
  1060. case kPluginBridgeRtClientControlEventParameter: {
  1061. const uint32_t time(fShmRtClientControl.readUInt());
  1062. const uint8_t channel(fShmRtClientControl.readByte());
  1063. const uint16_t param(fShmRtClientControl.readUShort());
  1064. const float value(fShmRtClientControl.readFloat());
  1065. if (EngineEvent* const event = getNextFreeInputEvent())
  1066. {
  1067. event->type = kEngineEventTypeControl;
  1068. event->time = time;
  1069. event->channel = channel;
  1070. event->ctrl.type = kEngineControlEventTypeParameter;
  1071. event->ctrl.param = param;
  1072. event->ctrl.midiValue = -1;
  1073. event->ctrl.normalizedValue = value;
  1074. event->ctrl.handled = true;
  1075. }
  1076. break;
  1077. }
  1078. case kPluginBridgeRtClientControlEventMidiBank: {
  1079. const uint32_t time(fShmRtClientControl.readUInt());
  1080. const uint8_t channel(fShmRtClientControl.readByte());
  1081. const uint16_t index(fShmRtClientControl.readUShort());
  1082. if (EngineEvent* const event = getNextFreeInputEvent())
  1083. {
  1084. event->type = kEngineEventTypeControl;
  1085. event->time = time;
  1086. event->channel = channel;
  1087. event->ctrl.type = kEngineControlEventTypeMidiBank;
  1088. event->ctrl.param = index;
  1089. event->ctrl.midiValue = -1;
  1090. event->ctrl.normalizedValue = 0.0f;
  1091. event->ctrl.handled = true;
  1092. }
  1093. break;
  1094. }
  1095. case kPluginBridgeRtClientControlEventMidiProgram: {
  1096. const uint32_t time(fShmRtClientControl.readUInt());
  1097. const uint8_t channel(fShmRtClientControl.readByte());
  1098. const uint16_t index(fShmRtClientControl.readUShort());
  1099. if (EngineEvent* const event = getNextFreeInputEvent())
  1100. {
  1101. event->type = kEngineEventTypeControl;
  1102. event->time = time;
  1103. event->channel = channel;
  1104. event->ctrl.type = kEngineControlEventTypeMidiProgram;
  1105. event->ctrl.param = index;
  1106. event->ctrl.midiValue = -1;
  1107. event->ctrl.normalizedValue = 0.0f;
  1108. event->ctrl.handled = true;
  1109. }
  1110. break;
  1111. }
  1112. case kPluginBridgeRtClientControlEventAllSoundOff: {
  1113. const uint32_t time(fShmRtClientControl.readUInt());
  1114. const uint8_t channel(fShmRtClientControl.readByte());
  1115. if (EngineEvent* const event = getNextFreeInputEvent())
  1116. {
  1117. event->type = kEngineEventTypeControl;
  1118. event->time = time;
  1119. event->channel = channel;
  1120. event->ctrl.type = kEngineControlEventTypeAllSoundOff;
  1121. event->ctrl.param = 0;
  1122. event->ctrl.midiValue = -1;
  1123. event->ctrl.normalizedValue = 0.0f;
  1124. event->ctrl.handled = true;
  1125. }
  1126. } break;
  1127. case kPluginBridgeRtClientControlEventAllNotesOff: {
  1128. const uint32_t time(fShmRtClientControl.readUInt());
  1129. const uint8_t channel(fShmRtClientControl.readByte());
  1130. if (EngineEvent* const event = getNextFreeInputEvent())
  1131. {
  1132. event->type = kEngineEventTypeControl;
  1133. event->time = time;
  1134. event->channel = channel;
  1135. event->ctrl.type = kEngineControlEventTypeAllNotesOff;
  1136. event->ctrl.param = 0;
  1137. event->ctrl.midiValue = -1;
  1138. event->ctrl.normalizedValue = 0.0f;
  1139. event->ctrl.handled = true;
  1140. }
  1141. } break;
  1142. case kPluginBridgeRtClientMidiEvent: {
  1143. const uint32_t time(fShmRtClientControl.readUInt());
  1144. const uint8_t port(fShmRtClientControl.readByte());
  1145. const uint8_t size(fShmRtClientControl.readByte());
  1146. CARLA_SAFE_ASSERT_BREAK(size > 0);
  1147. // FIXME variable-size stack
  1148. uint8_t data[4];
  1149. {
  1150. uint8_t i=0;
  1151. for (; i<size && i<4; ++i)
  1152. data[i] = fShmRtClientControl.readByte();
  1153. for (; i<size; ++i)
  1154. fShmRtClientControl.readByte();
  1155. }
  1156. if (size > 4)
  1157. continue;
  1158. if (EngineEvent* const event = getNextFreeInputEvent())
  1159. {
  1160. event->type = kEngineEventTypeMidi;
  1161. event->time = time;
  1162. event->channel = MIDI_GET_CHANNEL_FROM_DATA(data);
  1163. event->midi.port = port;
  1164. event->midi.size = size;
  1165. if (size > EngineMidiEvent::kDataSize)
  1166. {
  1167. event->midi.dataExt = data;
  1168. std::memset(event->midi.data, 0, sizeof(uint8_t)*EngineMidiEvent::kDataSize);
  1169. }
  1170. else
  1171. {
  1172. event->midi.data[0] = MIDI_GET_STATUS_FROM_DATA(data);
  1173. uint8_t i=1;
  1174. for (; i < size; ++i)
  1175. event->midi.data[i] = data[i];
  1176. for (; i < EngineMidiEvent::kDataSize; ++i)
  1177. event->midi.data[i] = 0;
  1178. event->midi.dataExt = nullptr;
  1179. }
  1180. }
  1181. break;
  1182. }
  1183. case kPluginBridgeRtClientProcess: {
  1184. const uint32_t frames(fShmRtClientControl.readUInt());
  1185. CARLA_SAFE_ASSERT_BREAK(fShmAudioPool.data != nullptr);
  1186. if (plugin.get() != nullptr && plugin->isEnabled() && plugin->tryLock(fIsOffline))
  1187. {
  1188. const BridgeTimeInfo& bridgeTimeInfo(fShmRtClientControl.data->timeInfo);
  1189. const uint32_t audioInCount = plugin->getAudioInCount();
  1190. const uint32_t audioOutCount = plugin->getAudioOutCount();
  1191. const uint32_t cvInCount = plugin->getCVInCount();
  1192. const uint32_t cvOutCount = plugin->getCVOutCount();
  1193. const float* audioIn[64];
  1194. /* */ float* audioOut[64];
  1195. const float* cvIn[32];
  1196. /* */ float* cvOut[32];
  1197. float* fdata = fShmAudioPool.data;
  1198. for (uint32_t i=0; i < audioInCount; ++i, fdata += pData->bufferSize)
  1199. audioIn[i] = fdata;
  1200. for (uint32_t i=0; i < audioOutCount; ++i, fdata += pData->bufferSize)
  1201. audioOut[i] = fdata;
  1202. for (uint32_t i=0; i < cvInCount; ++i, fdata += pData->bufferSize)
  1203. cvIn[i] = fdata;
  1204. for (uint32_t i=0; i < cvOutCount; ++i, fdata += pData->bufferSize)
  1205. cvOut[i] = fdata;
  1206. EngineTimeInfo& timeInfo(pData->timeInfo);
  1207. timeInfo.playing = bridgeTimeInfo.playing;
  1208. timeInfo.frame = bridgeTimeInfo.frame;
  1209. timeInfo.usecs = bridgeTimeInfo.usecs;
  1210. timeInfo.bbt.valid = (bridgeTimeInfo.validFlags & kPluginBridgeTimeInfoValidBBT) != 0;
  1211. if (timeInfo.bbt.valid)
  1212. {
  1213. timeInfo.bbt.bar = bridgeTimeInfo.bar;
  1214. timeInfo.bbt.beat = bridgeTimeInfo.beat;
  1215. timeInfo.bbt.tick = bridgeTimeInfo.tick;
  1216. timeInfo.bbt.beatsPerBar = bridgeTimeInfo.beatsPerBar;
  1217. timeInfo.bbt.beatType = bridgeTimeInfo.beatType;
  1218. timeInfo.bbt.ticksPerBeat = bridgeTimeInfo.ticksPerBeat;
  1219. timeInfo.bbt.beatsPerMinute = bridgeTimeInfo.beatsPerMinute;
  1220. timeInfo.bbt.barStartTick = bridgeTimeInfo.barStartTick;
  1221. }
  1222. plugin->initBuffers();
  1223. plugin->process(audioIn, audioOut, cvIn, cvOut, frames);
  1224. plugin->unlock();
  1225. }
  1226. uint8_t* midiData(fShmRtClientControl.data->midiOut);
  1227. carla_zeroBytes(midiData, kBridgeBaseMidiOutHeaderSize);
  1228. std::size_t curMidiDataPos = 0;
  1229. if (pData->events.in[0].type != kEngineEventTypeNull)
  1230. carla_zeroStructs(pData->events.in, kMaxEngineEventInternalCount);
  1231. if (pData->events.out[0].type != kEngineEventTypeNull)
  1232. {
  1233. for (ushort i=0; i < kMaxEngineEventInternalCount; ++i)
  1234. {
  1235. const EngineEvent& event(pData->events.out[i]);
  1236. if (event.type == kEngineEventTypeNull)
  1237. break;
  1238. if (event.type == kEngineEventTypeControl)
  1239. {
  1240. uint8_t data[3];
  1241. const uint8_t size = event.ctrl.convertToMidiData(event.channel, data);
  1242. CARLA_SAFE_ASSERT_CONTINUE(size > 0 && size <= 3);
  1243. if (curMidiDataPos + kBridgeBaseMidiOutHeaderSize + size >= kBridgeRtClientDataMidiOutSize)
  1244. break;
  1245. // set time
  1246. *(uint32_t*)midiData = event.time;
  1247. midiData = midiData + 4;
  1248. curMidiDataPos += 4;
  1249. // set port
  1250. *midiData++ = 0;
  1251. ++curMidiDataPos;
  1252. // set size
  1253. *midiData++ = size;
  1254. ++curMidiDataPos;
  1255. // set data
  1256. for (uint8_t j=0; j<size; ++j)
  1257. *midiData++ = data[j];
  1258. curMidiDataPos += size;
  1259. }
  1260. else if (event.type == kEngineEventTypeMidi)
  1261. {
  1262. const EngineMidiEvent& _midiEvent(event.midi);
  1263. if (curMidiDataPos + kBridgeBaseMidiOutHeaderSize + _midiEvent.size >= kBridgeRtClientDataMidiOutSize)
  1264. break;
  1265. const uint8_t* const _midiData(_midiEvent.dataExt != nullptr ? _midiEvent.dataExt : _midiEvent.data);
  1266. // set time
  1267. *(uint32_t*)midiData = event.time;
  1268. midiData += 4;
  1269. curMidiDataPos += 4;
  1270. // set port
  1271. *midiData++ = _midiEvent.port;
  1272. ++curMidiDataPos;
  1273. // set size
  1274. *midiData++ = _midiEvent.size;
  1275. ++curMidiDataPos;
  1276. // set data
  1277. *midiData++ = uint8_t(_midiData[0] | (event.channel & MIDI_CHANNEL_BIT));
  1278. for (uint8_t j=1; j<_midiEvent.size; ++j)
  1279. *midiData++ = _midiData[j];
  1280. curMidiDataPos += _midiEvent.size;
  1281. }
  1282. }
  1283. if (curMidiDataPos != 0 &&
  1284. curMidiDataPos + kBridgeBaseMidiOutHeaderSize < kBridgeRtClientDataMidiOutSize)
  1285. carla_zeroBytes(midiData, kBridgeBaseMidiOutHeaderSize);
  1286. carla_zeroStructs(pData->events.out, kMaxEngineEventInternalCount);
  1287. }
  1288. } break;
  1289. case kPluginBridgeRtClientQuit: {
  1290. quitReceived = true;
  1291. fClosingDown = true;
  1292. signalThreadShouldExit();
  1293. } break;
  1294. }
  1295. }
  1296. }
  1297. callback(true, true, ENGINE_CALLBACK_ENGINE_STOPPED, 0, 0, 0, 0, 0.0f, nullptr);
  1298. if (! quitReceived)
  1299. {
  1300. const char* const message("Plugin bridge error, process thread has stopped");
  1301. const std::size_t messageSize(std::strlen(message));
  1302. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  1303. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerError);
  1304. fShmNonRtServerControl.writeUInt(messageSize);
  1305. fShmNonRtServerControl.writeCustomData(message, messageSize);
  1306. fShmNonRtServerControl.commitWrite();
  1307. }
  1308. }
  1309. // called from process thread above
  1310. EngineEvent* getNextFreeInputEvent() const noexcept
  1311. {
  1312. for (ushort i=0; i < kMaxEngineEventInternalCount; ++i)
  1313. {
  1314. EngineEvent* const event(&pData->events.in[i]);
  1315. if (event->type == kEngineEventTypeNull)
  1316. return event;
  1317. }
  1318. return nullptr;
  1319. }
  1320. void latencyChanged(const uint32_t samples) noexcept override
  1321. {
  1322. const CarlaMutexLocker _cml(fShmNonRtServerControl.mutex);
  1323. fShmNonRtServerControl.writeOpcode(kPluginBridgeNonRtServerSetLatency);
  1324. fShmNonRtServerControl.writeUInt(samples);
  1325. fShmNonRtServerControl.commitWrite();
  1326. }
  1327. // -------------------------------------------------------------------
  1328. private:
  1329. BridgeAudioPool fShmAudioPool;
  1330. BridgeRtClientControl fShmRtClientControl;
  1331. BridgeNonRtClientControl fShmNonRtClientControl;
  1332. BridgeNonRtServerControl fShmNonRtServerControl;
  1333. CarlaString fBaseNameAudioPool;
  1334. CarlaString fBaseNameRtClientControl;
  1335. CarlaString fBaseNameNonRtClientControl;
  1336. CarlaString fBaseNameNonRtServerControl;
  1337. bool fClosingDown;
  1338. bool fIsOffline;
  1339. bool fFirstIdle;
  1340. uint32_t fBridgeVersion;
  1341. uint32_t fLastPingTime;
  1342. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineBridge)
  1343. };
  1344. // -----------------------------------------------------------------------
  1345. namespace EngineInit {
  1346. CarlaEngine* newBridge(const char* const audioPoolBaseName,
  1347. const char* const rtClientBaseName,
  1348. const char* const nonRtClientBaseName,
  1349. const char* const nonRtServerBaseName)
  1350. {
  1351. return new CarlaEngineBridge(audioPoolBaseName, rtClientBaseName, nonRtClientBaseName, nonRtServerBaseName);
  1352. }
  1353. }
  1354. // -----------------------------------------------------------------------
  1355. CARLA_BACKEND_END_NAMESPACE
  1356. // -----------------------------------------------------------------------
  1357. #include "CarlaBridgeUtils.cpp"
  1358. // -----------------------------------------------------------------------