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.

1953 lines
61KB

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