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.

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