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.

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