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.

2003 lines
66KB

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