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.

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