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.

1922 lines
64KB

  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 "CarlaBridgeUtils.hpp"
  22. #include "CarlaMathUtils.hpp"
  23. #include "CarlaShmUtils.hpp"
  24. #include "jackbridge/JackBridge.hpp"
  25. #include <cerrno>
  26. #include <cmath>
  27. #include <ctime>
  28. #define CARLA_BRIDGE_CHECK_OSC_TYPES(/* argc, types, */ argcToCompare, typesToCompare) \
  29. /* check argument count */ \
  30. if (argc != argcToCompare) \
  31. { \
  32. carla_stderr("BridgePlugin::%s() - argument count mismatch: %i != %i", __FUNCTION__, argc, argcToCompare); \
  33. return 1; \
  34. } \
  35. if (argc > 0) \
  36. { \
  37. /* check for nullness */ \
  38. if (! (types && typesToCompare)) \
  39. { \
  40. carla_stderr("BridgePlugin::%s() - argument types are null", __FUNCTION__); \
  41. return 1; \
  42. } \
  43. /* check argument types */ \
  44. if (std::strcmp(types, typesToCompare) != 0) \
  45. { \
  46. carla_stderr("BridgePlugin::%s() - argument types mismatch: '%s' != '%s'", __FUNCTION__, types, typesToCompare); \
  47. return 1; \
  48. } \
  49. }
  50. CARLA_BACKEND_START_NAMESPACE
  51. // -------------------------------------------------------------------------------------------------------------------
  52. // call carla_shm_create with for a XXXXXX temp filename
  53. static shm_t shm_mkstemp(char* const fileBase)
  54. {
  55. CARLA_SAFE_ASSERT_RETURN(fileBase != nullptr, gNullCarlaShm);
  56. const size_t fileBaseLen(std::strlen(fileBase));
  57. CARLA_SAFE_ASSERT_RETURN(fileBaseLen > 6, gNullCarlaShm);
  58. CARLA_SAFE_ASSERT_RETURN(std::strcmp(fileBase + fileBaseLen - 6, "XXXXXX") == 0, gNullCarlaShm);
  59. static const char charSet[] = "abcdefghijklmnopqrstuvwxyz"
  60. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  61. "0123456789";
  62. static const int charSetLen = static_cast<int>(sizeof(charSet) - 1); // -1 to avoid trailing '\0'
  63. // try until getting a valid shm or an error occurs
  64. for (;;)
  65. {
  66. for (size_t c = fileBaseLen - 6; c < fileBaseLen; ++c)
  67. fileBase[c] = charSet[std::rand() % charSetLen];
  68. const shm_t shm = carla_shm_create(fileBase);
  69. if (carla_is_shm_valid(shm))
  70. return shm;
  71. if (errno != EEXIST)
  72. return gNullCarlaShm;
  73. }
  74. }
  75. // -------------------------------------------------------------------------------------------------------------------
  76. struct BridgeAudioPool {
  77. CarlaString filename;
  78. float* data;
  79. size_t size;
  80. shm_t shm;
  81. BridgeAudioPool()
  82. : data(nullptr),
  83. size(0)
  84. {
  85. carla_shm_init(shm);
  86. }
  87. ~BridgeAudioPool()
  88. {
  89. // should be cleared by now
  90. CARLA_ASSERT(data == nullptr);
  91. clear();
  92. }
  93. void clear()
  94. {
  95. filename.clear();
  96. if (! carla_is_shm_valid(shm))
  97. return;
  98. if (data != nullptr)
  99. {
  100. carla_shm_unmap(shm, data, size);
  101. data = nullptr;
  102. }
  103. size = 0;
  104. carla_shm_close(shm);
  105. }
  106. void resize(const uint32_t bufferSize, const uint32_t portCount)
  107. {
  108. if (data != nullptr)
  109. carla_shm_unmap(shm, data, size);
  110. size = portCount*bufferSize*sizeof(float);
  111. if (size == 0)
  112. size = sizeof(float);
  113. data = (float*)carla_shm_map(shm, size);
  114. }
  115. };
  116. struct BridgeControl : public RingBufferControl<StackPackedRingBuffer> {
  117. CarlaString filename;
  118. BridgeShmControl* data;
  119. shm_t shm;
  120. BridgeControl()
  121. : RingBufferControl(nullptr),
  122. data(nullptr)
  123. {
  124. carla_shm_init(shm);
  125. }
  126. ~BridgeControl()
  127. {
  128. // should be cleared by now
  129. CARLA_ASSERT(data == nullptr);
  130. clear();
  131. }
  132. void clear()
  133. {
  134. filename.clear();
  135. if (! carla_is_shm_valid(shm))
  136. return;
  137. if (data != nullptr)
  138. {
  139. carla_shm_unmap(shm, data, sizeof(BridgeShmControl));
  140. data = nullptr;
  141. }
  142. carla_shm_close(shm);
  143. }
  144. bool mapData()
  145. {
  146. CARLA_ASSERT(data == nullptr);
  147. if (carla_shm_map<BridgeShmControl>(shm, data))
  148. {
  149. setRingBuffer(&data->ringBuffer, true);
  150. return true;
  151. }
  152. return false;
  153. }
  154. void unmapData()
  155. {
  156. CARLA_ASSERT(data != nullptr);
  157. if (data == nullptr)
  158. return;
  159. carla_shm_unmap(shm, data, sizeof(BridgeShmControl));
  160. data = nullptr;
  161. setRingBuffer(nullptr, false);
  162. }
  163. bool waitForServer()
  164. {
  165. CARLA_SAFE_ASSERT_RETURN(data != nullptr, false);
  166. jackbridge_sem_post(&data->runServer);
  167. return jackbridge_sem_timedwait(&data->runClient, 5);
  168. }
  169. void writeOpcode(const PluginBridgeOpcode opcode) noexcept
  170. {
  171. writeInt(static_cast<int32_t>(opcode));
  172. }
  173. };
  174. struct BridgeParamInfo {
  175. float value;
  176. CarlaString name;
  177. CarlaString unit;
  178. BridgeParamInfo()
  179. : value(0.0f) {}
  180. CARLA_DECLARE_NON_COPY_STRUCT(BridgeParamInfo)
  181. };
  182. // -------------------------------------------------------------------------------------------------------------------
  183. class BridgePlugin : public CarlaPlugin
  184. {
  185. public:
  186. BridgePlugin(CarlaEngine* const engine, const unsigned int id, const BinaryType btype, const PluginType ptype)
  187. : CarlaPlugin(engine, id),
  188. fBinaryType(btype),
  189. fPluginType(ptype),
  190. fInitiated(false),
  191. fInitError(false),
  192. fSaved(false),
  193. fNeedsSemDestroy(false),
  194. fParams(nullptr)
  195. {
  196. carla_debug("BridgePlugin::BridgePlugin(%p, %i, %s, %s)", engine, id, BinaryType2Str(btype), PluginType2Str(ptype));
  197. pData->osc.thread.setMode(CarlaPluginThread::PLUGIN_THREAD_BRIDGE);
  198. pData->hints |= PLUGIN_IS_BRIDGE;
  199. }
  200. ~BridgePlugin() override
  201. {
  202. carla_debug("BridgePlugin::~BridgePlugin()");
  203. pData->singleMutex.lock();
  204. pData->masterMutex.lock();
  205. if (pData->client != nullptr && pData->client->isActive())
  206. pData->client->deactivate();
  207. if (pData->active)
  208. {
  209. deactivate();
  210. pData->active = false;
  211. }
  212. if (pData->osc.thread.isRunning())
  213. {
  214. fShmControl.writeOpcode(kPluginBridgeOpcodeQuit);
  215. fShmControl.commitWrite();
  216. fShmControl.waitForServer();
  217. }
  218. if (pData->osc.data.target != nullptr)
  219. {
  220. osc_send_hide(pData->osc.data);
  221. osc_send_quit(pData->osc.data);
  222. }
  223. pData->osc.data.free();
  224. pData->osc.thread.stop(6000);
  225. if (fNeedsSemDestroy)
  226. {
  227. jackbridge_sem_destroy(&fShmControl.data->runServer);
  228. jackbridge_sem_destroy(&fShmControl.data->runClient);
  229. }
  230. fShmAudioPool.clear();
  231. fShmControl.clear();
  232. clearBuffers();
  233. //info.chunk.clear();
  234. }
  235. // -------------------------------------------------------------------
  236. // Information (base)
  237. BinaryType getBinaryType() const noexcept
  238. {
  239. return fBinaryType;
  240. }
  241. PluginType getType() const noexcept override
  242. {
  243. return fPluginType;
  244. }
  245. PluginCategory getCategory() const noexcept override
  246. {
  247. return fInfo.category;
  248. }
  249. long getUniqueId() const noexcept override
  250. {
  251. return fInfo.uniqueId;
  252. }
  253. // -------------------------------------------------------------------
  254. // Information (count)
  255. uint32_t getMidiInCount() const noexcept override
  256. {
  257. return fInfo.mIns;
  258. }
  259. uint32_t getMidiOutCount() const noexcept override
  260. {
  261. return fInfo.mOuts;
  262. }
  263. // -------------------------------------------------------------------
  264. // Information (current data)
  265. int32_t getChunkData(void** const dataPtr) const noexcept override
  266. {
  267. CARLA_ASSERT(pData->options & PLUGIN_OPTION_USE_CHUNKS);
  268. CARLA_ASSERT(dataPtr != nullptr);
  269. #if 0
  270. if (! info.chunk.isEmpty())
  271. {
  272. *dataPtr = info.chunk.data();
  273. return info.chunk.size();
  274. }
  275. #endif
  276. return 0;
  277. }
  278. // -------------------------------------------------------------------
  279. // Information (per-plugin data)
  280. unsigned int getOptionsAvailable() const noexcept override
  281. {
  282. unsigned int options = 0x0;
  283. options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  284. options |= PLUGIN_OPTION_USE_CHUNKS;
  285. options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  286. options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  287. options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  288. options |= PLUGIN_OPTION_SEND_PITCHBEND;
  289. options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  290. return options;
  291. }
  292. float getParameterValue(const uint32_t parameterId) const noexcept override
  293. {
  294. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, 0.0f);
  295. return fParams[parameterId].value;
  296. }
  297. void getLabel(char* const strBuf) const noexcept override
  298. {
  299. std::strncpy(strBuf, (const char*)fInfo.label, STR_MAX);
  300. }
  301. void getMaker(char* const strBuf) const noexcept override
  302. {
  303. std::strncpy(strBuf, (const char*)fInfo.maker, STR_MAX);
  304. }
  305. void getCopyright(char* const strBuf) const noexcept override
  306. {
  307. std::strncpy(strBuf, (const char*)fInfo.copyright, STR_MAX);
  308. }
  309. void getRealName(char* const strBuf) const noexcept override
  310. {
  311. std::strncpy(strBuf, (const char*)fInfo.name, STR_MAX);
  312. }
  313. void getParameterName(const uint32_t parameterId, char* const strBuf) const noexcept override
  314. {
  315. CARLA_ASSERT(parameterId < pData->param.count);
  316. std::strncpy(strBuf, (const char*)fParams[parameterId].name, STR_MAX);
  317. }
  318. void getParameterUnit(const uint32_t parameterId, char* const strBuf) const noexcept override
  319. {
  320. CARLA_ASSERT(parameterId < pData->param.count);
  321. std::strncpy(strBuf, (const char*)fParams[parameterId].unit, STR_MAX);
  322. }
  323. // -------------------------------------------------------------------
  324. // Set data (state)
  325. void prepareForSave() override
  326. {
  327. #if 0
  328. m_saved = false;
  329. osc_send_configure(&osc.data, CARLA_BRIDGE_MSG_SAVE_NOW, "");
  330. for (int i=0; i < 200; ++i)
  331. {
  332. if (m_saved)
  333. break;
  334. carla_msleep(50);
  335. }
  336. if (! m_saved)
  337. carla_stderr("BridgePlugin::prepareForSave() - Timeout while requesting save state");
  338. else
  339. carla_debug("BridgePlugin::prepareForSave() - success!");
  340. #endif
  341. }
  342. // -------------------------------------------------------------------
  343. // Set data (internal stuff)
  344. // nothing
  345. // -------------------------------------------------------------------
  346. // Set data (plugin-specific stuff)
  347. void setParameterValue(const uint32_t parameterId, const float value, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  348. {
  349. CARLA_ASSERT(parameterId < pData->param.count);
  350. const float fixedValue(pData->param.getFixedValue(parameterId, value));
  351. fParams[parameterId].value = fixedValue;
  352. const bool doLock(sendGui || sendOsc || sendCallback);
  353. if (doLock)
  354. pData->singleMutex.lock();
  355. fShmControl.writeOpcode(kPluginBridgeOpcodeSetParameter);
  356. fShmControl.writeInt(static_cast<int32_t>(parameterId));
  357. fShmControl.writeFloat(value);
  358. if (doLock)
  359. {
  360. fShmControl.commitWrite();
  361. pData->singleMutex.unlock();
  362. }
  363. CarlaPlugin::setParameterValue(parameterId, fixedValue, sendGui, sendOsc, sendCallback);
  364. }
  365. void setProgram(const int32_t index, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  366. {
  367. CARLA_SAFE_ASSERT_RETURN(index >= -1 && index < static_cast<int32_t>(pData->prog.count),);
  368. const bool doLock(sendGui || sendOsc || sendCallback);
  369. if (doLock)
  370. pData->singleMutex.lock();
  371. fShmControl.writeOpcode(kPluginBridgeOpcodeSetProgram);
  372. fShmControl.writeInt(index);
  373. if (doLock)
  374. {
  375. fShmControl.commitWrite();
  376. pData->singleMutex.unlock();
  377. }
  378. CarlaPlugin::setProgram(index, sendGui, sendOsc, sendCallback);
  379. }
  380. void setMidiProgram(const int32_t index, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  381. {
  382. CARLA_SAFE_ASSERT_RETURN(index >= -1 && index < static_cast<int32_t>(pData->midiprog.count),);
  383. const bool doLock(sendGui || sendOsc || sendCallback);
  384. if (doLock)
  385. pData->singleMutex.lock();
  386. fShmControl.writeOpcode(kPluginBridgeOpcodeSetMidiProgram);
  387. fShmControl.writeInt(index);
  388. if (doLock)
  389. {
  390. fShmControl.commitWrite();
  391. pData->singleMutex.unlock();
  392. }
  393. CarlaPlugin::setMidiProgram(index, sendGui, sendOsc, sendCallback);
  394. }
  395. #if 0
  396. void setCustomData(const char* const type, const char* const key, const char* const value, const bool sendGui) override
  397. {
  398. CARLA_ASSERT(type);
  399. CARLA_ASSERT(key);
  400. CARLA_ASSERT(value);
  401. if (sendGui)
  402. {
  403. // TODO - if type is chunk|binary, store it in a file and send path instead
  404. QString cData;
  405. cData = type;
  406. cData += "·";
  407. cData += key;
  408. cData += "·";
  409. cData += value;
  410. osc_send_configure(&osc.data, CARLA_BRIDGE_MSG_SET_CUSTOM, cData.toUtf8().constData());
  411. }
  412. CarlaPlugin::setCustomData(type, key, value, sendGui);
  413. }
  414. void setChunkData(const char* const stringData) override
  415. {
  416. CARLA_ASSERT(m_hints & PLUGIN_USES_CHUNKS);
  417. CARLA_ASSERT(stringData);
  418. QString filePath;
  419. filePath = QDir::tempPath();
  420. filePath += "/.CarlaChunk_";
  421. filePath += m_name;
  422. filePath = QDir::toNativeSeparators(filePath);
  423. QFile file(filePath);
  424. if (file.open(QIODevice::WriteOnly | QIODevice::Text))
  425. {
  426. QTextStream out(&file);
  427. out << stringData;
  428. file.close();
  429. osc_send_configure(&osc.data, CARLA_BRIDGE_MSG_SET_CHUNK, filePath.toUtf8().constData());
  430. }
  431. }
  432. #endif
  433. // -------------------------------------------------------------------
  434. // Set ui stuff
  435. void showCustomUI(const bool yesNo) override
  436. {
  437. if (yesNo)
  438. osc_send_show(pData->osc.data);
  439. else
  440. osc_send_hide(pData->osc.data);
  441. }
  442. void idle() override
  443. {
  444. if (! pData->osc.thread.isRunning())
  445. carla_stderr2("TESTING: Bridge has closed!");
  446. CarlaPlugin::idle();
  447. }
  448. // -------------------------------------------------------------------
  449. // Plugin state
  450. void reload() override
  451. {
  452. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  453. carla_debug("BridgePlugin::reload() - start");
  454. const EngineProcessMode processMode(pData->engine->getProccessMode());
  455. // Safely disable plugin for reload
  456. const ScopedDisabler sd(this);
  457. bool needsCtrlIn, needsCtrlOut;
  458. needsCtrlIn = needsCtrlOut = false;
  459. if (fInfo.aIns > 0)
  460. {
  461. pData->audioIn.createNew(fInfo.aIns);
  462. }
  463. if (fInfo.aOuts > 0)
  464. {
  465. pData->audioOut.createNew(fInfo.aOuts);
  466. needsCtrlIn = true;
  467. }
  468. if (fInfo.mIns > 0)
  469. needsCtrlIn = true;
  470. if (fInfo.mOuts > 0)
  471. needsCtrlOut = true;
  472. const uint portNameSize(pData->engine->getMaxPortNameSize());
  473. CarlaString portName;
  474. // Audio Ins
  475. for (uint32_t j=0; j < fInfo.aIns; ++j)
  476. {
  477. portName.clear();
  478. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  479. {
  480. portName = pData->name;
  481. portName += ":";
  482. }
  483. if (fInfo.aIns > 1)
  484. {
  485. portName += "input_";
  486. portName += CarlaString(j+1);
  487. }
  488. else
  489. portName += "input";
  490. portName.truncate(portNameSize);
  491. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true);
  492. pData->audioIn.ports[j].rindex = j;
  493. }
  494. // Audio Outs
  495. for (uint32_t j=0; j < fInfo.aOuts; ++j)
  496. {
  497. portName.clear();
  498. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  499. {
  500. portName = pData->name;
  501. portName += ":";
  502. }
  503. if (fInfo.aOuts > 1)
  504. {
  505. portName += "output_";
  506. portName += CarlaString(j+1);
  507. }
  508. else
  509. portName += "output";
  510. portName.truncate(portNameSize);
  511. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false);
  512. pData->audioOut.ports[j].rindex = j;
  513. }
  514. if (needsCtrlIn)
  515. {
  516. portName.clear();
  517. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  518. {
  519. portName = pData->name;
  520. portName += ":";
  521. }
  522. portName += "event-in";
  523. portName.truncate(portNameSize);
  524. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true);
  525. }
  526. if (needsCtrlOut)
  527. {
  528. portName.clear();
  529. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  530. {
  531. portName = pData->name;
  532. portName += ":";
  533. }
  534. portName += "event-out";
  535. portName.truncate(portNameSize);
  536. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false);
  537. }
  538. bufferSizeChanged(pData->engine->getBufferSize());
  539. reloadPrograms(true);
  540. carla_debug("BridgePlugin::reload() - end");
  541. }
  542. // -------------------------------------------------------------------
  543. // Plugin processing
  544. void activate() noexcept override
  545. {
  546. // already locked before
  547. fShmControl.writeOpcode(kPluginBridgeOpcodeSetParameter);
  548. fShmControl.writeInt(PARAMETER_ACTIVE);
  549. fShmControl.writeFloat(1.0f);
  550. fShmControl.commitWrite();
  551. try {
  552. waitForServer();
  553. } catch(...) {}
  554. }
  555. void deactivate() noexcept override
  556. {
  557. // already locked before
  558. fShmControl.writeOpcode(kPluginBridgeOpcodeSetParameter);
  559. fShmControl.writeInt(PARAMETER_ACTIVE);
  560. fShmControl.writeFloat(0.0f);
  561. fShmControl.commitWrite();
  562. try {
  563. waitForServer();
  564. } catch(...) {}
  565. }
  566. void process(float** const inBuffer, float** const outBuffer, const uint32_t frames) override
  567. {
  568. // --------------------------------------------------------------------------------------------------------
  569. // Check if active
  570. if (! pData->active)
  571. {
  572. // disable any output sound
  573. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  574. FLOAT_CLEAR(outBuffer[i], frames);
  575. return;
  576. }
  577. // --------------------------------------------------------------------------------------------------------
  578. // Check if needs reset
  579. if (pData->needsReset)
  580. {
  581. // TODO
  582. pData->needsReset = false;
  583. }
  584. // --------------------------------------------------------------------------------------------------------
  585. // Event Input
  586. if (pData->event.portIn != nullptr)
  587. {
  588. // ----------------------------------------------------------------------------------------------------
  589. // MIDI Input (External)
  590. if (pData->extNotes.mutex.tryLock())
  591. {
  592. for (; ! pData->extNotes.data.isEmpty();)
  593. {
  594. const ExternalMidiNote& note(pData->extNotes.data.getFirst(true));
  595. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  596. char data1, data2, data3;
  597. data1 = static_cast<char>(note.channel + (note.velo > 0) ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF);
  598. data2 = static_cast<char>(note.note);
  599. data3 = static_cast<char>(note.velo);
  600. fShmControl.writeOpcode(kPluginBridgeOpcodeMidiEvent);
  601. fShmControl.writeLong(0);
  602. fShmControl.writeInt(3);
  603. fShmControl.writeChar(data1);
  604. fShmControl.writeChar(data2);
  605. fShmControl.writeChar(data3);
  606. }
  607. pData->extNotes.mutex.unlock();
  608. } // End of MIDI Input (External)
  609. // ----------------------------------------------------------------------------------------------------
  610. // Event Input (System)
  611. bool allNotesOffSent = false;
  612. uint32_t numEvents = pData->event.portIn->getEventCount();
  613. uint32_t nextBankId;
  614. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0)
  615. nextBankId = pData->midiprog.data[pData->midiprog.current].bank;
  616. else
  617. nextBankId = 0;
  618. for (uint32_t i=0; i < numEvents; ++i)
  619. {
  620. const EngineEvent& event(pData->event.portIn->getEvent(i));
  621. // Control change
  622. switch (event.type)
  623. {
  624. case kEngineEventTypeNull:
  625. break;
  626. case kEngineEventTypeControl: {
  627. const EngineControlEvent& ctrlEvent = event.ctrl;
  628. switch (ctrlEvent.type)
  629. {
  630. case kEngineControlEventTypeNull:
  631. break;
  632. case kEngineControlEventTypeParameter:
  633. {
  634. // Control backend stuff
  635. if (event.channel == pData->ctrlChannel)
  636. {
  637. float value;
  638. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  639. {
  640. value = ctrlEvent.value;
  641. setDryWet(value, false, false);
  642. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  643. break;
  644. }
  645. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  646. {
  647. value = ctrlEvent.value*127.0f/100.0f;
  648. setVolume(value, false, false);
  649. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  650. break;
  651. }
  652. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  653. {
  654. float left, right;
  655. value = ctrlEvent.value/0.5f - 1.0f;
  656. if (value < 0.0f)
  657. {
  658. left = -1.0f;
  659. right = (value*2.0f)+1.0f;
  660. }
  661. else if (value > 0.0f)
  662. {
  663. left = (value*2.0f)-1.0f;
  664. right = 1.0f;
  665. }
  666. else
  667. {
  668. left = -1.0f;
  669. right = 1.0f;
  670. }
  671. setBalanceLeft(left, false, false);
  672. setBalanceRight(right, false, false);
  673. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  674. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  675. break;
  676. }
  677. }
  678. // Control plugin parameters
  679. uint32_t k;
  680. for (k=0; k < pData->param.count; ++k)
  681. {
  682. if (pData->param.data[k].midiChannel != event.channel)
  683. continue;
  684. if (pData->param.data[k].midiCC != ctrlEvent.param)
  685. continue;
  686. if (pData->param.data[k].type != PARAMETER_INPUT)
  687. continue;
  688. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  689. continue;
  690. float value;
  691. if (pData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  692. {
  693. value = (ctrlEvent.value < 0.5f) ? pData->param.ranges[k].min : pData->param.ranges[k].max;
  694. }
  695. else
  696. {
  697. value = pData->param.ranges[k].getUnnormalizedValue(ctrlEvent.value);
  698. if (pData->param.data[k].hints & PARAMETER_IS_INTEGER)
  699. value = std::rint(value);
  700. }
  701. setParameterValue(k, value, false, false, false);
  702. pData->postponeRtEvent(kPluginPostRtEventParameterChange, static_cast<int32_t>(k), 0, value);
  703. break;
  704. }
  705. // check if event is already handled
  706. if (k != pData->param.count)
  707. break;
  708. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param <= 0x5F)
  709. {
  710. fShmControl.writeOpcode(kPluginBridgeOpcodeMidiEvent);
  711. fShmControl.writeLong(event.time);
  712. fShmControl.writeInt(3);
  713. fShmControl.writeChar(static_cast<char>(MIDI_STATUS_CONTROL_CHANGE + event.channel));
  714. fShmControl.writeChar(static_cast<char>(ctrlEvent.param));
  715. fShmControl.writeChar(char(ctrlEvent.value*127.0f));
  716. }
  717. break;
  718. } // case kEngineControlEventTypeParameter
  719. case kEngineControlEventTypeMidiBank:
  720. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  721. nextBankId = ctrlEvent.param;
  722. break;
  723. case kEngineControlEventTypeMidiProgram:
  724. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  725. {
  726. const uint32_t nextProgramId(ctrlEvent.param);
  727. if (pData->midiprog.count > 0)
  728. {
  729. for (uint32_t k=0; k < pData->midiprog.count; ++k)
  730. {
  731. if (pData->midiprog.data[k].bank == nextBankId && pData->midiprog.data[k].program == nextProgramId)
  732. {
  733. const int32_t index(static_cast<int32_t>(k));
  734. setMidiProgram(index, false, false, false);
  735. pData->postponeRtEvent(kPluginPostRtEventMidiProgramChange, index, 0, 0.0f);
  736. break;
  737. }
  738. }
  739. }
  740. else
  741. {
  742. }
  743. }
  744. break;
  745. case kEngineControlEventTypeAllSoundOff:
  746. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  747. {
  748. // TODO
  749. }
  750. break;
  751. case kEngineControlEventTypeAllNotesOff:
  752. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  753. {
  754. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  755. {
  756. allNotesOffSent = true;
  757. sendMidiAllNotesOffToCallback();
  758. }
  759. // TODO
  760. }
  761. break;
  762. } // switch (ctrlEvent.type)
  763. break;
  764. } // case kEngineEventTypeControl
  765. case kEngineEventTypeMidi:
  766. {
  767. const EngineMidiEvent& midiEvent(event.midi);
  768. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiEvent.data));
  769. uint8_t channel = event.channel;
  770. if (MIDI_IS_STATUS_NOTE_ON(status) && midiEvent.data[2] == 0)
  771. status = MIDI_STATUS_NOTE_OFF;
  772. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  773. continue;
  774. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  775. continue;
  776. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  777. continue;
  778. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  779. continue;
  780. char data[EngineMidiEvent::kDataSize];
  781. data[0] = static_cast<char>(status + channel);
  782. for (uint8_t j=0; j < EngineMidiEvent::kDataSize; ++i)
  783. data[j] = static_cast<char>(midiEvent.data[j]);
  784. fShmControl.writeOpcode(kPluginBridgeOpcodeMidiEvent);
  785. fShmControl.writeLong(event.time);
  786. fShmControl.writeInt(midiEvent.size);
  787. for (uint8_t j=0; j < midiEvent.size && j < 4; ++j)
  788. fShmControl.writeChar(data[j]);
  789. if (status == MIDI_STATUS_NOTE_ON)
  790. pData->postponeRtEvent(kPluginPostRtEventNoteOn, channel, midiEvent.data[1], midiEvent.data[2]);
  791. else if (status == MIDI_STATUS_NOTE_OFF)
  792. pData->postponeRtEvent(kPluginPostRtEventNoteOff, channel, midiEvent.data[1], 0.0f);
  793. break;
  794. }
  795. }
  796. }
  797. pData->postRtEvents.trySplice();
  798. } // End of Event Input
  799. processSingle(inBuffer, outBuffer, frames);
  800. }
  801. bool processSingle(float** const inBuffer, float** const outBuffer, const uint32_t frames)
  802. {
  803. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  804. if (pData->audioIn.count > 0)
  805. {
  806. CARLA_SAFE_ASSERT_RETURN(inBuffer != nullptr, false);
  807. }
  808. if (pData->audioOut.count > 0)
  809. {
  810. CARLA_SAFE_ASSERT_RETURN(outBuffer != nullptr, false);
  811. }
  812. // --------------------------------------------------------------------------------------------------------
  813. // Try lock, silence otherwise
  814. if (pData->engine->isOffline())
  815. {
  816. pData->singleMutex.lock();
  817. }
  818. else if (! pData->singleMutex.tryLock())
  819. {
  820. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  821. FLOAT_CLEAR(outBuffer[i], frames);
  822. return false;
  823. }
  824. // --------------------------------------------------------------------------------------------------------
  825. // Reset audio buffers
  826. for (uint32_t i=0; i < fInfo.aIns; ++i)
  827. FLOAT_COPY(fShmAudioPool.data + (i * frames), inBuffer[i], frames);
  828. // --------------------------------------------------------------------------------------------------------
  829. // Run plugin
  830. fShmControl.writeOpcode(kPluginBridgeOpcodeProcess);
  831. fShmControl.commitWrite();
  832. if (! waitForServer())
  833. {
  834. pData->singleMutex.unlock();
  835. return true;
  836. }
  837. for (uint32_t i=0; i < fInfo.aOuts; ++i)
  838. FLOAT_COPY(outBuffer[i], fShmAudioPool.data + ((i + fInfo.aIns) * frames), frames);
  839. // --------------------------------------------------------------------------------------------------------
  840. // Post-processing (dry/wet, volume and balance)
  841. {
  842. const bool doVolume = (pData->hints & PLUGIN_CAN_VOLUME) != 0 && pData->postProc.volume != 1.0f;
  843. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && pData->postProc.dryWet != 1.0f;
  844. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && (pData->postProc.balanceLeft != -1.0f || pData->postProc.balanceRight != 1.0f);
  845. bool isPair;
  846. float bufValue, oldBufLeft[doBalance ? frames : 1];
  847. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  848. {
  849. // Dry/Wet
  850. if (doDryWet)
  851. {
  852. for (uint32_t k=0; k < frames; ++k)
  853. {
  854. bufValue = inBuffer[(pData->audioIn.count == 1) ? 0 : i][k];
  855. outBuffer[i][k] = (outBuffer[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  856. }
  857. }
  858. // Balance
  859. if (doBalance)
  860. {
  861. isPair = (i % 2 == 0);
  862. if (isPair)
  863. {
  864. CARLA_ASSERT(i+1 < pData->audioOut.count);
  865. FLOAT_COPY(oldBufLeft, outBuffer[i], frames);
  866. }
  867. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  868. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  869. for (uint32_t k=0; k < frames; ++k)
  870. {
  871. if (isPair)
  872. {
  873. // left
  874. outBuffer[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  875. outBuffer[i][k] += outBuffer[i+1][k] * (1.0f - balRangeR);
  876. }
  877. else
  878. {
  879. // right
  880. outBuffer[i][k] = outBuffer[i][k] * balRangeR;
  881. outBuffer[i][k] += oldBufLeft[k] * balRangeL;
  882. }
  883. }
  884. }
  885. // Volume (and buffer copy)
  886. if (doVolume)
  887. {
  888. for (uint32_t k=0; k < frames; ++k)
  889. outBuffer[i][k] *= pData->postProc.volume;
  890. }
  891. }
  892. } // End of Post-processing
  893. // --------------------------------------------------------------------------------------------------------
  894. pData->singleMutex.unlock();
  895. return true;
  896. }
  897. void bufferSizeChanged(const uint32_t newBufferSize) override
  898. {
  899. resizeAudioPool(newBufferSize);
  900. fShmControl.writeOpcode(kPluginBridgeOpcodeSetBufferSize);
  901. fShmControl.writeInt(static_cast<int32_t>(newBufferSize));
  902. fShmControl.commitWrite();
  903. }
  904. void sampleRateChanged(const double newSampleRate) override
  905. {
  906. fShmControl.writeOpcode(kPluginBridgeOpcodeSetSampleRate);
  907. fShmControl.writeFloat(static_cast<float>(newSampleRate));
  908. fShmControl.commitWrite();
  909. }
  910. // -------------------------------------------------------------------
  911. // Plugin buffers
  912. void clearBuffers() override
  913. {
  914. if (fParams != nullptr)
  915. {
  916. delete[] fParams;
  917. fParams = nullptr;
  918. }
  919. CarlaPlugin::clearBuffers();
  920. }
  921. // -------------------------------------------------------------------
  922. // Post-poned UI Stuff
  923. // nothing
  924. // -------------------------------------------------------------------
  925. int setOscPluginBridgeInfo(const PluginBridgeInfoType infoType, const int argc, const lo_arg* const* const argv, const char* const types)
  926. {
  927. carla_debug("setOscPluginBridgeInfo(%s, %i, %p, \"%s\")", PluginBridgeInfoType2str(infoType), argc, argv, types);
  928. switch (infoType)
  929. {
  930. case kPluginBridgeNull:
  931. break;
  932. case kPluginBridgePluginInfo1: {
  933. CARLA_BRIDGE_CHECK_OSC_TYPES(3, "iih");
  934. const int32_t category = argv[0]->i;
  935. const int32_t hints = argv[1]->i;
  936. const int64_t uniqueId = argv[2]->h;
  937. CARLA_SAFE_ASSERT_BREAK(category >= 0);
  938. CARLA_SAFE_ASSERT_BREAK(hints >= 0);
  939. pData->hints = static_cast<uint>(hints);
  940. pData->hints |= PLUGIN_IS_BRIDGE;
  941. fInfo.category = static_cast<PluginCategory>(category);
  942. fInfo.uniqueId = static_cast<long>(uniqueId);
  943. break;
  944. }
  945. case kPluginBridgePluginInfo2: {
  946. CARLA_BRIDGE_CHECK_OSC_TYPES(4, "ssss");
  947. const char* const realName = (const char*)&argv[0]->s;
  948. const char* const label = (const char*)&argv[1]->s;
  949. const char* const maker = (const char*)&argv[2]->s;
  950. const char* const copyright = (const char*)&argv[3]->s;
  951. CARLA_SAFE_ASSERT_BREAK(realName != nullptr);
  952. CARLA_SAFE_ASSERT_BREAK(label != nullptr);
  953. CARLA_SAFE_ASSERT_BREAK(maker != nullptr);
  954. CARLA_SAFE_ASSERT_BREAK(copyright != nullptr);
  955. fInfo.name = realName;
  956. fInfo.label = label;
  957. fInfo.maker = maker;
  958. fInfo.copyright = copyright;
  959. if (pData->name == nullptr)
  960. pData->name = carla_strdup(realName);
  961. break;
  962. }
  963. case kPluginBridgeAudioCount: {
  964. CARLA_BRIDGE_CHECK_OSC_TYPES(2, "ii");
  965. const int32_t ins = argv[0]->i;
  966. const int32_t outs = argv[1]->i;
  967. CARLA_SAFE_ASSERT_BREAK(ins >= 0);
  968. CARLA_SAFE_ASSERT_BREAK(outs >= 0);
  969. fInfo.aIns = static_cast<uint32_t>(ins);
  970. fInfo.aOuts = static_cast<uint32_t>(outs);
  971. break;
  972. }
  973. case kPluginBridgeMidiCount: {
  974. CARLA_BRIDGE_CHECK_OSC_TYPES(2, "ii");
  975. const int32_t ins = argv[0]->i;
  976. const int32_t outs = argv[1]->i;
  977. CARLA_SAFE_ASSERT_BREAK(ins >= 0);
  978. CARLA_SAFE_ASSERT_BREAK(outs >= 0);
  979. fInfo.mIns = static_cast<uint32_t>(ins);
  980. fInfo.mOuts = static_cast<uint32_t>(outs);
  981. break;
  982. }
  983. case kPluginBridgeParameterCount: {
  984. CARLA_BRIDGE_CHECK_OSC_TYPES(2, "ii");
  985. const int32_t ins = argv[0]->i;
  986. const int32_t outs = argv[1]->i;
  987. CARLA_SAFE_ASSERT_BREAK(ins >= 0);
  988. CARLA_SAFE_ASSERT_BREAK(outs >= 0);
  989. // delete old data
  990. pData->param.clear();
  991. if (fParams != nullptr)
  992. {
  993. delete[] fParams;
  994. fParams = nullptr;
  995. }
  996. CARLA_SAFE_ASSERT_INT2(ins+outs < static_cast<int32_t>(pData->engine->getOptions().maxParameters), ins+outs, pData->engine->getOptions().maxParameters);
  997. const uint32_t count(static_cast<uint32_t>(carla_min<int32_t>(ins+outs, static_cast<int32_t>(pData->engine->getOptions().maxParameters), 0)));
  998. if (count > 0)
  999. {
  1000. pData->param.createNew(count, false);
  1001. fParams = new BridgeParamInfo[count];
  1002. }
  1003. break;
  1004. }
  1005. case kPluginBridgeProgramCount: {
  1006. CARLA_BRIDGE_CHECK_OSC_TYPES(1, "i");
  1007. const int32_t count = argv[0]->i;
  1008. CARLA_SAFE_ASSERT_BREAK(count >= 0);
  1009. pData->prog.clear();
  1010. if (count > 0)
  1011. pData->prog.createNew(static_cast<uint32_t>(count));
  1012. break;
  1013. }
  1014. case kPluginBridgeMidiProgramCount: {
  1015. CARLA_BRIDGE_CHECK_OSC_TYPES(1, "i");
  1016. const int32_t count = argv[0]->i;
  1017. CARLA_SAFE_ASSERT_BREAK(count >= 0);
  1018. pData->midiprog.clear();
  1019. if (count > 0)
  1020. pData->midiprog.createNew(static_cast<uint32_t>(count));
  1021. break;
  1022. }
  1023. case kPluginBridgeParameterData:
  1024. {
  1025. CARLA_BRIDGE_CHECK_OSC_TYPES(6, "iiiiss");
  1026. const int32_t index = argv[0]->i;
  1027. const int32_t rindex = argv[1]->i;
  1028. const int32_t type = argv[2]->i;
  1029. const int32_t hints = argv[3]->i;
  1030. const char* const name = (const char*)&argv[4]->s;
  1031. const char* const unit = (const char*)&argv[5]->s;
  1032. CARLA_SAFE_ASSERT_BREAK(index >= 0);
  1033. CARLA_SAFE_ASSERT_BREAK(rindex >= 0);
  1034. CARLA_SAFE_ASSERT_BREAK(type >= 0);
  1035. CARLA_SAFE_ASSERT_BREAK(hints >= 0);
  1036. CARLA_SAFE_ASSERT_BREAK(name != nullptr);
  1037. CARLA_SAFE_ASSERT_BREAK(unit != nullptr);
  1038. CARLA_SAFE_ASSERT_INT2(index < static_cast<int32_t>(pData->param.count), index, pData->param.count);
  1039. if (index < static_cast<int32_t>(pData->param.count))
  1040. {
  1041. pData->param.data[index].index = index;
  1042. pData->param.data[index].rindex = rindex;
  1043. pData->param.data[index].hints = static_cast<uint>(hints);
  1044. fParams[index].name = name;
  1045. fParams[index].unit = unit;
  1046. }
  1047. break;
  1048. }
  1049. case kPluginBridgeParameterRanges1:
  1050. {
  1051. CARLA_BRIDGE_CHECK_OSC_TYPES(4, "ifff");
  1052. const int32_t index = argv[0]->i;
  1053. const float def = argv[1]->f;
  1054. const float min = argv[2]->f;
  1055. const float max = argv[3]->f;
  1056. CARLA_SAFE_ASSERT_BREAK(index >= 0);
  1057. CARLA_SAFE_ASSERT_BREAK(min < max);
  1058. CARLA_SAFE_ASSERT_BREAK(def >= min);
  1059. CARLA_SAFE_ASSERT_BREAK(def <= max);
  1060. CARLA_SAFE_ASSERT_INT2(index < static_cast<int32_t>(pData->param.count), index, pData->param.count);
  1061. if (index < static_cast<int32_t>(pData->param.count))
  1062. {
  1063. pData->param.ranges[index].def = def;
  1064. pData->param.ranges[index].min = min;
  1065. pData->param.ranges[index].max = max;
  1066. }
  1067. break;
  1068. }
  1069. case kPluginBridgeParameterRanges2:
  1070. {
  1071. CARLA_BRIDGE_CHECK_OSC_TYPES(4, "ifff");
  1072. const int32_t index = argv[0]->i;
  1073. const float step = argv[1]->f;
  1074. const float stepSmall = argv[2]->f;
  1075. const float stepLarge = argv[3]->f;
  1076. CARLA_SAFE_ASSERT_BREAK(index >= 0);
  1077. CARLA_SAFE_ASSERT_INT2(index < static_cast<int32_t>(pData->param.count), index, pData->param.count);
  1078. if (index < static_cast<int32_t>(pData->param.count))
  1079. {
  1080. pData->param.ranges[index].step = step;
  1081. pData->param.ranges[index].stepSmall = stepSmall;
  1082. pData->param.ranges[index].stepLarge = stepLarge;
  1083. }
  1084. break;
  1085. }
  1086. case kPluginBridgeParameterMidiCC: {
  1087. CARLA_BRIDGE_CHECK_OSC_TYPES(2, "ii");
  1088. const int32_t index = argv[0]->i;
  1089. const int32_t cc = argv[1]->i;
  1090. CARLA_SAFE_ASSERT_BREAK(index >= 0);
  1091. CARLA_SAFE_ASSERT_BREAK(cc >= -1 && cc < 0x5F);
  1092. CARLA_SAFE_ASSERT_INT2(index < static_cast<int32_t>(pData->param.count), index, pData->param.count);
  1093. if (index < static_cast<int32_t>(pData->param.count))
  1094. pData->param.data[index].midiCC = static_cast<int16_t>(cc);
  1095. break;
  1096. }
  1097. case kPluginBridgeParameterMidiChannel: {
  1098. CARLA_BRIDGE_CHECK_OSC_TYPES(2, "ii");
  1099. const int32_t index = argv[0]->i;
  1100. const int32_t channel = argv[0]->i;
  1101. CARLA_SAFE_ASSERT_BREAK(index >= 0);
  1102. CARLA_SAFE_ASSERT_BREAK(channel >= 0 && channel < MAX_MIDI_CHANNELS);
  1103. CARLA_SAFE_ASSERT_INT2(index < static_cast<int32_t>(pData->param.count), index, pData->param.count);
  1104. if (index < static_cast<int32_t>(pData->param.count))
  1105. pData->param.data[index].midiChannel = static_cast<uint8_t>(channel);
  1106. break;
  1107. }
  1108. case kPluginBridgeParameterValue:
  1109. {
  1110. CARLA_BRIDGE_CHECK_OSC_TYPES(2, "if");
  1111. const int32_t index = argv[0]->i;
  1112. const float value = argv[1]->f;
  1113. CARLA_SAFE_ASSERT_BREAK(index >= 0);
  1114. CARLA_SAFE_ASSERT_INT2(index < static_cast<int32_t>(pData->param.count), index, pData->param.count);
  1115. if (index < static_cast<int32_t>(pData->param.count))
  1116. {
  1117. const uint32_t uindex(static_cast<uint32_t>(index));
  1118. const float fixedValue(pData->param.getFixedValue(uindex, value));
  1119. fParams[uindex].value = fixedValue;
  1120. CarlaPlugin::setParameterValue(uindex, fixedValue, false, true, true);
  1121. }
  1122. break;
  1123. }
  1124. case kPluginBridgeDefaultValue:
  1125. {
  1126. CARLA_BRIDGE_CHECK_OSC_TYPES(2, "if");
  1127. const int32_t index = argv[0]->i;
  1128. const float value = argv[1]->f;
  1129. CARLA_SAFE_ASSERT_BREAK(index >= 0);
  1130. CARLA_SAFE_ASSERT_INT2(index < static_cast<int32_t>(pData->param.count), index, pData->param.count);
  1131. if (index < static_cast<int32_t>(pData->param.count))
  1132. pData->param.ranges[index].def = value;
  1133. break;
  1134. }
  1135. case kPluginBridgeCurrentProgram: {
  1136. CARLA_BRIDGE_CHECK_OSC_TYPES(1, "i");
  1137. const int32_t index = argv[0]->i;
  1138. CARLA_SAFE_ASSERT_BREAK(index >= -1);
  1139. CARLA_SAFE_ASSERT_INT2(index < static_cast<int32_t>(pData->prog.count), index, pData->prog.count);
  1140. CarlaPlugin::setProgram(index, false, true, true);
  1141. break;
  1142. }
  1143. case kPluginBridgeCurrentMidiProgram: {
  1144. CARLA_BRIDGE_CHECK_OSC_TYPES(1, "i");
  1145. const int32_t index = argv[0]->i;
  1146. CARLA_SAFE_ASSERT_BREAK(index >= -1);
  1147. CARLA_SAFE_ASSERT_INT2(index < static_cast<int32_t>(pData->midiprog.count), index, pData->midiprog.count);
  1148. CarlaPlugin::setMidiProgram(index, false, true, true);
  1149. break;
  1150. }
  1151. case kPluginBridgeProgramName: {
  1152. CARLA_BRIDGE_CHECK_OSC_TYPES(2, "is");
  1153. const int32_t index = argv[0]->i;
  1154. const char* const name = (const char*)&argv[1]->s;
  1155. CARLA_SAFE_ASSERT_BREAK(index >= 0);
  1156. CARLA_SAFE_ASSERT_BREAK(name != nullptr);
  1157. CARLA_SAFE_ASSERT_INT2(index < static_cast<int32_t>(pData->prog.count), index, pData->prog.count);
  1158. if (index < static_cast<int32_t>(pData->prog.count))
  1159. {
  1160. if (pData->prog.names[index] != nullptr)
  1161. delete[] pData->prog.names[index];
  1162. pData->prog.names[index] = carla_strdup(name);
  1163. }
  1164. break;
  1165. }
  1166. case kPluginBridgeMidiProgramData: {
  1167. CARLA_BRIDGE_CHECK_OSC_TYPES(4, "iiis");
  1168. const int32_t index = argv[0]->i;
  1169. const int32_t bank = argv[1]->i;
  1170. const int32_t program = argv[2]->i;
  1171. const char* const name = (const char*)&argv[3]->s;
  1172. CARLA_SAFE_ASSERT_BREAK(index >= 0);
  1173. CARLA_SAFE_ASSERT_BREAK(bank >= 0);
  1174. CARLA_SAFE_ASSERT_BREAK(program >= 0);
  1175. CARLA_SAFE_ASSERT_BREAK(name != nullptr);
  1176. CARLA_SAFE_ASSERT_INT2(index < static_cast<int32_t>(pData->midiprog.count), index, pData->midiprog.count);
  1177. if (index < static_cast<int32_t>(pData->midiprog.count))
  1178. {
  1179. if (pData->midiprog.data[index].name != nullptr)
  1180. delete[] pData->midiprog.data[index].name;
  1181. pData->midiprog.data[index].bank = static_cast<uint32_t>(bank);
  1182. pData->midiprog.data[index].program = static_cast<uint32_t>(program);
  1183. pData->midiprog.data[index].name = carla_strdup(name);
  1184. }
  1185. break;
  1186. }
  1187. case kPluginBridgeConfigure: {
  1188. CARLA_BRIDGE_CHECK_OSC_TYPES(2, "ss");
  1189. const char* const key = (const char*)&argv[0]->s;
  1190. const char* const value = (const char*)&argv[1]->s;
  1191. CARLA_SAFE_ASSERT_BREAK(key != nullptr);
  1192. CARLA_SAFE_ASSERT_BREAK(value != nullptr);
  1193. if (std::strcmp(key, CARLA_BRIDGE_MSG_HIDE_GUI) == 0)
  1194. pData->engine->callback(ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, 0, 0, 0.0f, nullptr);
  1195. else if (std::strcmp(key, CARLA_BRIDGE_MSG_SAVED) == 0)
  1196. fSaved = true;
  1197. break;
  1198. }
  1199. case kPluginBridgeSetCustomData: {
  1200. CARLA_BRIDGE_CHECK_OSC_TYPES(3, "sss");
  1201. const char* const type = (const char*)&argv[0]->s;
  1202. const char* const key = (const char*)&argv[1]->s;
  1203. const char* const value = (const char*)&argv[2]->s;
  1204. CARLA_SAFE_ASSERT_BREAK(type != nullptr);
  1205. CARLA_SAFE_ASSERT_BREAK(key != nullptr);
  1206. CARLA_SAFE_ASSERT_BREAK(value != nullptr);
  1207. CarlaPlugin::setCustomData(type, key, value, false);
  1208. break;
  1209. }
  1210. case kPluginBridgeSetChunkData: {
  1211. CARLA_BRIDGE_CHECK_OSC_TYPES(1, "s");
  1212. #if 0
  1213. const char* const chunkFileChar = (const char*)&argv[0]->s;
  1214. CARLA_ASSERT(chunkFileChar);
  1215. QString chunkFileStr(chunkFileChar);
  1216. #ifndef CARLA_OS_WIN
  1217. // Using Wine, fix temp dir
  1218. if (m_binary == BINARY_WIN32 || m_binary == BINARY_WIN64)
  1219. {
  1220. // Get WINEPREFIX
  1221. QString wineDir;
  1222. if (const char* const WINEPREFIX = getenv("WINEPREFIX"))
  1223. wineDir = QString(WINEPREFIX);
  1224. else
  1225. wineDir = QDir::homePath() + "/.wine";
  1226. QStringList chunkFileStrSplit1 = chunkFileStr.split(":/");
  1227. QStringList chunkFileStrSplit2 = chunkFileStrSplit1.at(1).split("\\");
  1228. QString wineDrive = chunkFileStrSplit1.at(0).toLower();
  1229. QString wineTMP = chunkFileStrSplit2.at(0);
  1230. QString baseName = chunkFileStrSplit2.at(1);
  1231. chunkFileStr = wineDir;
  1232. chunkFileStr += "/drive_";
  1233. chunkFileStr += wineDrive;
  1234. chunkFileStr += "/";
  1235. chunkFileStr += wineTMP;
  1236. chunkFileStr += "/";
  1237. chunkFileStr += baseName;
  1238. chunkFileStr = QDir::toNativeSeparators(chunkFileStr);
  1239. }
  1240. #endif
  1241. QFile chunkFile(chunkFileStr);
  1242. if (chunkFile.open(QIODevice::ReadOnly))
  1243. {
  1244. info.chunk = chunkFile.readAll();
  1245. chunkFile.close();
  1246. chunkFile.remove();
  1247. }
  1248. #endif
  1249. break;
  1250. }
  1251. case kPluginBridgeUpdate:
  1252. fInitiated = true;
  1253. break;
  1254. case kPluginBridgeError: {
  1255. CARLA_BRIDGE_CHECK_OSC_TYPES(1, "s");
  1256. const char* const error = (const char*)&argv[0]->s;
  1257. CARLA_ASSERT(error != nullptr);
  1258. pData->engine->setLastError(error);
  1259. fInitError = true;
  1260. fInitiated = true;
  1261. break;
  1262. }
  1263. }
  1264. return 0;
  1265. }
  1266. // -------------------------------------------------------------------
  1267. const void* getExtraStuff() const noexcept override
  1268. {
  1269. return fBridgeBinary.isNotEmpty() ? fBridgeBinary.getBuffer() : nullptr;
  1270. }
  1271. bool init(const char* const filename, const char* const name, const char* const label, const char* const bridgeBinary)
  1272. {
  1273. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  1274. // ---------------------------------------------------------------
  1275. // first checks
  1276. if (pData->client != nullptr)
  1277. {
  1278. pData->engine->setLastError("Plugin client is already registered");
  1279. return false;
  1280. }
  1281. // ---------------------------------------------------------------
  1282. // set info
  1283. if (name != nullptr && name[0] != '\0')
  1284. pData->name = pData->engine->getUniquePluginName(name);
  1285. pData->filename = carla_strdup(filename);
  1286. fBridgeBinary = bridgeBinary;
  1287. // ---------------------------------------------------------------
  1288. // SHM Audio Pool
  1289. {
  1290. char tmpFileBase[60];
  1291. std::srand(static_cast<uint>(std::time(nullptr)));
  1292. std::sprintf(tmpFileBase, "/carla-bridge_shm_XXXXXX");
  1293. fShmAudioPool.shm = shm_mkstemp(tmpFileBase);
  1294. if (! carla_is_shm_valid(fShmAudioPool.shm))
  1295. {
  1296. carla_stdout("Failed to open or create shared memory file #1");
  1297. return false;
  1298. }
  1299. fShmAudioPool.filename = tmpFileBase;
  1300. }
  1301. // ---------------------------------------------------------------
  1302. // SHM Control
  1303. {
  1304. char tmpFileBase[60];
  1305. std::sprintf(tmpFileBase, "/carla-bridge_shc_XXXXXX");
  1306. fShmControl.shm = shm_mkstemp(tmpFileBase);
  1307. if (! carla_is_shm_valid(fShmControl.shm))
  1308. {
  1309. carla_stdout("Failed to open or create shared memory file #2");
  1310. // clear
  1311. carla_shm_close(fShmAudioPool.shm);
  1312. return false;
  1313. }
  1314. fShmControl.filename = tmpFileBase;
  1315. if (! fShmControl.mapData())
  1316. {
  1317. carla_stdout("Failed to mmap shared memory file");
  1318. // clear
  1319. carla_shm_close(fShmControl.shm);
  1320. carla_shm_close(fShmAudioPool.shm);
  1321. return false;
  1322. }
  1323. CARLA_ASSERT(fShmControl.data != nullptr);
  1324. if (! jackbridge_sem_init(&fShmControl.data->runServer))
  1325. {
  1326. carla_stdout("Failed to initialize shared memory semaphore #1");
  1327. // clear
  1328. fShmControl.unmapData();
  1329. carla_shm_close(fShmControl.shm);
  1330. carla_shm_close(fShmAudioPool.shm);
  1331. return false;
  1332. }
  1333. if (! jackbridge_sem_init(&fShmControl.data->runClient))
  1334. {
  1335. carla_stdout("Failed to initialize shared memory semaphore #2");
  1336. // clear
  1337. jackbridge_sem_destroy(&fShmControl.data->runServer);
  1338. fShmControl.unmapData();
  1339. carla_shm_close(fShmControl.shm);
  1340. carla_shm_close(fShmAudioPool.shm);
  1341. return false;
  1342. }
  1343. fNeedsSemDestroy = true;
  1344. }
  1345. // initial values
  1346. fShmControl.writeOpcode(kPluginBridgeOpcodeSetBufferSize);
  1347. fShmControl.writeInt(static_cast<int32_t>(pData->engine->getBufferSize()));
  1348. fShmControl.writeOpcode(kPluginBridgeOpcodeSetSampleRate);
  1349. fShmControl.writeFloat(float(pData->engine->getSampleRate()));
  1350. fShmControl.commitWrite();
  1351. // register plugin now so we can receive OSC (and wait for it)
  1352. pData->hints |= PLUGIN_IS_BRIDGE;
  1353. pData->engine->registerEnginePlugin(pData->id, this);
  1354. // init OSC
  1355. {
  1356. char shmIdStr[12+1] = { 0 };
  1357. std::strncpy(shmIdStr, &fShmAudioPool.filename[fShmAudioPool.filename.length()-6], 6);
  1358. std::strncat(shmIdStr, &fShmControl.filename[fShmControl.filename.length()-6], 6);
  1359. pData->osc.thread.setOscData(bridgeBinary, label, getPluginTypeAsString(fPluginType), shmIdStr);
  1360. pData->osc.thread.start();
  1361. }
  1362. for (int i=0; i < 200; ++i)
  1363. {
  1364. if (fInitiated || ! pData->osc.thread.isRunning())
  1365. break;
  1366. carla_msleep(50);
  1367. }
  1368. if (fInitError || ! fInitiated)
  1369. {
  1370. // unregister so it gets handled properly
  1371. pData->engine->registerEnginePlugin(pData->id, nullptr);
  1372. pData->osc.thread.stop(6000);
  1373. if (! fInitError)
  1374. pData->engine->setLastError("Timeout while waiting for a response from plugin-bridge\n(or the plugin crashed on initialization?)");
  1375. return false;
  1376. }
  1377. // ---------------------------------------------------------------
  1378. // register client
  1379. if (pData->name == nullptr)
  1380. {
  1381. if (name != nullptr && name[0] != '\0')
  1382. pData->name = pData->engine->getUniquePluginName(name);
  1383. else if (label != nullptr && label[0] != '\0')
  1384. pData->name = pData->engine->getUniquePluginName(label);
  1385. else
  1386. pData->name = pData->engine->getUniquePluginName("unknown");
  1387. }
  1388. pData->client = pData->engine->addClient(this);
  1389. if (pData->client == nullptr || ! pData->client->isOk())
  1390. {
  1391. pData->engine->setLastError("Failed to register plugin client");
  1392. return false;
  1393. }
  1394. return true;
  1395. }
  1396. private:
  1397. const BinaryType fBinaryType;
  1398. const PluginType fPluginType;
  1399. bool fInitiated;
  1400. bool fInitError;
  1401. bool fSaved;
  1402. bool fNeedsSemDestroy;
  1403. CarlaString fBridgeBinary;
  1404. BridgeAudioPool fShmAudioPool;
  1405. BridgeControl fShmControl;
  1406. struct Info {
  1407. uint32_t aIns, aOuts;
  1408. uint32_t mIns, mOuts;
  1409. PluginCategory category;
  1410. long uniqueId;
  1411. CarlaString name;
  1412. CarlaString label;
  1413. CarlaString maker;
  1414. CarlaString copyright;
  1415. //QByteArray chunk;
  1416. Info()
  1417. : aIns(0),
  1418. aOuts(0),
  1419. mIns(0),
  1420. mOuts(0),
  1421. category(PLUGIN_CATEGORY_NONE),
  1422. uniqueId(0) {}
  1423. } fInfo;
  1424. BridgeParamInfo* fParams;
  1425. void resizeAudioPool(const uint32_t bufferSize)
  1426. {
  1427. fShmAudioPool.resize(bufferSize, fInfo.aIns+fInfo.aOuts);
  1428. fShmControl.writeOpcode(kPluginBridgeOpcodeSetAudioPool);
  1429. fShmControl.writeLong(static_cast<int64_t>(fShmAudioPool.size));
  1430. fShmControl.commitWrite();
  1431. waitForServer();
  1432. }
  1433. bool waitForServer()
  1434. {
  1435. if (! fShmControl.waitForServer())
  1436. {
  1437. carla_stderr("waitForServer() timeout");
  1438. pData->active = false; // TODO
  1439. return false;
  1440. }
  1441. return true;
  1442. }
  1443. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(BridgePlugin)
  1444. };
  1445. CARLA_BACKEND_END_NAMESPACE
  1446. #endif // ! BUILD_BRIDGE
  1447. // -------------------------------------------------------------------------------------------------------------------
  1448. CARLA_BACKEND_START_NAMESPACE
  1449. CarlaPlugin* CarlaPlugin::newBridge(const Initializer& init, BinaryType btype, PluginType ptype, const char* const bridgeBinary)
  1450. {
  1451. carla_debug("CarlaPlugin::newBridge({%p, \"%s\", \"%s\", \"%s\"}, %s, %s, \"%s\")", init.engine, init.filename, init.name, init.label, BinaryType2Str(btype), PluginType2Str(ptype), bridgeBinary);
  1452. #ifndef BUILD_BRIDGE
  1453. if (bridgeBinary == nullptr || bridgeBinary[0] == '\0')
  1454. {
  1455. init.engine->setLastError("Bridge not possible, bridge-binary not found");
  1456. return nullptr;
  1457. }
  1458. BridgePlugin* const plugin(new BridgePlugin(init.engine, init.id, btype, ptype));
  1459. if (! plugin->init(init.filename, init.name, init.label, bridgeBinary))
  1460. {
  1461. delete plugin;
  1462. return nullptr;
  1463. }
  1464. plugin->reload();
  1465. if (init.engine->getProccessMode() == ENGINE_PROCESS_MODE_CONTINUOUS_RACK && ! plugin->canRunInRack())
  1466. {
  1467. init.engine->setLastError("Carla's rack mode can only work with Stereo Bridged plugins, sorry!");
  1468. delete plugin;
  1469. return nullptr;
  1470. }
  1471. return plugin;
  1472. #else
  1473. init.engine->setLastError("Plugin bridge support not available");
  1474. return nullptr;
  1475. // unused
  1476. (void)bridgeBinary;
  1477. #endif
  1478. }
  1479. #ifndef BUILD_BRIDGE
  1480. // -------------------------------------------------------------------------------------------------------------------
  1481. // Bridge Helper
  1482. #define bridgePlugin ((BridgePlugin*)plugin)
  1483. extern int CarlaPluginSetOscBridgeInfo(CarlaPlugin* const plugin, const PluginBridgeInfoType type,
  1484. const int argc, const lo_arg* const* const argv, const char* const types);
  1485. int CarlaPluginSetOscBridgeInfo(CarlaPlugin* const plugin, const PluginBridgeInfoType type,
  1486. const int argc, const lo_arg* const* const argv, const char* const types)
  1487. {
  1488. CARLA_ASSERT(plugin != nullptr && (plugin->getHints() & PLUGIN_IS_BRIDGE) != 0);
  1489. return bridgePlugin->setOscPluginBridgeInfo(type, argc, argv, types);
  1490. }
  1491. #undef bridgePlugin
  1492. #endif
  1493. CARLA_BACKEND_END_NAMESPACE
  1494. // -------------------------------------------------------------------------------------------------------------------