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.

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