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.

1958 lines
62KB

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