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.

1933 lines
61KB

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