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.

1993 lines
66KB

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