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.

1949 lines
61KB

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