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.

2256 lines
75KB

  1. /*
  2. * Carla Bridge Plugin
  3. * Copyright (C) 2011-2014 Filipe Coelho <falktx@falktx.com>
  4. *
  5. * This program is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU General Public License as
  7. * published by the Free Software Foundation; either version 2 of
  8. * the License, or any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * For a full copy of the GNU General Public License see the doc/GPL.txt file.
  16. */
  17. #include "CarlaPluginInternal.hpp"
  18. #include "CarlaEngine.hpp"
  19. #ifndef BUILD_BRIDGE
  20. #include "CarlaBackendUtils.hpp"
  21. #include "CarlaBase64Utils.hpp"
  22. #include "CarlaBridgeUtils.hpp"
  23. #include "CarlaMathUtils.hpp"
  24. #include "CarlaShmUtils.hpp"
  25. #include "jackbridge/JackBridge.hpp"
  26. #include <cerrno>
  27. #include <cmath>
  28. #include <ctime>
  29. #define CARLA_BRIDGE_CHECK_OSC_TYPES(/* argc, types, */ argcToCompare, typesToCompare) \
  30. /* check argument count */ \
  31. if (argc != argcToCompare) \
  32. { \
  33. carla_stderr("BridgePlugin::%s() - argument count mismatch: %i != %i", __FUNCTION__, argc, argcToCompare); \
  34. return 1; \
  35. } \
  36. if (argc > 0) \
  37. { \
  38. /* check for nullness */ \
  39. if (! (types && typesToCompare)) \
  40. { \
  41. carla_stderr("BridgePlugin::%s() - argument types are null", __FUNCTION__); \
  42. return 1; \
  43. } \
  44. /* check argument types */ \
  45. if (std::strcmp(types, typesToCompare) != 0) \
  46. { \
  47. carla_stderr("BridgePlugin::%s() - argument types mismatch: '%s' != '%s'", __FUNCTION__, types, typesToCompare); \
  48. return 1; \
  49. } \
  50. }
  51. // -------------------------------------------------------------------------------------------------------------------
  52. using juce::File;
  53. using juce::String;
  54. using juce::StringArray;
  55. CARLA_BACKEND_START_NAMESPACE
  56. // -------------------------------------------------------------------------------------------------------------------
  57. // call carla_shm_create with for a XXXXXX temp filename
  58. static shm_t shm_mkstemp(char* const fileBase)
  59. {
  60. CARLA_SAFE_ASSERT_RETURN(fileBase != nullptr, gNullCarlaShm);
  61. const size_t fileBaseLen(std::strlen(fileBase));
  62. CARLA_SAFE_ASSERT_RETURN(fileBaseLen > 6, gNullCarlaShm);
  63. CARLA_SAFE_ASSERT_RETURN(std::strcmp(fileBase + fileBaseLen - 6, "XXXXXX") == 0, gNullCarlaShm);
  64. static const char charSet[] = "abcdefghijklmnopqrstuvwxyz"
  65. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  66. "0123456789";
  67. static const int charSetLen = static_cast<int>(std::strlen(charSet) - 1); // -1 to avoid trailing '\0'
  68. // try until getting a valid shm or an error occurs
  69. for (;;)
  70. {
  71. for (size_t c = fileBaseLen - 6; c < fileBaseLen; ++c)
  72. fileBase[c] = charSet[std::rand() % charSetLen];
  73. const shm_t shm = carla_shm_create(fileBase);
  74. if (carla_is_shm_valid(shm))
  75. return shm;
  76. if (errno != EEXIST)
  77. return gNullCarlaShm;
  78. }
  79. }
  80. // -------------------------------------------------------------------------------------------------------------------
  81. struct BridgeAudioPool {
  82. CarlaString filename;
  83. float* data;
  84. size_t size;
  85. shm_t shm;
  86. BridgeAudioPool() noexcept
  87. : filename(),
  88. data(nullptr),
  89. size(0)
  90. #ifdef CARLA_PROPER_CPP11_SUPPORT
  91. , shm(shm_t_INIT) {}
  92. #else
  93. {
  94. carla_shm_init(shm);
  95. }
  96. #endif
  97. ~BridgeAudioPool() noexcept
  98. {
  99. // should be cleared by now
  100. CARLA_SAFE_ASSERT(data == nullptr);
  101. clear();
  102. }
  103. void clear() noexcept
  104. {
  105. filename.clear();
  106. if (! carla_is_shm_valid(shm))
  107. return;
  108. if (data != nullptr)
  109. {
  110. carla_shm_unmap(shm, data, size);
  111. data = nullptr;
  112. }
  113. size = 0;
  114. carla_shm_close(shm);
  115. }
  116. void resize(const uint32_t bufferSize, const uint32_t portCount) noexcept
  117. {
  118. if (data != nullptr)
  119. carla_shm_unmap(shm, data, size);
  120. size = portCount*bufferSize*sizeof(float);
  121. if (size == 0)
  122. size = sizeof(float);
  123. data = (float*)carla_shm_map(shm, size);
  124. }
  125. CARLA_DECLARE_NON_COPY_STRUCT(BridgeAudioPool)
  126. };
  127. // -------------------------------------------------------------------------------------------------------------------
  128. struct BridgeRtControl : public CarlaRingBuffer<StackBuffer> {
  129. CarlaString filename;
  130. BridgeRtData* data;
  131. shm_t shm;
  132. BridgeRtControl()
  133. : filename(),
  134. data(nullptr)
  135. #ifdef CARLA_PROPER_CPP11_SUPPORT
  136. , shm(shm_t_INIT) {}
  137. #else
  138. {
  139. carla_shm_init(shm);
  140. }
  141. #endif
  142. ~BridgeRtControl() noexcept override
  143. {
  144. // should be cleared by now
  145. CARLA_SAFE_ASSERT(data == nullptr);
  146. clear();
  147. }
  148. void clear() noexcept
  149. {
  150. filename.clear();
  151. if (! carla_is_shm_valid(shm))
  152. return;
  153. if (data != nullptr)
  154. {
  155. carla_shm_unmap(shm, data, sizeof(BridgeRtData));
  156. data = nullptr;
  157. }
  158. carla_shm_close(shm);
  159. }
  160. bool mapData() noexcept
  161. {
  162. CARLA_SAFE_ASSERT(data == nullptr);
  163. if (carla_shm_map<BridgeRtData>(shm, data))
  164. {
  165. setRingBuffer(&data->ringBuffer, true);
  166. return true;
  167. }
  168. return false;
  169. }
  170. void unmapData() noexcept
  171. {
  172. CARLA_SAFE_ASSERT_RETURN(data != nullptr,);
  173. carla_shm_unmap(shm, data, sizeof(BridgeRtData));
  174. data = nullptr;
  175. setRingBuffer(nullptr, false);
  176. }
  177. bool waitForServer(const int secs) noexcept
  178. {
  179. CARLA_SAFE_ASSERT_RETURN(data != nullptr, false);
  180. jackbridge_sem_post(&data->sem.server);
  181. return jackbridge_sem_timedwait(&data->sem.client, secs);
  182. }
  183. void writeOpcode(const PluginBridgeRtOpcode opcode) noexcept
  184. {
  185. writeInt(static_cast<int32_t>(opcode));
  186. }
  187. CARLA_DECLARE_NON_COPY_STRUCT(BridgeRtControl)
  188. };
  189. // -------------------------------------------------------------------------------------------------------------------
  190. struct BridgeNonRtControl : public CarlaRingBuffer<BigStackBuffer> {
  191. CarlaMutex mutex;
  192. CarlaString filename;
  193. BridgeNonRtData* data;
  194. shm_t shm;
  195. BridgeNonRtControl() noexcept
  196. : mutex(),
  197. filename(),
  198. data(nullptr)
  199. #ifdef CARLA_PROPER_CPP11_SUPPORT
  200. , shm(shm_t_INIT) {}
  201. #else
  202. {
  203. carla_shm_init(shm);
  204. }
  205. #endif
  206. ~BridgeNonRtControl() noexcept override
  207. {
  208. // should be cleared by now
  209. CARLA_SAFE_ASSERT(data == nullptr);
  210. clear();
  211. }
  212. void clear() noexcept
  213. {
  214. filename.clear();
  215. if (! carla_is_shm_valid(shm))
  216. return;
  217. if (data != nullptr)
  218. {
  219. carla_shm_unmap(shm, data, sizeof(BridgeNonRtData));
  220. data = nullptr;
  221. }
  222. carla_shm_close(shm);
  223. }
  224. bool mapData() noexcept
  225. {
  226. CARLA_SAFE_ASSERT(data == nullptr);
  227. if (carla_shm_map<BridgeNonRtData>(shm, data))
  228. {
  229. setRingBuffer(&data->ringBuffer, true);
  230. return true;
  231. }
  232. return false;
  233. }
  234. void unmapData() noexcept
  235. {
  236. CARLA_SAFE_ASSERT_RETURN(data != nullptr,);
  237. carla_shm_unmap(shm, data, sizeof(BridgeNonRtData));
  238. data = nullptr;
  239. setRingBuffer(nullptr, false);
  240. }
  241. void writeOpcode(const PluginBridgeNonRtOpcode opcode) noexcept
  242. {
  243. writeInt(static_cast<int32_t>(opcode));
  244. }
  245. CARLA_DECLARE_NON_COPY_STRUCT(BridgeNonRtControl)
  246. };
  247. // -------------------------------------------------------------------------------------------------------------------
  248. struct BridgeParamInfo {
  249. float value;
  250. CarlaString name;
  251. CarlaString unit;
  252. BridgeParamInfo() noexcept
  253. : value(0.0f),
  254. name(),
  255. unit() {}
  256. CARLA_DECLARE_NON_COPY_STRUCT(BridgeParamInfo)
  257. };
  258. // -------------------------------------------------------------------------------------------------------------------
  259. class BridgePlugin : public CarlaPlugin
  260. {
  261. public:
  262. BridgePlugin(CarlaEngine* const engine, const uint id, const BinaryType btype, const PluginType ptype)
  263. : CarlaPlugin(engine, id),
  264. fBinaryType(btype),
  265. fPluginType(ptype),
  266. fInitiated(false),
  267. fInitError(false),
  268. fSaved(false),
  269. fNeedsSemDestroy(false),
  270. fTimedOut(false),
  271. fLastPongCounter(-1),
  272. fBridgeBinary(),
  273. fShmAudioPool(),
  274. fShmRtControl(),
  275. fShmNonRtControl(),
  276. fInfo(),
  277. fParams(nullptr),
  278. leakDetector_BridgePlugin()
  279. {
  280. carla_debug("BridgePlugin::BridgePlugin(%p, %i, %s, %s)", engine, id, BinaryType2Str(btype), PluginType2Str(ptype));
  281. pData->osc.thread.setMode(CarlaPluginThread::PLUGIN_THREAD_BRIDGE);
  282. pData->hints |= PLUGIN_IS_BRIDGE;
  283. }
  284. ~BridgePlugin() override
  285. {
  286. carla_debug("BridgePlugin::~BridgePlugin()");
  287. // close UI
  288. if (pData->hints & PLUGIN_HAS_CUSTOM_UI)
  289. pData->transientTryCounter = 0;
  290. pData->singleMutex.lock();
  291. pData->masterMutex.lock();
  292. if (pData->client != nullptr && pData->client->isActive())
  293. pData->client->deactivate();
  294. if (pData->active)
  295. {
  296. deactivate();
  297. pData->active = false;
  298. }
  299. if (pData->osc.thread.isThreadRunning())
  300. {
  301. fShmNonRtControl.writeOpcode(kPluginBridgeNonRtQuit);
  302. fShmNonRtControl.commitWrite();
  303. if (! fTimedOut)
  304. fShmRtControl.waitForServer(3);
  305. }
  306. pData->osc.data.clear();
  307. pData->osc.thread.stopThread(3000);
  308. if (fNeedsSemDestroy)
  309. {
  310. jackbridge_sem_destroy(&fShmRtControl.data->sem.server);
  311. jackbridge_sem_destroy(&fShmRtControl.data->sem.client);
  312. }
  313. fShmAudioPool.clear();
  314. fShmRtControl.clear();
  315. fShmNonRtControl.clear();
  316. clearBuffers();
  317. fInfo.chunk.clear();
  318. }
  319. // -------------------------------------------------------------------
  320. // Information (base)
  321. BinaryType getBinaryType() const noexcept
  322. {
  323. return fBinaryType;
  324. }
  325. PluginType getType() const noexcept override
  326. {
  327. return fPluginType;
  328. }
  329. PluginCategory getCategory() const noexcept override
  330. {
  331. return fInfo.category;
  332. }
  333. int64_t getUniqueId() const noexcept override
  334. {
  335. return fInfo.uniqueId;
  336. }
  337. // -------------------------------------------------------------------
  338. // Information (count)
  339. uint32_t getMidiInCount() const noexcept override
  340. {
  341. return fInfo.mIns;
  342. }
  343. uint32_t getMidiOutCount() const noexcept override
  344. {
  345. return fInfo.mOuts;
  346. }
  347. // -------------------------------------------------------------------
  348. // Information (current data)
  349. std::size_t getChunkData(void** const dataPtr) noexcept override
  350. {
  351. CARLA_SAFE_ASSERT_RETURN(pData->options & PLUGIN_OPTION_USE_CHUNKS, 0);
  352. CARLA_SAFE_ASSERT_RETURN(dataPtr != nullptr, 0);
  353. CARLA_SAFE_ASSERT_RETURN(fInfo.chunk.size() > 0, 0);
  354. *dataPtr = fInfo.chunk.data();
  355. return fInfo.chunk.size();
  356. }
  357. // -------------------------------------------------------------------
  358. // Information (per-plugin data)
  359. uint getOptionsAvailable() const noexcept override
  360. {
  361. return fInfo.optionsAvailable;
  362. }
  363. float getParameterValue(const uint32_t parameterId) const noexcept override
  364. {
  365. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, 0.0f);
  366. return fParams[parameterId].value;
  367. }
  368. void getLabel(char* const strBuf) const noexcept override
  369. {
  370. std::strncpy(strBuf, fInfo.label, STR_MAX);
  371. }
  372. void getMaker(char* const strBuf) const noexcept override
  373. {
  374. std::strncpy(strBuf, fInfo.maker, STR_MAX);
  375. }
  376. void getCopyright(char* const strBuf) const noexcept override
  377. {
  378. std::strncpy(strBuf, fInfo.copyright, STR_MAX);
  379. }
  380. void getRealName(char* const strBuf) const noexcept override
  381. {
  382. std::strncpy(strBuf, fInfo.name, STR_MAX);
  383. }
  384. void getParameterName(const uint32_t parameterId, char* const strBuf) const noexcept override
  385. {
  386. CARLA_ASSERT(parameterId < pData->param.count);
  387. std::strncpy(strBuf, fParams[parameterId].name.buffer(), STR_MAX);
  388. }
  389. void getParameterUnit(const uint32_t parameterId, char* const strBuf) const noexcept override
  390. {
  391. CARLA_ASSERT(parameterId < pData->param.count);
  392. std::strncpy(strBuf, fParams[parameterId].unit.buffer(), STR_MAX);
  393. }
  394. // -------------------------------------------------------------------
  395. // Set data (state)
  396. void prepareForSave() override
  397. {
  398. fSaved = false;
  399. {
  400. const CarlaMutexLocker _cml(fShmNonRtControl.mutex);
  401. fShmNonRtControl.writeOpcode(kPluginBridgeNonRtPrepareForSave);
  402. fShmNonRtControl.commitWrite();
  403. }
  404. carla_stdout("BridgePlugin::prepareForSave() - sent, now waiting...");
  405. for (int i=0; i < 200; ++i)
  406. {
  407. if (fSaved)
  408. break;
  409. carla_msleep(30);
  410. pData->engine->callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  411. pData->engine->idle();
  412. }
  413. if (! fSaved)
  414. carla_stderr("BridgePlugin::prepareForSave() - Timeout while requesting save state");
  415. else
  416. carla_stdout("BridgePlugin::prepareForSave() - success!");
  417. }
  418. // -------------------------------------------------------------------
  419. // Set data (internal stuff)
  420. void setOption(const uint option, const bool yesNo, const bool sendCallback) override
  421. {
  422. {
  423. const CarlaMutexLocker _cml(fShmNonRtControl.mutex);
  424. fShmNonRtControl.writeOpcode(kPluginBridgeNonRtSetOption);
  425. fShmNonRtControl.writeUInt(option);
  426. fShmNonRtControl.writeBool(yesNo);
  427. fShmNonRtControl.commitWrite();
  428. }
  429. CarlaPlugin::setOption(option, yesNo, sendCallback);
  430. }
  431. void setCtrlChannel(const int8_t channel, const bool sendOsc, const bool sendCallback) noexcept override
  432. {
  433. CARLA_SAFE_ASSERT_RETURN(sendOsc || sendCallback,); // never call this from RT
  434. {
  435. const CarlaMutexLocker _cml(fShmNonRtControl.mutex);
  436. fShmNonRtControl.writeOpcode(kPluginBridgeNonRtSetCtrlChannel);
  437. fShmNonRtControl.writeShort(channel);
  438. fShmNonRtControl.commitWrite();
  439. }
  440. CarlaPlugin::setCtrlChannel(channel, sendOsc, sendCallback);
  441. }
  442. // -------------------------------------------------------------------
  443. // Set data (plugin-specific stuff)
  444. void setParameterValue(const uint32_t parameterId, const float value, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  445. {
  446. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  447. const float fixedValue(pData->param.getFixedValue(parameterId, value));
  448. fParams[parameterId].value = fixedValue;
  449. {
  450. const CarlaMutexLocker _cml(fShmNonRtControl.mutex);
  451. fShmNonRtControl.writeOpcode(kPluginBridgeNonRtSetParameterValue);
  452. fShmNonRtControl.writeUInt(parameterId);
  453. fShmNonRtControl.writeFloat(value);
  454. fShmNonRtControl.commitWrite();
  455. }
  456. CarlaPlugin::setParameterValue(parameterId, fixedValue, sendGui, sendOsc, sendCallback);
  457. }
  458. void setParameterMidiChannel(const uint32_t parameterId, const uint8_t channel, const bool sendOsc, const bool sendCallback) noexcept override
  459. {
  460. CARLA_SAFE_ASSERT_RETURN(sendOsc || sendCallback,); // never call this from RT
  461. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  462. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  463. {
  464. const CarlaMutexLocker _cml(fShmNonRtControl.mutex);
  465. fShmNonRtControl.writeOpcode(kPluginBridgeNonRtSetParameterMidiChannel);
  466. fShmNonRtControl.writeUInt(parameterId);
  467. fShmNonRtControl.writeByte(channel);
  468. fShmNonRtControl.commitWrite();
  469. }
  470. CarlaPlugin::setParameterMidiChannel(parameterId, channel, sendOsc, sendCallback);
  471. }
  472. void setParameterMidiCC(const uint32_t parameterId, const int16_t cc, const bool sendOsc, const bool sendCallback) noexcept override
  473. {
  474. CARLA_SAFE_ASSERT_RETURN(sendOsc || sendCallback,); // never call this from RT
  475. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  476. CARLA_SAFE_ASSERT_RETURN(cc >= -1 && cc <= 0x5F,);
  477. {
  478. const CarlaMutexLocker _cml(fShmNonRtControl.mutex);
  479. fShmNonRtControl.writeOpcode(kPluginBridgeNonRtSetParameterMidiCC);
  480. fShmNonRtControl.writeUInt(parameterId);
  481. fShmNonRtControl.writeShort(cc);
  482. fShmNonRtControl.commitWrite();
  483. }
  484. CarlaPlugin::setParameterMidiCC(parameterId, cc, sendOsc, sendCallback);
  485. }
  486. void setProgram(const int32_t index, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  487. {
  488. CARLA_SAFE_ASSERT_RETURN(index >= -1 && index < static_cast<int32_t>(pData->prog.count),);
  489. {
  490. const CarlaMutexLocker _cml(fShmNonRtControl.mutex);
  491. fShmNonRtControl.writeOpcode(kPluginBridgeNonRtSetProgram);
  492. fShmNonRtControl.writeInt(index);
  493. fShmNonRtControl.commitWrite();
  494. }
  495. CarlaPlugin::setProgram(index, sendGui, sendOsc, sendCallback);
  496. }
  497. void setMidiProgram(const int32_t index, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  498. {
  499. CARLA_SAFE_ASSERT_RETURN(index >= -1 && index < static_cast<int32_t>(pData->midiprog.count),);
  500. {
  501. const CarlaMutexLocker _cml(fShmNonRtControl.mutex);
  502. fShmNonRtControl.writeOpcode(kPluginBridgeNonRtSetMidiProgram);
  503. fShmNonRtControl.writeInt(index);
  504. fShmNonRtControl.commitWrite();
  505. }
  506. CarlaPlugin::setMidiProgram(index, sendGui, sendOsc, sendCallback);
  507. }
  508. #if 0
  509. void setCustomData(const char* const type, const char* const key, const char* const value, const bool sendGui) override
  510. {
  511. CARLA_ASSERT(type);
  512. CARLA_ASSERT(key);
  513. CARLA_ASSERT(value);
  514. if (sendGui)
  515. {
  516. // TODO - if type is chunk|binary, store it in a file and send path instead
  517. QString cData;
  518. cData = type;
  519. cData += "·";
  520. cData += key;
  521. cData += "·";
  522. cData += value;
  523. osc_send_configure(&osc.data, CARLA_BRIDGE_MSG_SET_CUSTOM, cData.toUtf8().constData());
  524. }
  525. CarlaPlugin::setCustomData(type, key, value, sendGui);
  526. }
  527. #endif
  528. void setChunkData(const void* const data, const std::size_t dataSize) override
  529. {
  530. CARLA_SAFE_ASSERT_RETURN(pData->options & PLUGIN_OPTION_USE_CHUNKS,);
  531. CARLA_SAFE_ASSERT_RETURN(data != nullptr,);
  532. CARLA_SAFE_ASSERT_RETURN(dataSize > 0,);
  533. CarlaString dataBase64 = CarlaString::asBase64(data, dataSize);
  534. CARLA_SAFE_ASSERT_RETURN(dataBase64.length() > 0,);
  535. String filePath(File::getSpecialLocation(File::tempDirectory).getFullPathName());
  536. filePath += CARLA_OS_SEP_STR;
  537. filePath += ".CarlaChunk_";
  538. filePath += fShmAudioPool.filename.buffer() + 18;
  539. if (File(filePath).replaceWithText(dataBase64.buffer()))
  540. {
  541. const uint32_t ulength(static_cast<uint32_t>(filePath.length()));
  542. const CarlaMutexLocker _cml(fShmNonRtControl.mutex);
  543. fShmNonRtControl.writeOpcode(kPluginBridgeNonRtSetChunkDataFile);
  544. fShmNonRtControl.writeUInt(ulength);
  545. fShmNonRtControl.writeCustomData(filePath.toRawUTF8(), ulength);
  546. fShmNonRtControl.commitWrite();
  547. }
  548. }
  549. // -------------------------------------------------------------------
  550. // Set ui stuff
  551. void showCustomUI(const bool yesNo) override
  552. {
  553. {
  554. const CarlaMutexLocker _cml(fShmNonRtControl.mutex);
  555. fShmNonRtControl.writeOpcode(yesNo ? kPluginBridgeNonRtShowUI : kPluginBridgeNonRtHideUI);
  556. fShmNonRtControl.commitWrite();
  557. }
  558. if (yesNo)
  559. {
  560. pData->tryTransient();
  561. }
  562. else
  563. {
  564. pData->transientTryCounter = 0;
  565. }
  566. }
  567. void idle() override
  568. {
  569. if (pData->osc.thread.isThreadRunning())
  570. {
  571. if (fTimedOut && pData->active)
  572. setActive(false, true, true);
  573. const CarlaMutexLocker _cml(fShmNonRtControl.mutex);
  574. fShmNonRtControl.writeOpcode(kPluginBridgeNonRtPing);
  575. fShmNonRtControl.commitWrite();
  576. }
  577. else
  578. carla_stderr2("TESTING: Bridge has closed!");
  579. CarlaPlugin::idle();
  580. }
  581. // -------------------------------------------------------------------
  582. // Plugin state
  583. void reload() override
  584. {
  585. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  586. carla_debug("BridgePlugin::reload() - start");
  587. const EngineProcessMode processMode(pData->engine->getProccessMode());
  588. // Safely disable plugin for reload
  589. const ScopedDisabler sd(this);
  590. bool needsCtrlIn, needsCtrlOut;
  591. needsCtrlIn = needsCtrlOut = false;
  592. if (fInfo.aIns > 0)
  593. {
  594. pData->audioIn.createNew(fInfo.aIns);
  595. }
  596. if (fInfo.aOuts > 0)
  597. {
  598. pData->audioOut.createNew(fInfo.aOuts);
  599. needsCtrlIn = true;
  600. }
  601. if (fInfo.mIns > 0)
  602. needsCtrlIn = true;
  603. if (fInfo.mOuts > 0)
  604. needsCtrlOut = true;
  605. const uint portNameSize(pData->engine->getMaxPortNameSize());
  606. CarlaString portName;
  607. // Audio Ins
  608. for (uint32_t j=0; j < fInfo.aIns; ++j)
  609. {
  610. portName.clear();
  611. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  612. {
  613. portName = pData->name;
  614. portName += ":";
  615. }
  616. if (fInfo.aIns > 1)
  617. {
  618. portName += "input_";
  619. portName += CarlaString(j+1);
  620. }
  621. else
  622. portName += "input";
  623. portName.truncate(portNameSize);
  624. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true);
  625. pData->audioIn.ports[j].rindex = j;
  626. }
  627. // Audio Outs
  628. for (uint32_t j=0; j < fInfo.aOuts; ++j)
  629. {
  630. portName.clear();
  631. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  632. {
  633. portName = pData->name;
  634. portName += ":";
  635. }
  636. if (fInfo.aOuts > 1)
  637. {
  638. portName += "output_";
  639. portName += CarlaString(j+1);
  640. }
  641. else
  642. portName += "output";
  643. portName.truncate(portNameSize);
  644. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false);
  645. pData->audioOut.ports[j].rindex = j;
  646. }
  647. if (needsCtrlIn)
  648. {
  649. portName.clear();
  650. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  651. {
  652. portName = pData->name;
  653. portName += ":";
  654. }
  655. portName += "event-in";
  656. portName.truncate(portNameSize);
  657. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true);
  658. }
  659. if (needsCtrlOut)
  660. {
  661. portName.clear();
  662. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  663. {
  664. portName = pData->name;
  665. portName += ":";
  666. }
  667. portName += "event-out";
  668. portName.truncate(portNameSize);
  669. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false);
  670. }
  671. // extra plugin hints
  672. pData->extraHints = 0x0;
  673. if (fInfo.mIns > 0)
  674. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  675. if (fInfo.mOuts > 0)
  676. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_OUT;
  677. if (fInfo.aIns <= 2 && fInfo.aOuts <= 2 && (fInfo.aIns == fInfo.aOuts || fInfo.aIns == 0 || fInfo.aOuts == 0))
  678. pData->extraHints |= PLUGIN_EXTRA_HINT_CAN_RUN_RACK;
  679. bufferSizeChanged(pData->engine->getBufferSize());
  680. reloadPrograms(true);
  681. carla_debug("BridgePlugin::reload() - end");
  682. }
  683. // -------------------------------------------------------------------
  684. // Plugin processing
  685. void activate() noexcept override
  686. {
  687. {
  688. const CarlaMutexLocker _cml(fShmNonRtControl.mutex);
  689. fShmNonRtControl.writeOpcode(kPluginBridgeNonRtActivate);
  690. fShmNonRtControl.commitWrite();
  691. }
  692. bool timedOut = true;
  693. try {
  694. timedOut = waitForServer(1);
  695. } catch(...) {}
  696. if (! timedOut)
  697. fTimedOut = false;
  698. }
  699. void deactivate() noexcept override
  700. {
  701. {
  702. const CarlaMutexLocker _cml(fShmNonRtControl.mutex);
  703. fShmNonRtControl.writeOpcode(kPluginBridgeNonRtDeactivate);
  704. fShmNonRtControl.commitWrite();
  705. }
  706. bool timedOut = true;
  707. try {
  708. timedOut = waitForServer(1);
  709. } catch(...) {}
  710. if (! timedOut)
  711. fTimedOut = false;
  712. }
  713. void process(float** const inBuffer, float** const outBuffer, const uint32_t frames) override
  714. {
  715. // --------------------------------------------------------------------------------------------------------
  716. // Check if active
  717. if (fTimedOut || ! pData->active)
  718. {
  719. // disable any output sound
  720. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  721. FloatVectorOperations::clear(outBuffer[i], static_cast<int>(frames));
  722. return;
  723. }
  724. // --------------------------------------------------------------------------------------------------------
  725. // Check if needs reset
  726. if (pData->needsReset)
  727. {
  728. // TODO
  729. pData->needsReset = false;
  730. }
  731. // --------------------------------------------------------------------------------------------------------
  732. // Event Input
  733. if (pData->event.portIn != nullptr)
  734. {
  735. // ----------------------------------------------------------------------------------------------------
  736. // MIDI Input (External)
  737. if (pData->extNotes.mutex.tryLock())
  738. {
  739. for (RtLinkedList<ExternalMidiNote>::Itenerator it = pData->extNotes.data.begin(); it.valid(); it.next())
  740. {
  741. const ExternalMidiNote& note(it.getValue());
  742. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  743. uint8_t data1, data2, data3;
  744. data1 = static_cast<uint8_t>((note.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT));
  745. data2 = note.note;
  746. data3 = note.velo;
  747. fShmRtControl.writeOpcode(kPluginBridgeRtMidiEvent);
  748. fShmRtControl.writeUInt(0); // time
  749. fShmRtControl.writeByte(0); // port
  750. fShmRtControl.writeByte(3); // size
  751. fShmRtControl.writeByte(data1);
  752. fShmRtControl.writeByte(data2);
  753. fShmRtControl.writeByte(data3);
  754. fShmRtControl.commitWrite();
  755. }
  756. pData->extNotes.data.clear();
  757. pData->extNotes.mutex.unlock();
  758. } // End of MIDI Input (External)
  759. // ----------------------------------------------------------------------------------------------------
  760. // Event Input (System)
  761. bool allNotesOffSent = false;
  762. for (uint32_t i=0, numEvents = pData->event.portIn->getEventCount(); i < numEvents; ++i)
  763. {
  764. const EngineEvent& event(pData->event.portIn->getEvent(i));
  765. // Control change
  766. switch (event.type)
  767. {
  768. case kEngineEventTypeNull:
  769. break;
  770. case kEngineEventTypeControl: {
  771. const EngineControlEvent& ctrlEvent = event.ctrl;
  772. switch (ctrlEvent.type)
  773. {
  774. case kEngineControlEventTypeNull:
  775. break;
  776. case kEngineControlEventTypeParameter:
  777. // Control backend stuff
  778. if (event.channel == pData->ctrlChannel)
  779. {
  780. float value;
  781. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  782. {
  783. value = ctrlEvent.value;
  784. setDryWet(value, false, false);
  785. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  786. break;
  787. }
  788. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  789. {
  790. value = ctrlEvent.value*127.0f/100.0f;
  791. setVolume(value, false, false);
  792. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  793. break;
  794. }
  795. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  796. {
  797. float left, right;
  798. value = ctrlEvent.value/0.5f - 1.0f;
  799. if (value < 0.0f)
  800. {
  801. left = -1.0f;
  802. right = (value*2.0f)+1.0f;
  803. }
  804. else if (value > 0.0f)
  805. {
  806. left = (value*2.0f)-1.0f;
  807. right = 1.0f;
  808. }
  809. else
  810. {
  811. left = -1.0f;
  812. right = 1.0f;
  813. }
  814. setBalanceLeft(left, false, false);
  815. setBalanceRight(right, false, false);
  816. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  817. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  818. break;
  819. }
  820. }
  821. fShmRtControl.writeOpcode(kPluginBridgeRtControlEventParameter);
  822. fShmRtControl.writeUInt(event.time);
  823. fShmRtControl.writeByte(event.channel);
  824. fShmRtControl.writeUShort(event.ctrl.param);
  825. fShmRtControl.writeFloat(event.ctrl.value);
  826. fShmRtControl.commitWrite();
  827. break;
  828. case kEngineControlEventTypeMidiBank:
  829. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  830. {
  831. fShmRtControl.writeOpcode(kPluginBridgeRtControlEventMidiBank);
  832. fShmRtControl.writeUInt(event.time);
  833. fShmRtControl.writeByte(event.channel);
  834. fShmRtControl.writeUShort(event.ctrl.param);
  835. fShmRtControl.commitWrite();
  836. }
  837. break;
  838. case kEngineControlEventTypeMidiProgram:
  839. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  840. {
  841. fShmRtControl.writeOpcode(kPluginBridgeRtControlEventMidiProgram);
  842. fShmRtControl.writeUInt(event.time);
  843. fShmRtControl.writeByte(event.channel);
  844. fShmRtControl.writeUShort(event.ctrl.param);
  845. fShmRtControl.commitWrite();
  846. }
  847. break;
  848. case kEngineControlEventTypeAllSoundOff:
  849. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  850. {
  851. fShmRtControl.writeOpcode(kPluginBridgeRtControlEventAllSoundOff);
  852. fShmRtControl.writeUInt(event.time);
  853. fShmRtControl.writeByte(event.channel);
  854. fShmRtControl.commitWrite();
  855. }
  856. break;
  857. case kEngineControlEventTypeAllNotesOff:
  858. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  859. {
  860. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  861. {
  862. allNotesOffSent = true;
  863. sendMidiAllNotesOffToCallback();
  864. }
  865. fShmRtControl.writeOpcode(kPluginBridgeRtControlEventAllNotesOff);
  866. fShmRtControl.writeUInt(event.time);
  867. fShmRtControl.writeByte(event.channel);
  868. fShmRtControl.commitWrite();
  869. }
  870. break;
  871. } // switch (ctrlEvent.type)
  872. break;
  873. } // case kEngineEventTypeControl
  874. case kEngineEventTypeMidi: {
  875. const EngineMidiEvent& midiEvent(event.midi);
  876. if (midiEvent.size == 0 || midiEvent.size >= MAX_MIDI_VALUE)
  877. continue;
  878. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiEvent.data));
  879. uint8_t channel = event.channel;
  880. if (MIDI_IS_STATUS_NOTE_ON(status) && midiEvent.data[2] == 0)
  881. status = MIDI_STATUS_NOTE_OFF;
  882. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  883. continue;
  884. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  885. continue;
  886. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  887. continue;
  888. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  889. continue;
  890. fShmRtControl.writeOpcode(kPluginBridgeRtMidiEvent);
  891. fShmRtControl.writeUInt(event.time);
  892. fShmRtControl.writeByte(midiEvent.port);
  893. fShmRtControl.writeByte(midiEvent.size);
  894. for (uint8_t j=0; j < midiEvent.size; ++j)
  895. fShmRtControl.writeByte(midiEvent.data[j]);
  896. fShmRtControl.commitWrite();
  897. if (status == MIDI_STATUS_NOTE_ON)
  898. pData->postponeRtEvent(kPluginPostRtEventNoteOn, channel, midiEvent.data[1], midiEvent.data[2]);
  899. else if (status == MIDI_STATUS_NOTE_OFF)
  900. pData->postponeRtEvent(kPluginPostRtEventNoteOff, channel, midiEvent.data[1], 0.0f);
  901. } break;
  902. }
  903. }
  904. pData->postRtEvents.trySplice();
  905. } // End of Event Input
  906. processSingle(inBuffer, outBuffer, frames);
  907. }
  908. bool processSingle(float** const inBuffer, float** const outBuffer, const uint32_t frames)
  909. {
  910. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  911. if (pData->audioIn.count > 0)
  912. {
  913. CARLA_SAFE_ASSERT_RETURN(inBuffer != nullptr, false);
  914. }
  915. if (pData->audioOut.count > 0)
  916. {
  917. CARLA_SAFE_ASSERT_RETURN(outBuffer != nullptr, false);
  918. }
  919. // --------------------------------------------------------------------------------------------------------
  920. // Try lock, silence otherwise
  921. if (pData->engine->isOffline())
  922. {
  923. pData->singleMutex.lock();
  924. }
  925. else if (! pData->singleMutex.tryLock())
  926. {
  927. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  928. FloatVectorOperations::clear(outBuffer[i], static_cast<int>(frames));
  929. return false;
  930. }
  931. // --------------------------------------------------------------------------------------------------------
  932. // Reset audio buffers
  933. //std::memset(fShmAudioPool.data, 0, fShmAudioPool.size);
  934. for (uint32_t i=0; i < fInfo.aIns; ++i)
  935. FloatVectorOperations::copy(fShmAudioPool.data + (i * frames), inBuffer[i], static_cast<int>(frames));
  936. // --------------------------------------------------------------------------------------------------------
  937. // TimeInfo
  938. const EngineTimeInfo& timeInfo(pData->engine->getTimeInfo());
  939. BridgeTimeInfo& bridgeTimeInfo(fShmRtControl.data->timeInfo);
  940. bridgeTimeInfo.playing = timeInfo.playing;
  941. bridgeTimeInfo.frame = timeInfo.frame;
  942. bridgeTimeInfo.usecs = timeInfo.usecs;
  943. bridgeTimeInfo.valid = timeInfo.valid;
  944. if (timeInfo.valid & EngineTimeInfo::kValidBBT)
  945. {
  946. bridgeTimeInfo.bar = timeInfo.bbt.bar;
  947. bridgeTimeInfo.beat = timeInfo.bbt.beat;
  948. bridgeTimeInfo.tick = timeInfo.bbt.tick;
  949. bridgeTimeInfo.beatsPerBar = timeInfo.bbt.beatsPerBar;
  950. bridgeTimeInfo.beatType = timeInfo.bbt.beatType;
  951. bridgeTimeInfo.ticksPerBeat = timeInfo.bbt.ticksPerBeat;
  952. bridgeTimeInfo.beatsPerMinute = timeInfo.bbt.beatsPerMinute;
  953. bridgeTimeInfo.barStartTick = timeInfo.bbt.barStartTick;
  954. }
  955. // --------------------------------------------------------------------------------------------------------
  956. // Run plugin
  957. {
  958. fShmRtControl.writeOpcode(kPluginBridgeRtProcess);
  959. fShmRtControl.commitWrite();
  960. }
  961. if (! waitForServer(2))
  962. {
  963. pData->singleMutex.unlock();
  964. return true;
  965. }
  966. for (uint32_t i=0; i < fInfo.aOuts; ++i)
  967. FloatVectorOperations::copy(outBuffer[i], fShmAudioPool.data + ((i + fInfo.aIns) * frames), static_cast<int>(frames));
  968. // --------------------------------------------------------------------------------------------------------
  969. // Post-processing (dry/wet, volume and balance)
  970. {
  971. const bool doVolume = (pData->hints & PLUGIN_CAN_VOLUME) != 0 && ! carla_compareFloats(pData->postProc.volume, 1.0f);
  972. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && ! carla_compareFloats(pData->postProc.dryWet, 1.0f);
  973. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_compareFloats(pData->postProc.balanceLeft, -1.0f) && carla_compareFloats(pData->postProc.balanceRight, 1.0f));
  974. bool isPair;
  975. float bufValue, oldBufLeft[doBalance ? frames : 1];
  976. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  977. {
  978. // Dry/Wet
  979. if (doDryWet)
  980. {
  981. for (uint32_t k=0; k < frames; ++k)
  982. {
  983. bufValue = inBuffer[(pData->audioIn.count == 1) ? 0 : i][k];
  984. outBuffer[i][k] = (outBuffer[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  985. }
  986. }
  987. // Balance
  988. if (doBalance)
  989. {
  990. isPair = (i % 2 == 0);
  991. if (isPair)
  992. {
  993. CARLA_ASSERT(i+1 < pData->audioOut.count);
  994. FloatVectorOperations::copy(oldBufLeft, outBuffer[i], static_cast<int>(frames));
  995. }
  996. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  997. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  998. for (uint32_t k=0; k < frames; ++k)
  999. {
  1000. if (isPair)
  1001. {
  1002. // left
  1003. outBuffer[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  1004. outBuffer[i][k] += outBuffer[i+1][k] * (1.0f - balRangeR);
  1005. }
  1006. else
  1007. {
  1008. // right
  1009. outBuffer[i][k] = outBuffer[i][k] * balRangeR;
  1010. outBuffer[i][k] += oldBufLeft[k] * balRangeL;
  1011. }
  1012. }
  1013. }
  1014. // Volume (and buffer copy)
  1015. if (doVolume)
  1016. {
  1017. for (uint32_t k=0; k < frames; ++k)
  1018. outBuffer[i][k] *= pData->postProc.volume;
  1019. }
  1020. }
  1021. } // End of Post-processing
  1022. // --------------------------------------------------------------------------------------------------------
  1023. pData->singleMutex.unlock();
  1024. return true;
  1025. }
  1026. void bufferSizeChanged(const uint32_t newBufferSize) override
  1027. {
  1028. resizeAudioPool(newBufferSize);
  1029. {
  1030. const CarlaMutexLocker _cml(fShmNonRtControl.mutex);
  1031. fShmNonRtControl.writeOpcode(kPluginBridgeNonRtSetBufferSize);
  1032. fShmNonRtControl.writeUInt(newBufferSize);
  1033. fShmNonRtControl.commitWrite();
  1034. }
  1035. fShmRtControl.waitForServer(1);
  1036. }
  1037. void sampleRateChanged(const double newSampleRate) override
  1038. {
  1039. {
  1040. const CarlaMutexLocker _cml(fShmNonRtControl.mutex);
  1041. fShmNonRtControl.writeOpcode(kPluginBridgeNonRtSetSampleRate);
  1042. fShmNonRtControl.writeDouble(newSampleRate);
  1043. fShmNonRtControl.commitWrite();
  1044. }
  1045. fShmRtControl.waitForServer(1);
  1046. }
  1047. void offlineModeChanged(const bool isOffline) override
  1048. {
  1049. {
  1050. const CarlaMutexLocker _cml(fShmNonRtControl.mutex);
  1051. fShmNonRtControl.writeOpcode(isOffline ? kPluginBridgeNonRtSetOffline : kPluginBridgeNonRtSetOnline);
  1052. fShmNonRtControl.commitWrite();
  1053. }
  1054. fShmRtControl.waitForServer(1);
  1055. }
  1056. // -------------------------------------------------------------------
  1057. // Plugin buffers
  1058. void clearBuffers() noexcept override
  1059. {
  1060. if (fParams != nullptr)
  1061. {
  1062. delete[] fParams;
  1063. fParams = nullptr;
  1064. }
  1065. CarlaPlugin::clearBuffers();
  1066. }
  1067. // -------------------------------------------------------------------
  1068. // OSC stuff
  1069. void updateOscURL() override
  1070. {
  1071. const String newURL(String(pData->engine->getOscServerPathUDP()) + String("/") + String(pData->id));
  1072. const uint32_t ulength(static_cast<uint32_t>(newURL.length()));
  1073. const CarlaMutexLocker _cml(fShmNonRtControl.mutex);
  1074. fShmNonRtControl.writeOpcode(kPluginBridgeNonRtSetOscURL);
  1075. fShmNonRtControl.writeUInt(ulength);
  1076. fShmNonRtControl.writeCustomData(newURL.toRawUTF8(), ulength);
  1077. fShmNonRtControl.commitWrite();
  1078. }
  1079. // -------------------------------------------------------------------
  1080. // Post-poned UI Stuff
  1081. void uiParameterChange(const uint32_t index, const float value) noexcept override
  1082. {
  1083. CARLA_SAFE_ASSERT_RETURN(index < pData->param.count,);
  1084. const CarlaMutexLocker _cml(fShmNonRtControl.mutex);
  1085. fShmNonRtControl.writeOpcode(kPluginBridgeNonRtUiParameterChange);
  1086. fShmNonRtControl.writeUInt(index);
  1087. fShmNonRtControl.writeFloat(value);
  1088. fShmNonRtControl.commitWrite();
  1089. }
  1090. void uiProgramChange(const uint32_t index) noexcept override
  1091. {
  1092. CARLA_SAFE_ASSERT_RETURN(index < pData->midiprog.count,);
  1093. const CarlaMutexLocker _cml(fShmNonRtControl.mutex);
  1094. fShmNonRtControl.writeOpcode(kPluginBridgeNonRtUiProgramChange);
  1095. fShmNonRtControl.writeUInt(index);
  1096. fShmNonRtControl.commitWrite();
  1097. }
  1098. void uiMidiProgramChange(const uint32_t index) noexcept override
  1099. {
  1100. CARLA_SAFE_ASSERT_RETURN(index < pData->midiprog.count,);
  1101. const CarlaMutexLocker _cml(fShmNonRtControl.mutex);
  1102. fShmNonRtControl.writeOpcode(kPluginBridgeNonRtUiMidiProgramChange);
  1103. fShmNonRtControl.writeUInt(index);
  1104. fShmNonRtControl.commitWrite();
  1105. }
  1106. void uiNoteOn(const uint8_t channel, const uint8_t note, const uint8_t velo) noexcept override
  1107. {
  1108. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  1109. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  1110. CARLA_SAFE_ASSERT_RETURN(velo > 0 && velo < MAX_MIDI_VALUE,);
  1111. const CarlaMutexLocker _cml(fShmNonRtControl.mutex);
  1112. fShmNonRtControl.writeOpcode(kPluginBridgeNonRtUiNoteOn);
  1113. fShmNonRtControl.writeByte(channel);
  1114. fShmNonRtControl.writeByte(note);
  1115. fShmNonRtControl.writeByte(velo);
  1116. fShmNonRtControl.commitWrite();
  1117. }
  1118. void uiNoteOff(const uint8_t channel, const uint8_t note) noexcept override
  1119. {
  1120. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  1121. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  1122. const CarlaMutexLocker _cml(fShmNonRtControl.mutex);
  1123. fShmNonRtControl.writeOpcode(kPluginBridgeNonRtUiNoteOff);
  1124. fShmNonRtControl.writeByte(channel);
  1125. fShmNonRtControl.writeByte(note);
  1126. fShmNonRtControl.commitWrite();
  1127. }
  1128. // -------------------------------------------------------------------
  1129. int setOscPluginBridgeInfo(const PluginBridgeOscInfoType infoType, const int argc, const lo_arg* const* const argv, const char* const types)
  1130. {
  1131. #ifdef DEBUG
  1132. if (infoType != kPluginBridgeOscPong) {
  1133. carla_debug("BridgePlugin::setOscPluginBridgeInfo(%s, %i, %p, \"%s\")", PluginBridgeOscInfoType2str(infoType), argc, argv, types);
  1134. }
  1135. #endif
  1136. switch (infoType)
  1137. {
  1138. case kPluginBridgeOscNull:
  1139. break;
  1140. case kPluginBridgeOscPong:
  1141. if (fLastPongCounter > 0)
  1142. fLastPongCounter = 0;
  1143. break;
  1144. case kPluginBridgeOscPluginInfo1: {
  1145. CARLA_BRIDGE_CHECK_OSC_TYPES(5, "iiiih");
  1146. const int32_t category = argv[0]->i;
  1147. const int32_t hints = argv[1]->i;
  1148. const int32_t optionAv = argv[2]->i;
  1149. const int32_t optionEn = argv[3]->i;
  1150. const int64_t uniqueId = argv[4]->h;
  1151. CARLA_SAFE_ASSERT_BREAK(category >= 0);
  1152. CARLA_SAFE_ASSERT_BREAK(hints >= 0);
  1153. CARLA_SAFE_ASSERT_BREAK(optionAv >= 0);
  1154. CARLA_SAFE_ASSERT_BREAK(optionEn >= 0);
  1155. pData->hints = static_cast<uint>(hints);
  1156. pData->hints |= PLUGIN_IS_BRIDGE;
  1157. pData->options = static_cast<uint>(optionEn);
  1158. fInfo.category = static_cast<PluginCategory>(category);
  1159. fInfo.uniqueId = uniqueId;
  1160. fInfo.optionsAvailable = static_cast<uint>(optionAv);
  1161. break;
  1162. }
  1163. case kPluginBridgeOscPluginInfo2: {
  1164. CARLA_BRIDGE_CHECK_OSC_TYPES(4, "ssss");
  1165. const char* const realName = (const char*)&argv[0]->s;
  1166. const char* const label = (const char*)&argv[1]->s;
  1167. const char* const maker = (const char*)&argv[2]->s;
  1168. const char* const copyright = (const char*)&argv[3]->s;
  1169. CARLA_SAFE_ASSERT_BREAK(realName != nullptr);
  1170. CARLA_SAFE_ASSERT_BREAK(label != nullptr);
  1171. CARLA_SAFE_ASSERT_BREAK(maker != nullptr);
  1172. CARLA_SAFE_ASSERT_BREAK(copyright != nullptr);
  1173. fInfo.name = realName;
  1174. fInfo.label = label;
  1175. fInfo.maker = maker;
  1176. fInfo.copyright = copyright;
  1177. if (pData->name == nullptr)
  1178. pData->name = pData->engine->getUniquePluginName(realName);
  1179. break;
  1180. }
  1181. case kPluginBridgeOscAudioCount: {
  1182. CARLA_BRIDGE_CHECK_OSC_TYPES(2, "ii");
  1183. const int32_t ins = argv[0]->i;
  1184. const int32_t outs = argv[1]->i;
  1185. CARLA_SAFE_ASSERT_BREAK(ins >= 0);
  1186. CARLA_SAFE_ASSERT_BREAK(outs >= 0);
  1187. fInfo.aIns = static_cast<uint32_t>(ins);
  1188. fInfo.aOuts = static_cast<uint32_t>(outs);
  1189. break;
  1190. }
  1191. case kPluginBridgeOscMidiCount: {
  1192. CARLA_BRIDGE_CHECK_OSC_TYPES(2, "ii");
  1193. const int32_t ins = argv[0]->i;
  1194. const int32_t outs = argv[1]->i;
  1195. CARLA_SAFE_ASSERT_BREAK(ins >= 0);
  1196. CARLA_SAFE_ASSERT_BREAK(outs >= 0);
  1197. fInfo.mIns = static_cast<uint32_t>(ins);
  1198. fInfo.mOuts = static_cast<uint32_t>(outs);
  1199. break;
  1200. }
  1201. case kPluginBridgeOscParameterCount: {
  1202. CARLA_BRIDGE_CHECK_OSC_TYPES(2, "ii");
  1203. const int32_t ins = argv[0]->i;
  1204. const int32_t outs = argv[1]->i;
  1205. CARLA_SAFE_ASSERT_BREAK(ins >= 0);
  1206. CARLA_SAFE_ASSERT_BREAK(outs >= 0);
  1207. // delete old data
  1208. pData->param.clear();
  1209. if (fParams != nullptr)
  1210. {
  1211. delete[] fParams;
  1212. fParams = nullptr;
  1213. }
  1214. if (int32_t count = ins+outs)
  1215. {
  1216. const int32_t maxParams(static_cast<int32_t>(pData->engine->getOptions().maxParameters));
  1217. if (count > maxParams)
  1218. {
  1219. count = maxParams;
  1220. carla_safe_assert_int2("count <= pData->engine->getOptions().maxParameters", __FILE__, __LINE__, count, maxParams);
  1221. }
  1222. const uint32_t ucount(static_cast<uint32_t>(count));
  1223. pData->param.createNew(ucount, false);
  1224. fParams = new BridgeParamInfo[ucount];
  1225. }
  1226. break;
  1227. }
  1228. case kPluginBridgeOscProgramCount: {
  1229. CARLA_BRIDGE_CHECK_OSC_TYPES(1, "i");
  1230. const int32_t count = argv[0]->i;
  1231. CARLA_SAFE_ASSERT_BREAK(count >= 0);
  1232. pData->prog.clear();
  1233. if (count > 0)
  1234. pData->prog.createNew(static_cast<uint32_t>(count));
  1235. break;
  1236. }
  1237. case kPluginBridgeOscMidiProgramCount: {
  1238. CARLA_BRIDGE_CHECK_OSC_TYPES(1, "i");
  1239. const int32_t count = argv[0]->i;
  1240. CARLA_SAFE_ASSERT_BREAK(count >= 0);
  1241. pData->midiprog.clear();
  1242. if (count > 0)
  1243. pData->midiprog.createNew(static_cast<uint32_t>(count));
  1244. break;
  1245. }
  1246. case kPluginBridgeOscParameterData1: {
  1247. CARLA_BRIDGE_CHECK_OSC_TYPES(5, "iiiii");
  1248. const int32_t index = argv[0]->i;
  1249. const int32_t rindex = argv[1]->i;
  1250. const int32_t type = argv[2]->i;
  1251. const int32_t hints = argv[3]->i;
  1252. const int32_t midiCC = argv[4]->i;
  1253. CARLA_SAFE_ASSERT_BREAK(index >= 0);
  1254. CARLA_SAFE_ASSERT_BREAK(rindex >= 0);
  1255. CARLA_SAFE_ASSERT_BREAK(type >= 0);
  1256. CARLA_SAFE_ASSERT_BREAK(hints >= 0);
  1257. CARLA_SAFE_ASSERT_BREAK(midiCC >= -1 && midiCC < 0x5F);
  1258. CARLA_SAFE_ASSERT_INT2(index < static_cast<int32_t>(pData->param.count), index, pData->param.count);
  1259. if (index < static_cast<int32_t>(pData->param.count))
  1260. {
  1261. pData->param.data[index].type = static_cast<ParameterType>(type);
  1262. pData->param.data[index].index = index;
  1263. pData->param.data[index].rindex = rindex;
  1264. pData->param.data[index].hints = static_cast<uint>(hints);
  1265. pData->param.data[index].midiCC = static_cast<int16_t>(midiCC);
  1266. }
  1267. break;
  1268. }
  1269. case kPluginBridgeOscParameterData2: {
  1270. CARLA_BRIDGE_CHECK_OSC_TYPES(3, "iss");
  1271. const int32_t index = argv[0]->i;
  1272. const char* const name = (const char*)&argv[1]->s;
  1273. const char* const unit = (const char*)&argv[2]->s;
  1274. CARLA_SAFE_ASSERT_BREAK(index >= 0);
  1275. CARLA_SAFE_ASSERT_BREAK(name != nullptr);
  1276. CARLA_SAFE_ASSERT_BREAK(unit != nullptr);
  1277. CARLA_SAFE_ASSERT_INT2(index < static_cast<int32_t>(pData->param.count), index, pData->param.count);
  1278. if (index < static_cast<int32_t>(pData->param.count))
  1279. {
  1280. fParams[index].name = name;
  1281. fParams[index].unit = unit;
  1282. }
  1283. break;
  1284. }
  1285. case kPluginBridgeOscParameterRanges1: {
  1286. CARLA_BRIDGE_CHECK_OSC_TYPES(4, "ifff");
  1287. const int32_t index = argv[0]->i;
  1288. const float def = argv[1]->f;
  1289. const float min = argv[2]->f;
  1290. const float max = argv[3]->f;
  1291. CARLA_SAFE_ASSERT_BREAK(index >= 0);
  1292. CARLA_SAFE_ASSERT_BREAK(min < max);
  1293. CARLA_SAFE_ASSERT_BREAK(def >= min);
  1294. CARLA_SAFE_ASSERT_BREAK(def <= max);
  1295. CARLA_SAFE_ASSERT_INT2(index < static_cast<int32_t>(pData->param.count), index, pData->param.count);
  1296. if (index < static_cast<int32_t>(pData->param.count))
  1297. {
  1298. pData->param.ranges[index].def = def;
  1299. pData->param.ranges[index].min = min;
  1300. pData->param.ranges[index].max = max;
  1301. }
  1302. break;
  1303. }
  1304. case kPluginBridgeOscParameterRanges2: {
  1305. CARLA_BRIDGE_CHECK_OSC_TYPES(4, "ifff");
  1306. const int32_t index = argv[0]->i;
  1307. const float step = argv[1]->f;
  1308. const float stepSmall = argv[2]->f;
  1309. const float stepLarge = argv[3]->f;
  1310. CARLA_SAFE_ASSERT_BREAK(index >= 0);
  1311. CARLA_SAFE_ASSERT_INT2(index < static_cast<int32_t>(pData->param.count), index, pData->param.count);
  1312. if (index < static_cast<int32_t>(pData->param.count))
  1313. {
  1314. pData->param.ranges[index].step = step;
  1315. pData->param.ranges[index].stepSmall = stepSmall;
  1316. pData->param.ranges[index].stepLarge = stepLarge;
  1317. }
  1318. break;
  1319. }
  1320. case kPluginBridgeOscParameterValue: {
  1321. CARLA_BRIDGE_CHECK_OSC_TYPES(2, "if");
  1322. const int32_t index = argv[0]->i;
  1323. const float value = argv[1]->f;
  1324. CARLA_SAFE_ASSERT_BREAK(index >= 0);
  1325. CARLA_SAFE_ASSERT_INT2(index < static_cast<int32_t>(pData->param.count), index, pData->param.count);
  1326. if (index < static_cast<int32_t>(pData->param.count))
  1327. {
  1328. const uint32_t uindex(static_cast<uint32_t>(index));
  1329. const float fixedValue(pData->param.getFixedValue(uindex, value));
  1330. fParams[uindex].value = fixedValue;
  1331. CarlaPlugin::setParameterValue(uindex, fixedValue, false, true, true);
  1332. }
  1333. break;
  1334. }
  1335. case kPluginBridgeOscDefaultValue: {
  1336. CARLA_BRIDGE_CHECK_OSC_TYPES(2, "if");
  1337. const int32_t index = argv[0]->i;
  1338. const float value = argv[1]->f;
  1339. CARLA_SAFE_ASSERT_BREAK(index >= 0);
  1340. CARLA_SAFE_ASSERT_INT2(index < static_cast<int32_t>(pData->param.count), index, pData->param.count);
  1341. if (index < static_cast<int32_t>(pData->param.count))
  1342. pData->param.ranges[index].def = value;
  1343. break;
  1344. }
  1345. case kPluginBridgeOscCurrentProgram: {
  1346. CARLA_BRIDGE_CHECK_OSC_TYPES(1, "i");
  1347. const int32_t index = argv[0]->i;
  1348. CARLA_SAFE_ASSERT_BREAK(index >= -1);
  1349. CARLA_SAFE_ASSERT_INT2(index < static_cast<int32_t>(pData->prog.count), index, pData->prog.count);
  1350. CarlaPlugin::setProgram(index, false, true, true);
  1351. break;
  1352. }
  1353. case kPluginBridgeOscCurrentMidiProgram: {
  1354. CARLA_BRIDGE_CHECK_OSC_TYPES(1, "i");
  1355. const int32_t index = argv[0]->i;
  1356. CARLA_SAFE_ASSERT_BREAK(index >= -1);
  1357. CARLA_SAFE_ASSERT_INT2(index < static_cast<int32_t>(pData->midiprog.count), index, pData->midiprog.count);
  1358. CarlaPlugin::setMidiProgram(index, false, true, true);
  1359. break;
  1360. }
  1361. case kPluginBridgeOscProgramName: {
  1362. CARLA_BRIDGE_CHECK_OSC_TYPES(2, "is");
  1363. const int32_t index = argv[0]->i;
  1364. const char* const name = (const char*)&argv[1]->s;
  1365. CARLA_SAFE_ASSERT_BREAK(index >= 0);
  1366. CARLA_SAFE_ASSERT_BREAK(name != nullptr);
  1367. CARLA_SAFE_ASSERT_INT2(index < static_cast<int32_t>(pData->prog.count), index, pData->prog.count);
  1368. if (index < static_cast<int32_t>(pData->prog.count))
  1369. {
  1370. if (pData->prog.names[index] != nullptr)
  1371. delete[] pData->prog.names[index];
  1372. pData->prog.names[index] = carla_strdup(name);
  1373. }
  1374. break;
  1375. }
  1376. case kPluginBridgeOscMidiProgramData: {
  1377. CARLA_BRIDGE_CHECK_OSC_TYPES(4, "iiis");
  1378. const int32_t index = argv[0]->i;
  1379. const int32_t bank = argv[1]->i;
  1380. const int32_t program = argv[2]->i;
  1381. const char* const name = (const char*)&argv[3]->s;
  1382. CARLA_SAFE_ASSERT_BREAK(index >= 0);
  1383. CARLA_SAFE_ASSERT_BREAK(bank >= 0);
  1384. CARLA_SAFE_ASSERT_BREAK(program >= 0);
  1385. CARLA_SAFE_ASSERT_BREAK(name != nullptr);
  1386. CARLA_SAFE_ASSERT_INT2(index < static_cast<int32_t>(pData->midiprog.count), index, pData->midiprog.count);
  1387. if (index < static_cast<int32_t>(pData->midiprog.count))
  1388. {
  1389. if (pData->midiprog.data[index].name != nullptr)
  1390. delete[] pData->midiprog.data[index].name;
  1391. pData->midiprog.data[index].bank = static_cast<uint32_t>(bank);
  1392. pData->midiprog.data[index].program = static_cast<uint32_t>(program);
  1393. pData->midiprog.data[index].name = carla_strdup(name);
  1394. }
  1395. break;
  1396. }
  1397. case kPluginBridgeOscConfigure: {
  1398. CARLA_BRIDGE_CHECK_OSC_TYPES(2, "ss");
  1399. const char* const key = (const char*)&argv[0]->s;
  1400. const char* const value = (const char*)&argv[1]->s;
  1401. CARLA_SAFE_ASSERT_BREAK(key != nullptr);
  1402. CARLA_SAFE_ASSERT_BREAK(value != nullptr);
  1403. if (std::strcmp(key, CARLA_BRIDGE_MSG_HIDE_GUI) == 0)
  1404. pData->engine->callback(ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, 0, 0, 0.0f, nullptr);
  1405. else if (std::strcmp(key, CARLA_BRIDGE_MSG_SAVED) == 0)
  1406. fSaved = true;
  1407. break;
  1408. }
  1409. case kPluginBridgeOscSetCustomData: {
  1410. CARLA_BRIDGE_CHECK_OSC_TYPES(3, "sss");
  1411. const char* const type = (const char*)&argv[0]->s;
  1412. const char* const key = (const char*)&argv[1]->s;
  1413. const char* const value = (const char*)&argv[2]->s;
  1414. CARLA_SAFE_ASSERT_BREAK(type != nullptr);
  1415. CARLA_SAFE_ASSERT_BREAK(key != nullptr);
  1416. CARLA_SAFE_ASSERT_BREAK(value != nullptr);
  1417. CarlaPlugin::setCustomData(type, key, value, false);
  1418. break;
  1419. }
  1420. case kPluginBridgeOscSetChunkDataFile: {
  1421. CARLA_BRIDGE_CHECK_OSC_TYPES(1, "s");
  1422. const char* const chunkFilePath = (const char*)&argv[0]->s;
  1423. CARLA_SAFE_ASSERT_BREAK(chunkFilePath != nullptr);
  1424. String realChunkFilePath(chunkFilePath);
  1425. carla_stdout("chunk save path BEFORE => %s", realChunkFilePath.toRawUTF8());
  1426. #ifndef CARLA_OS_WIN
  1427. // Using Wine, fix temp dir
  1428. if (fBinaryType == BINARY_WIN32 || fBinaryType == BINARY_WIN64)
  1429. {
  1430. // Get WINEPREFIX
  1431. String wineDir;
  1432. if (const char* const WINEPREFIX = getenv("WINEPREFIX"))
  1433. wineDir = String(WINEPREFIX);
  1434. else
  1435. wineDir = File::getSpecialLocation(File::userHomeDirectory).getFullPathName() + "/.wine";
  1436. const StringArray driveLetterSplit(StringArray::fromTokens(realChunkFilePath, ":/", ""));
  1437. realChunkFilePath = wineDir;
  1438. realChunkFilePath += "/drive_";
  1439. realChunkFilePath += driveLetterSplit[0].toLowerCase();
  1440. realChunkFilePath += "/";
  1441. realChunkFilePath += driveLetterSplit[1];
  1442. realChunkFilePath = realChunkFilePath.replace("\\", "/");
  1443. carla_stdout("chunk save path AFTER => %s", realChunkFilePath.toRawUTF8());
  1444. }
  1445. #endif
  1446. File chunkFile(realChunkFilePath);
  1447. if (chunkFile.existsAsFile())
  1448. {
  1449. fInfo.chunk = carla_getChunkFromBase64String(chunkFile.loadFileAsString().toRawUTF8());
  1450. chunkFile.deleteFile();
  1451. carla_stderr("chunk data final");
  1452. }
  1453. break;
  1454. }
  1455. case kPluginBridgeOscLatency:
  1456. // TODO
  1457. break;
  1458. case kPluginBridgeOscReady:
  1459. fInitiated = true;
  1460. break;
  1461. case kPluginBridgeOscError: {
  1462. CARLA_BRIDGE_CHECK_OSC_TYPES(1, "s");
  1463. const char* const error = (const char*)&argv[0]->s;
  1464. CARLA_ASSERT(error != nullptr);
  1465. pData->engine->setLastError(error);
  1466. fInitError = true;
  1467. fInitiated = true;
  1468. break;
  1469. }
  1470. }
  1471. return 0;
  1472. }
  1473. // -------------------------------------------------------------------
  1474. const void* getExtraStuff() const noexcept override
  1475. {
  1476. return fBridgeBinary.isNotEmpty() ? fBridgeBinary.buffer() : nullptr;
  1477. }
  1478. bool init(const char* const filename, const char* const name, const char* const label, const char* const bridgeBinary)
  1479. {
  1480. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  1481. // ---------------------------------------------------------------
  1482. // first checks
  1483. if (pData->client != nullptr)
  1484. {
  1485. pData->engine->setLastError("Plugin client is already registered");
  1486. return false;
  1487. }
  1488. // ---------------------------------------------------------------
  1489. // set info
  1490. if (name != nullptr && name[0] != '\0')
  1491. pData->name = pData->engine->getUniquePluginName(name);
  1492. pData->filename = carla_strdup(filename);
  1493. if (bridgeBinary != nullptr)
  1494. fBridgeBinary = bridgeBinary;
  1495. std::srand(static_cast<uint>(std::time(nullptr)));
  1496. // ---------------------------------------------------------------
  1497. // SHM Audio Pool
  1498. {
  1499. char tmpFileBase[64];
  1500. std::sprintf(tmpFileBase, "/carla-bridge_shm_ap_XXXXXX");
  1501. fShmAudioPool.shm = shm_mkstemp(tmpFileBase);
  1502. if (! carla_is_shm_valid(fShmAudioPool.shm))
  1503. {
  1504. carla_stdout("Failed to open or create shared memory file #1");
  1505. return false;
  1506. }
  1507. fShmAudioPool.filename = tmpFileBase;
  1508. }
  1509. // ---------------------------------------------------------------
  1510. // SHM RT Control
  1511. {
  1512. char tmpFileBase[64];
  1513. std::sprintf(tmpFileBase, "/carla-bridge_shm_rt_XXXXXX");
  1514. fShmRtControl.shm = shm_mkstemp(tmpFileBase);
  1515. if (! carla_is_shm_valid(fShmRtControl.shm))
  1516. {
  1517. carla_stdout("Failed to open or create shared memory file #2");
  1518. // clear
  1519. carla_shm_close(fShmAudioPool.shm);
  1520. return false;
  1521. }
  1522. fShmRtControl.filename = tmpFileBase;
  1523. if (! fShmRtControl.mapData())
  1524. {
  1525. carla_stdout("Failed to map shared memory file #2");
  1526. // clear
  1527. carla_shm_close(fShmRtControl.shm);
  1528. carla_shm_close(fShmAudioPool.shm);
  1529. return false;
  1530. }
  1531. CARLA_SAFE_ASSERT(fShmRtControl.data != nullptr);
  1532. if (! jackbridge_sem_init(&fShmRtControl.data->sem.server))
  1533. {
  1534. carla_stdout("Failed to initialize shared memory semaphore #1");
  1535. // clear
  1536. fShmRtControl.unmapData();
  1537. carla_shm_close(fShmRtControl.shm);
  1538. carla_shm_close(fShmAudioPool.shm);
  1539. return false;
  1540. }
  1541. if (! jackbridge_sem_init(&fShmRtControl.data->sem.client))
  1542. {
  1543. carla_stdout("Failed to initialize shared memory semaphore #2");
  1544. // clear
  1545. jackbridge_sem_destroy(&fShmRtControl.data->sem.server);
  1546. fShmRtControl.unmapData();
  1547. carla_shm_close(fShmRtControl.shm);
  1548. carla_shm_close(fShmAudioPool.shm);
  1549. return false;
  1550. }
  1551. fNeedsSemDestroy = true;
  1552. }
  1553. // ---------------------------------------------------------------
  1554. // SHM Non-RT Control
  1555. {
  1556. char tmpFileBase[64];
  1557. std::sprintf(tmpFileBase, "/carla-bridge_shm_nonrt_XXXXXX");
  1558. fShmNonRtControl.shm = shm_mkstemp(tmpFileBase);
  1559. if (! carla_is_shm_valid(fShmNonRtControl.shm))
  1560. {
  1561. carla_stdout("Failed to open or create shared memory file #3");
  1562. return false;
  1563. }
  1564. fShmNonRtControl.filename = tmpFileBase;
  1565. if (! fShmNonRtControl.mapData())
  1566. {
  1567. carla_stdout("Failed to map shared memory file #3");
  1568. // clear
  1569. fShmNonRtControl.unmapData();
  1570. carla_shm_close(fShmNonRtControl.shm);
  1571. carla_shm_close(fShmRtControl.shm);
  1572. carla_shm_close(fShmAudioPool.shm);
  1573. return false;
  1574. }
  1575. }
  1576. carla_stdout("Carla Server Info:");
  1577. carla_stdout(" sizeof(BridgeRtData): " P_SIZE, sizeof(BridgeRtData));
  1578. carla_stdout(" sizeof(BridgeNonRtData): " P_SIZE, sizeof(BridgeNonRtData));
  1579. // initial values
  1580. fShmNonRtControl.writeOpcode(kPluginBridgeNonRtNull);
  1581. fShmNonRtControl.writeInt(static_cast<int32_t>(sizeof(BridgeRtData)));
  1582. fShmNonRtControl.writeInt(static_cast<int32_t>(sizeof(BridgeNonRtData)));
  1583. fShmNonRtControl.writeOpcode(kPluginBridgeNonRtSetBufferSize);
  1584. fShmNonRtControl.writeInt(static_cast<int32_t>(pData->engine->getBufferSize()));
  1585. fShmNonRtControl.writeOpcode(kPluginBridgeNonRtSetSampleRate);
  1586. fShmNonRtControl.writeDouble(pData->engine->getSampleRate());
  1587. fShmNonRtControl.commitWrite();
  1588. // register plugin now so we can receive OSC (and wait for it)
  1589. pData->hints |= PLUGIN_IS_BRIDGE;
  1590. pData->engine->registerEnginePlugin(pData->id, this);
  1591. // init OSC
  1592. {
  1593. char shmIdStr[18+1] = { 0 };
  1594. std::strncpy(shmIdStr, &fShmAudioPool.filename[fShmAudioPool.filename.length()-6], 6);
  1595. std::strncat(shmIdStr, &fShmRtControl.filename[fShmRtControl.filename.length()-6], 6);
  1596. std::strncat(shmIdStr, &fShmNonRtControl.filename[fShmNonRtControl.filename.length()-6], 6);
  1597. pData->osc.thread.setOscData(bridgeBinary, label, getPluginTypeAsString(fPluginType), shmIdStr);
  1598. pData->osc.thread.startThread();
  1599. }
  1600. fInitiated = false;
  1601. fLastPongCounter = 0;
  1602. for (; fLastPongCounter++ < 500;)
  1603. {
  1604. if (fInitiated || ! pData->osc.thread.isThreadRunning())
  1605. break;
  1606. carla_msleep(25);
  1607. pData->engine->callback(ENGINE_CALLBACK_IDLE, 0, 0, 0, 0.0f, nullptr);
  1608. pData->engine->idle();
  1609. }
  1610. fLastPongCounter = -1;
  1611. if (fInitError || ! fInitiated)
  1612. {
  1613. pData->osc.thread.stopThread(6000);
  1614. if (! fInitError)
  1615. pData->engine->setLastError("Timeout while waiting for a response from plugin-bridge\n(or the plugin crashed on initialization?)");
  1616. return false;
  1617. }
  1618. // ---------------------------------------------------------------
  1619. // register client
  1620. if (pData->name == nullptr)
  1621. {
  1622. if (name != nullptr && name[0] != '\0')
  1623. pData->name = pData->engine->getUniquePluginName(name);
  1624. else if (label != nullptr && label[0] != '\0')
  1625. pData->name = pData->engine->getUniquePluginName(label);
  1626. else
  1627. pData->name = pData->engine->getUniquePluginName("unknown");
  1628. }
  1629. pData->client = pData->engine->addClient(this);
  1630. if (pData->client == nullptr || ! pData->client->isOk())
  1631. {
  1632. pData->engine->setLastError("Failed to register plugin client");
  1633. return false;
  1634. }
  1635. return true;
  1636. }
  1637. private:
  1638. const BinaryType fBinaryType;
  1639. const PluginType fPluginType;
  1640. bool fInitiated;
  1641. bool fInitError;
  1642. bool fSaved;
  1643. bool fNeedsSemDestroy;
  1644. bool fTimedOut;
  1645. volatile int32_t fLastPongCounter;
  1646. CarlaString fBridgeBinary;
  1647. BridgeAudioPool fShmAudioPool;
  1648. BridgeRtControl fShmRtControl;
  1649. BridgeNonRtControl fShmNonRtControl;
  1650. struct Info {
  1651. uint32_t aIns, aOuts;
  1652. uint32_t mIns, mOuts;
  1653. PluginCategory category;
  1654. uint optionsAvailable;
  1655. int64_t uniqueId;
  1656. CarlaString name;
  1657. CarlaString label;
  1658. CarlaString maker;
  1659. CarlaString copyright;
  1660. std::vector<uint8_t> chunk;
  1661. Info()
  1662. : aIns(0),
  1663. aOuts(0),
  1664. mIns(0),
  1665. mOuts(0),
  1666. category(PLUGIN_CATEGORY_NONE),
  1667. optionsAvailable(0),
  1668. uniqueId(0),
  1669. name(),
  1670. label(),
  1671. maker(),
  1672. copyright(),
  1673. chunk() {}
  1674. } fInfo;
  1675. BridgeParamInfo* fParams;
  1676. void resizeAudioPool(const uint32_t bufferSize)
  1677. {
  1678. fShmAudioPool.resize(bufferSize, fInfo.aIns+fInfo.aOuts);
  1679. fShmRtControl.writeOpcode(kPluginBridgeRtSetAudioPool);
  1680. fShmRtControl.writeLong(static_cast<int64_t>(fShmAudioPool.size));
  1681. fShmRtControl.commitWrite();
  1682. waitForServer();
  1683. }
  1684. bool waitForServer(const int secs = 5)
  1685. {
  1686. CARLA_SAFE_ASSERT_RETURN(! fTimedOut, false);
  1687. if (! fShmRtControl.waitForServer(secs))
  1688. {
  1689. carla_stderr("waitForServer() timeout here");
  1690. fTimedOut = true;
  1691. return false;
  1692. }
  1693. return true;
  1694. }
  1695. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(BridgePlugin)
  1696. };
  1697. CARLA_BACKEND_END_NAMESPACE
  1698. #endif // ! BUILD_BRIDGE
  1699. // -------------------------------------------------------------------------------------------------------------------
  1700. CARLA_BACKEND_START_NAMESPACE
  1701. CarlaPlugin* CarlaPlugin::newBridge(const Initializer& init, BinaryType btype, PluginType ptype, const char* const bridgeBinary)
  1702. {
  1703. carla_debug("CarlaPlugin::newBridge({%p, \"%s\", \"%s\", \"%s\"}, %s, %s, \"%s\")", init.engine, init.filename, init.name, init.label, BinaryType2Str(btype), PluginType2Str(ptype), bridgeBinary);
  1704. #ifndef BUILD_BRIDGE
  1705. if (bridgeBinary == nullptr || bridgeBinary[0] == '\0')
  1706. {
  1707. init.engine->setLastError("Bridge not possible, bridge-binary not found");
  1708. return nullptr;
  1709. }
  1710. BridgePlugin* const plugin(new BridgePlugin(init.engine, init.id, btype, ptype));
  1711. if (! plugin->init(init.filename, init.name, init.label, bridgeBinary))
  1712. {
  1713. init.engine->registerEnginePlugin(init.id, nullptr);
  1714. delete plugin;
  1715. return nullptr;
  1716. }
  1717. plugin->reload();
  1718. if (init.engine->getProccessMode() == ENGINE_PROCESS_MODE_CONTINUOUS_RACK && ! plugin->canRunInRack())
  1719. {
  1720. init.engine->setLastError("Carla's rack mode can only work with Stereo Bridged plugins, sorry!");
  1721. delete plugin;
  1722. return nullptr;
  1723. }
  1724. return plugin;
  1725. #else
  1726. init.engine->setLastError("Plugin bridge support not available");
  1727. return nullptr;
  1728. // unused
  1729. (void)bridgeBinary;
  1730. #endif
  1731. }
  1732. #ifndef BUILD_BRIDGE
  1733. // -------------------------------------------------------------------------------------------------------------------
  1734. // Bridge Helper
  1735. #define bridgePlugin ((BridgePlugin*)plugin)
  1736. extern int CarlaPluginSetOscBridgeInfo(CarlaPlugin* const plugin, const PluginBridgeOscInfoType type,
  1737. const int argc, const lo_arg* const* const argv, const char* const types);
  1738. int CarlaPluginSetOscBridgeInfo(CarlaPlugin* const plugin, const PluginBridgeOscInfoType type,
  1739. const int argc, const lo_arg* const* const argv, const char* const types)
  1740. {
  1741. CARLA_SAFE_ASSERT(plugin != nullptr && (plugin->getHints() & PLUGIN_IS_BRIDGE) != 0);
  1742. return bridgePlugin->setOscPluginBridgeInfo(type, argc, argv, types);
  1743. }
  1744. #undef bridgePlugin
  1745. #endif
  1746. CARLA_BACKEND_END_NAMESPACE
  1747. // -------------------------------------------------------------------------------------------------------------------