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.

1540 lines
61KB

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