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.

1938 lines
64KB

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