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.

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