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.

1679 lines
67KB

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