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.

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