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.

1520 lines
44KB

  1. /*
  2. * Carla Bridge Plugin
  3. * Copyright (C) 2011-2013 Filipe Coelho <falktx@falktx.com>
  4. *
  5. * This program is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU General Public License as
  7. * published by the Free Software Foundation; either version 2 of
  8. * the License, or any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * For a full copy of the GNU General Public License see the GPL.txt file
  16. */
  17. #include "CarlaPluginInternal.hpp"
  18. #ifndef BUILD_BRIDGE
  19. #include "CarlaBridgeUtils.hpp"
  20. #include "CarlaShmUtils.hpp"
  21. #include <cerrno>
  22. #include <ctime>
  23. #if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
  24. # include <sys/time.h>
  25. #endif
  26. #include <QtCore/QDir>
  27. #include <QtCore/QFile>
  28. #include <QtCore/QStringList>
  29. #include <QtCore/QTextStream>
  30. #define CARLA_BRIDGE_CHECK_OSC_TYPES(/* argc, types, */ argcToCompare, typesToCompare) \
  31. /* check argument count */ \
  32. if (argc != argcToCompare) \
  33. { \
  34. carla_stderr("BridgePlugin::%s() - argument count mismatch: %i != %i", __FUNCTION__, argc, argcToCompare); \
  35. return 1; \
  36. } \
  37. if (argc > 0) \
  38. { \
  39. /* check for nullness */ \
  40. if (! (types && typesToCompare)) \
  41. { \
  42. carla_stderr("BridgePlugin::%s() - argument types are null", __FUNCTION__); \
  43. return 1; \
  44. } \
  45. /* check argument types */ \
  46. if (std::strcmp(types, typesToCompare) != 0) \
  47. { \
  48. carla_stderr("BridgePlugin::%s() - argument types mismatch: '%s' != '%s'", __FUNCTION__, types, typesToCompare); \
  49. return 1; \
  50. } \
  51. }
  52. CARLA_BACKEND_START_NAMESPACE
  53. // -------------------------------------------------------------------------------------------------------------------
  54. // Engine Helpers
  55. extern void registerEnginePlugin(CarlaEngine* const engine, const unsigned int id, CarlaPlugin* const plugin);
  56. // -------------------------------------------------------------------------------------------------------------------
  57. shm_t shm_mkstemp(char* const fileBase)
  58. {
  59. static const char charSet[] = "abcdefghijklmnopqrstuvwxyz"
  60. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  61. "0123456789";
  62. const int size = (fileBase != nullptr) ? std::strlen(fileBase) : 0;
  63. shm_t shm;
  64. carla_shm_init(shm);
  65. if (size < 6)
  66. {
  67. errno = EINVAL;
  68. return shm;
  69. }
  70. if (std::strcmp(fileBase + size - 6, "XXXXXX") != 0)
  71. {
  72. errno = EINVAL;
  73. return shm;
  74. }
  75. while (true)
  76. {
  77. for (int c = size - 6; c < size; c++)
  78. {
  79. // Note the -1 to avoid the trailing '\0' in charSet.
  80. fileBase[c] = charSet[std::rand() % (sizeof(charSet) - 1)];
  81. }
  82. shm_t shm = carla_shm_create(fileBase);
  83. if (carla_is_shm_valid(shm) || errno != EEXIST)
  84. return shm;
  85. }
  86. }
  87. // -------------------------------------------------------------------------------------------------------------------
  88. struct BridgeParamInfo {
  89. float value;
  90. CarlaString name;
  91. CarlaString unit;
  92. BridgeParamInfo()
  93. : value(0.0f) {}
  94. };
  95. class BridgePlugin : public CarlaPlugin
  96. {
  97. public:
  98. BridgePlugin(CarlaEngine* const engine, const unsigned int id, const BinaryType btype, const PluginType ptype)
  99. : CarlaPlugin(engine, id),
  100. fBinaryType(btype),
  101. fPluginType(ptype),
  102. fInitiated(false),
  103. fInitError(false),
  104. fSaved(false),
  105. fParams(nullptr)
  106. {
  107. carla_debug("BridgePlugin::BridgePlugin(%p, %i, %s, %s)", engine, id, BinaryType2Str(btype), PluginType2Str(ptype));
  108. kData->osc.thread.setMode(CarlaPluginThread::PLUGIN_THREAD_BRIDGE);
  109. }
  110. ~BridgePlugin() override
  111. {
  112. carla_debug("BridgePlugin::~BridgePlugin()");
  113. kData->singleMutex.lock();
  114. kData->masterMutex.lock();
  115. if (kData->active)
  116. {
  117. deactivate();
  118. kData->active = false;
  119. }
  120. if (kData->osc.data.target != nullptr)
  121. {
  122. osc_send_hide(&kData->osc.data);
  123. osc_send_quit(&kData->osc.data);
  124. }
  125. kData->osc.data.free();
  126. // Wait a bit first, then force kill
  127. if (kData->osc.thread.isRunning() && ! kData->osc.thread.wait(kData->engine->getOptions().oscUiTimeout))
  128. {
  129. carla_stderr("Failed to properly stop Plugin Bridge thread");
  130. kData->osc.thread.terminate();
  131. }
  132. cleanup();
  133. //info.chunk.clear();
  134. }
  135. // -------------------------------------------------------------------
  136. // Information (base)
  137. BinaryType binaryType() const
  138. {
  139. return fBinaryType;
  140. }
  141. PluginType type() const override
  142. {
  143. return fPluginType;
  144. }
  145. PluginCategory category() override
  146. {
  147. return fInfo.category;
  148. }
  149. long uniqueId() const override
  150. {
  151. return fInfo.uniqueId;
  152. }
  153. // -------------------------------------------------------------------
  154. // Information (count)
  155. uint32_t midiInCount() const override
  156. {
  157. return fInfo.mIns;
  158. }
  159. uint32_t midiOutCount() const override
  160. {
  161. return fInfo.mOuts;
  162. }
  163. // -------------------------------------------------------------------
  164. // Information (current data)
  165. int32_t chunkData(void** const dataPtr) override
  166. {
  167. CARLA_ASSERT(fOptions & PLUGIN_OPTION_USE_CHUNKS);
  168. CARLA_ASSERT(dataPtr != nullptr);
  169. #if 0
  170. if (! info.chunk.isEmpty())
  171. {
  172. *dataPtr = info.chunk.data();
  173. return info.chunk.size();
  174. }
  175. #endif
  176. return 0;
  177. }
  178. // -------------------------------------------------------------------
  179. // Information (per-plugin data)
  180. unsigned int availableOptions() override
  181. {
  182. unsigned int options = 0x0;
  183. options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  184. options |= PLUGIN_OPTION_USE_CHUNKS;
  185. options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  186. options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  187. options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  188. options |= PLUGIN_OPTION_SEND_PITCHBEND;
  189. options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  190. return options;
  191. }
  192. #if 0
  193. double getParameterValue(const uint32_t parameterId) override
  194. {
  195. CARLA_ASSERT(parameterId < param.count);
  196. return params[parameterId].value;
  197. }
  198. #endif
  199. void getLabel(char* const strBuf) override
  200. {
  201. std::strncpy(strBuf, (const char*)fInfo.label, STR_MAX);
  202. }
  203. void getMaker(char* const strBuf) override
  204. {
  205. std::strncpy(strBuf, (const char*)fInfo.maker, STR_MAX);
  206. }
  207. void getCopyright(char* const strBuf) override
  208. {
  209. std::strncpy(strBuf, (const char*)fInfo.copyright, STR_MAX);
  210. }
  211. void getRealName(char* const strBuf) override
  212. {
  213. std::strncpy(strBuf, (const char*)fInfo.name, STR_MAX);
  214. }
  215. #if 0
  216. void getParameterName(const uint32_t parameterId, char* const strBuf) override
  217. {
  218. CARLA_ASSERT(parameterId < param.count);
  219. strncpy(strBuf, params[parameterId].name.toUtf8().constData(), STR_MAX);
  220. }
  221. void getParameterUnit(const uint32_t parameterId, char* const strBuf) override
  222. {
  223. CARLA_ASSERT(parameterId < param.count);
  224. strncpy(strBuf, params[parameterId].unit.toUtf8().constData(), STR_MAX);
  225. }
  226. #endif
  227. // -------------------------------------------------------------------
  228. // Set data (state)
  229. void prepareForSave() override
  230. {
  231. #if 0
  232. m_saved = false;
  233. osc_send_configure(&osc.data, CARLA_BRIDGE_MSG_SAVE_NOW, "");
  234. for (int i=0; i < 200; i++)
  235. {
  236. if (m_saved)
  237. break;
  238. carla_msleep(50);
  239. }
  240. if (! m_saved)
  241. carla_stderr("BridgePlugin::prepareForSave() - Timeout while requesting save state");
  242. else
  243. carla_debug("BridgePlugin::prepareForSave() - success!");
  244. #endif
  245. }
  246. // -------------------------------------------------------------------
  247. // Set data (internal stuff)
  248. // nothing
  249. // -------------------------------------------------------------------
  250. // Set data (plugin-specific stuff)
  251. #if 0
  252. void setParameterValue(const uint32_t parameterId, double value, const bool sendGui, const bool sendOsc, const bool sendCallback) override
  253. {
  254. CARLA_ASSERT(parameterId < param.count);
  255. params[parameterId].value = fixParameterValue(value, param.ranges[parameterId]);
  256. CarlaPlugin::setParameterValue(parameterId, value, sendGui, sendOsc, sendCallback);
  257. }
  258. void setCustomData(const char* const type, const char* const key, const char* const value, const bool sendGui) override
  259. {
  260. CARLA_ASSERT(type);
  261. CARLA_ASSERT(key);
  262. CARLA_ASSERT(value);
  263. if (sendGui)
  264. {
  265. // TODO - if type is chunk|binary, store it in a file and send path instead
  266. QString cData;
  267. cData = type;
  268. cData += "·";
  269. cData += key;
  270. cData += "·";
  271. cData += value;
  272. osc_send_configure(&osc.data, CARLA_BRIDGE_MSG_SET_CUSTOM, cData.toUtf8().constData());
  273. }
  274. CarlaPlugin::setCustomData(type, key, value, sendGui);
  275. }
  276. void setChunkData(const char* const stringData) override
  277. {
  278. CARLA_ASSERT(m_hints & PLUGIN_USES_CHUNKS);
  279. CARLA_ASSERT(stringData);
  280. QString filePath;
  281. filePath = QDir::tempPath();
  282. filePath += "/.CarlaChunk_";
  283. filePath += m_name;
  284. filePath = QDir::toNativeSeparators(filePath);
  285. QFile file(filePath);
  286. if (file.open(QIODevice::WriteOnly | QIODevice::Text))
  287. {
  288. QTextStream out(&file);
  289. out << stringData;
  290. file.close();
  291. osc_send_configure(&osc.data, CARLA_BRIDGE_MSG_SET_CHUNK, filePath.toUtf8().constData());
  292. }
  293. }
  294. #endif
  295. // -------------------------------------------------------------------
  296. // Set gui stuff
  297. void showGui(const bool yesNo) override
  298. {
  299. if (yesNo)
  300. osc_send_show(&kData->osc.data);
  301. else
  302. osc_send_hide(&kData->osc.data);
  303. }
  304. void idleGui() override
  305. {
  306. if (! kData->osc.thread.isRunning())
  307. carla_stderr2("TESTING: Bridge has closed!");
  308. CarlaPlugin::idleGui();
  309. }
  310. // -------------------------------------------------------------------
  311. // Plugin state
  312. void reload() override
  313. {
  314. carla_debug("BridgePlugin::reload() - start");
  315. CARLA_ASSERT(kData->engine != nullptr);
  316. if (kData->engine == nullptr)
  317. return;
  318. const ProcessMode processMode(kData->engine->getProccessMode());
  319. // Safely disable plugin for reload
  320. const ScopedDisabler sd(this);
  321. kData->clearBuffers();
  322. bool needsCtrlIn, needsCtrlOut;
  323. needsCtrlIn = needsCtrlOut = false;
  324. if (fInfo.aIns > 0)
  325. {
  326. kData->audioIn.createNew(fInfo.aIns);
  327. }
  328. if (fInfo.aOuts > 0)
  329. {
  330. kData->audioOut.createNew(fInfo.aOuts);
  331. needsCtrlIn = true;
  332. }
  333. if (fInfo.mIns > 0)
  334. needsCtrlIn = true;
  335. if (fInfo.mOuts > 0)
  336. needsCtrlOut = true;
  337. const uint portNameSize(kData->engine->maxPortNameSize());
  338. CarlaString portName;
  339. // Audio Ins
  340. for (uint32_t j=0; j < fInfo.aIns; j++)
  341. {
  342. portName.clear();
  343. if (processMode == PROCESS_MODE_SINGLE_CLIENT)
  344. {
  345. portName = fName;
  346. portName += ":";
  347. }
  348. if (fInfo.aIns > 1)
  349. {
  350. portName += "input_";
  351. portName += CarlaString(j+1);
  352. }
  353. else
  354. portName += "input";
  355. portName.truncate(portNameSize);
  356. kData->audioIn.ports[j].port = (CarlaEngineAudioPort*)kData->client->addPort(kEnginePortTypeAudio, portName, true);
  357. kData->audioIn.ports[j].rindex = j;
  358. }
  359. // Audio Outs
  360. for (uint32_t j=0; j < fInfo.aOuts; j++)
  361. {
  362. portName.clear();
  363. if (processMode == PROCESS_MODE_SINGLE_CLIENT)
  364. {
  365. portName = fName;
  366. portName += ":";
  367. }
  368. if (fInfo.aOuts > 1)
  369. {
  370. portName += "output_";
  371. portName += CarlaString(j+1);
  372. }
  373. else
  374. portName += "output";
  375. portName.truncate(portNameSize);
  376. kData->audioOut.ports[j].port = (CarlaEngineAudioPort*)kData->client->addPort(kEnginePortTypeAudio, portName, false);
  377. kData->audioOut.ports[j].rindex = j;
  378. }
  379. if (needsCtrlIn)
  380. {
  381. portName.clear();
  382. if (processMode == PROCESS_MODE_SINGLE_CLIENT)
  383. {
  384. portName = fName;
  385. portName += ":";
  386. }
  387. portName += "event-in";
  388. portName.truncate(portNameSize);
  389. kData->event.portIn = (CarlaEngineEventPort*)kData->client->addPort(kEnginePortTypeEvent, portName, true);
  390. }
  391. if (needsCtrlOut)
  392. {
  393. portName.clear();
  394. if (processMode == PROCESS_MODE_SINGLE_CLIENT)
  395. {
  396. portName = fName;
  397. portName += ":";
  398. }
  399. portName += "event-out";
  400. portName.truncate(portNameSize);
  401. kData->event.portOut = (CarlaEngineEventPort*)kData->client->addPort(kEnginePortTypeEvent, portName, false);
  402. }
  403. //bufferSizeChanged(kData->engine->getBufferSize());
  404. //reloadPrograms(true);
  405. carla_debug("BridgePlugin::reload() - end");
  406. }
  407. // -------------------------------------------------------------------
  408. // Plugin processing
  409. void process(float** const inBuffer, float** const outBuffer, const uint32_t frames) override
  410. {
  411. uint32_t i, k;
  412. // --------------------------------------------------------------------------------------------------------
  413. // Check if active
  414. if (! kData->active)
  415. {
  416. // disable any output sound
  417. for (i=0; i < kData->audioOut.count; i++)
  418. carla_zeroFloat(outBuffer[i], frames);
  419. return;
  420. }
  421. for (i=0; i < fInfo.aIns; ++i)
  422. carla_copyFloat(fShmAudioPool.data + i * frames, inBuffer[i], frames);
  423. rdwr_writeOpcode(&fShmControl.data->ringBuffer, kPluginBridgeOpcodeProcess);
  424. rdwr_commitWrite(&fShmControl.data->ringBuffer);
  425. waitForServer();
  426. for (i=0; i < fInfo.aOuts; ++i)
  427. carla_copyFloat(outBuffer[i], fShmAudioPool.data + (i+fInfo.aIns) * frames, frames);
  428. }
  429. // -------------------------------------------------------------------
  430. // Plugin buffers
  431. // nothing
  432. // -------------------------------------------------------------------
  433. // Post-poned UI Stuff
  434. void uiParameterChange(const uint32_t index, const float value) override
  435. {
  436. CARLA_ASSERT(index < kData->param.count);
  437. if (index >= kData->param.count)
  438. return;
  439. if (kData->osc.data.target == nullptr)
  440. return;
  441. osc_send_control(&kData->osc.data, kData->param.data[index].rindex, value);
  442. }
  443. void uiProgramChange(const uint32_t index) override
  444. {
  445. CARLA_ASSERT(index < kData->prog.count);
  446. if (index >= kData->prog.count)
  447. return;
  448. if (kData->osc.data.target == nullptr)
  449. return;
  450. osc_send_program(&kData->osc.data, index);
  451. }
  452. void uiMidiProgramChange(const uint32_t index) override
  453. {
  454. CARLA_ASSERT(index < kData->midiprog.count);
  455. if (index >= kData->midiprog.count)
  456. return;
  457. if (kData->osc.data.target == nullptr)
  458. return;
  459. osc_send_midi_program(&kData->osc.data, index);
  460. }
  461. void uiNoteOn(const uint8_t channel, const uint8_t note, const uint8_t velo) override
  462. {
  463. CARLA_ASSERT(channel < MAX_MIDI_CHANNELS);
  464. CARLA_ASSERT(note < MAX_MIDI_NOTE);
  465. CARLA_ASSERT(velo > 0 && velo < MAX_MIDI_VALUE);
  466. if (channel >= MAX_MIDI_CHANNELS)
  467. return;
  468. if (note >= MAX_MIDI_NOTE)
  469. return;
  470. if (velo >= MAX_MIDI_VALUE)
  471. return;
  472. if (kData->osc.data.target == nullptr)
  473. return;
  474. uint8_t midiData[4] = { 0 };
  475. midiData[1] = MIDI_STATUS_NOTE_ON + channel;
  476. midiData[2] = note;
  477. midiData[3] = velo;
  478. osc_send_midi(&kData->osc.data, midiData);
  479. }
  480. void uiNoteOff(const uint8_t channel, const uint8_t note) override
  481. {
  482. CARLA_ASSERT(channel < MAX_MIDI_CHANNELS);
  483. CARLA_ASSERT(note < MAX_MIDI_NOTE);
  484. if (channel >= MAX_MIDI_CHANNELS)
  485. return;
  486. if (note >= MAX_MIDI_NOTE)
  487. return;
  488. if (kData->osc.data.target == nullptr)
  489. return;
  490. uint8_t midiData[4] = { 0 };
  491. midiData[1] = MIDI_STATUS_NOTE_OFF + channel;
  492. midiData[2] = note;
  493. osc_send_midi(&kData->osc.data, midiData);
  494. }
  495. void bufferSizeChanged(const uint32_t newBufferSize) override
  496. {
  497. resizeAudioPool(newBufferSize);
  498. }
  499. // -------------------------------------------------------------------
  500. int setOscPluginBridgeInfo(const PluginBridgeInfoType type, const int argc, const lo_arg* const* const argv, const char* const types)
  501. {
  502. carla_stdout("setOscPluginBridgeInfo(%i, %i, %p, \"%s\")", type, argc, argv, types);
  503. switch (type)
  504. {
  505. case kPluginBridgeAudioCount:
  506. {
  507. CARLA_BRIDGE_CHECK_OSC_TYPES(3, "iii");
  508. const int32_t aIns = argv[0]->i;
  509. const int32_t aOuts = argv[1]->i;
  510. const int32_t aTotal = argv[2]->i;
  511. CARLA_ASSERT(aIns >= 0);
  512. CARLA_ASSERT(aOuts >= 0);
  513. CARLA_ASSERT(aIns + aOuts == aTotal);
  514. fInfo.aIns = aIns;
  515. fInfo.aOuts = aOuts;
  516. break;
  517. // unused
  518. (void)aTotal;
  519. }
  520. case kPluginBridgeMidiCount:
  521. {
  522. CARLA_BRIDGE_CHECK_OSC_TYPES(3, "iii");
  523. const int32_t mIns = argv[0]->i;
  524. const int32_t mOuts = argv[1]->i;
  525. const int32_t mTotal = argv[2]->i;
  526. CARLA_ASSERT(mIns >= 0);
  527. CARLA_ASSERT(mOuts >= 0);
  528. CARLA_ASSERT(mIns + mOuts == mTotal);
  529. fInfo.mIns = mIns;
  530. fInfo.mOuts = mOuts;
  531. break;
  532. // unused
  533. (void)mTotal;
  534. }
  535. #if 0
  536. case PluginBridgeParameterCount:
  537. {
  538. CARLA_BRIDGE_CHECK_OSC_TYPES(3, "iii");
  539. const int32_t pIns = argv[0]->i;
  540. const int32_t pOuts = argv[1]->i;
  541. const int32_t pTotal = argv[2]->i;
  542. CARLA_ASSERT(pIns >= 0);
  543. CARLA_ASSERT(pOuts >= 0);
  544. CARLA_ASSERT(pIns + pOuts <= pTotal);
  545. // delete old data
  546. if (param.count > 0)
  547. {
  548. delete[] param.data;
  549. delete[] param.ranges;
  550. delete[] params;
  551. }
  552. // create new if needed
  553. const int32_t maxParams = x_engine->getOptions().maxParameters;
  554. param.count = (pTotal < maxParams) ? pTotal : 0;
  555. if (param.count > 0)
  556. {
  557. param.data = new ParameterData[param.count];
  558. param.ranges = new ParameterRanges[param.count];
  559. params = new BridgeParamInfo[param.count];
  560. }
  561. else
  562. {
  563. param.data = nullptr;
  564. param.ranges = nullptr;
  565. params = nullptr;
  566. }
  567. break;
  568. Q_UNUSED(pIns);
  569. Q_UNUSED(pOuts);
  570. }
  571. case PluginBridgeProgramCount:
  572. {
  573. CARLA_BRIDGE_CHECK_OSC_TYPES(1, "i");
  574. const int32_t count = argv[0]->i;
  575. CARLA_ASSERT(count >= 0);
  576. // delete old programs
  577. if (prog.count > 0)
  578. {
  579. for (uint32_t i=0; i < prog.count; i++)
  580. {
  581. if (prog.names[i])
  582. free((void*)prog.names[i]);
  583. }
  584. delete[] prog.names;
  585. }
  586. prog.count = count;
  587. // create new if needed
  588. if (prog.count > 0)
  589. {
  590. prog.names = new const char* [prog.count];
  591. for (uint32_t i=0; i < prog.count; i++)
  592. prog.names[i] = nullptr;
  593. }
  594. else
  595. prog.names = nullptr;
  596. break;
  597. }
  598. case PluginBridgeMidiProgramCount:
  599. {
  600. CARLA_BRIDGE_CHECK_OSC_TYPES(1, "i");
  601. const int32_t count = argv[0]->i;
  602. // delete old programs
  603. if (midiprog.count > 0)
  604. {
  605. for (uint32_t i=0; i < midiprog.count; i++)
  606. {
  607. if (midiprog.data[i].name)
  608. free((void*)midiprog.data[i].name);
  609. }
  610. delete[] midiprog.data;
  611. }
  612. // create new if needed
  613. midiprog.count = count;
  614. if (midiprog.count > 0)
  615. midiprog.data = new MidiProgramData[midiprog.count];
  616. else
  617. midiprog.data = nullptr;
  618. break;
  619. }
  620. #endif
  621. case kPluginBridgePluginInfo:
  622. {
  623. CARLA_BRIDGE_CHECK_OSC_TYPES(7, "iissssh");
  624. const int32_t category = argv[0]->i;
  625. const int32_t hints = argv[1]->i;
  626. const char* const name = (const char*)&argv[2]->s;
  627. const char* const label = (const char*)&argv[3]->s;
  628. const char* const maker = (const char*)&argv[4]->s;
  629. const char* const copyright = (const char*)&argv[5]->s;
  630. const int64_t uniqueId = argv[6]->h;
  631. CARLA_ASSERT(category >= 0);
  632. CARLA_ASSERT(hints >= 0);
  633. CARLA_ASSERT(name);
  634. CARLA_ASSERT(label);
  635. CARLA_ASSERT(maker);
  636. CARLA_ASSERT(copyright);
  637. fHints = hints | PLUGIN_IS_BRIDGE;
  638. fInfo.category = static_cast<PluginCategory>(category);
  639. fInfo.uniqueId = uniqueId;
  640. fInfo.name = name;
  641. fInfo.label = label;
  642. fInfo.maker = maker;
  643. fInfo.copyright = copyright;
  644. if (fName.isEmpty())
  645. fName = kData->engine->getUniquePluginName(name);
  646. break;
  647. }
  648. #if 0
  649. case PluginBridgeParameterInfo:
  650. {
  651. CARLA_BRIDGE_CHECK_OSC_TYPES(3, "iss");
  652. const int32_t index = argv[0]->i;
  653. const char* const name = (const char*)&argv[1]->s;
  654. const char* const unit = (const char*)&argv[2]->s;
  655. CARLA_ASSERT(index >= 0 && index < (int32_t)param.count);
  656. CARLA_ASSERT(name);
  657. CARLA_ASSERT(unit);
  658. if (index >= 0 && index < (int32_t)param.count)
  659. {
  660. params[index].name = QString(name);
  661. params[index].unit = QString(unit);
  662. }
  663. break;
  664. }
  665. case PluginBridgeParameterData:
  666. {
  667. CARLA_BRIDGE_CHECK_OSC_TYPES(6, "iiiiii");
  668. const int32_t index = argv[0]->i;
  669. const int32_t type = argv[1]->i;
  670. const int32_t rindex = argv[2]->i;
  671. const int32_t hints = argv[3]->i;
  672. const int32_t channel = argv[4]->i;
  673. const int32_t cc = argv[5]->i;
  674. CARLA_ASSERT(index >= 0 && index < (int32_t)param.count);
  675. CARLA_ASSERT(type >= 0);
  676. CARLA_ASSERT(rindex >= 0);
  677. CARLA_ASSERT(hints >= 0);
  678. CARLA_ASSERT(channel >= 0 && channel < 16);
  679. CARLA_ASSERT(cc >= -1);
  680. if (index >= 0 && index < (int32_t)param.count)
  681. {
  682. param.data[index].type = (ParameterType)type;
  683. param.data[index].index = index;
  684. param.data[index].rindex = rindex;
  685. param.data[index].hints = hints;
  686. param.data[index].midiChannel = channel;
  687. param.data[index].midiCC = cc;
  688. }
  689. break;
  690. }
  691. case PluginBridgeParameterRanges:
  692. {
  693. CARLA_BRIDGE_CHECK_OSC_TYPES(7, "idddddd");
  694. const int32_t index = argv[0]->i;
  695. const double def = argv[1]->d;
  696. const double min = argv[2]->d;
  697. const double max = argv[3]->d;
  698. const double step = argv[4]->d;
  699. const double stepSmall = argv[5]->d;
  700. const double stepLarge = argv[6]->d;
  701. CARLA_ASSERT(index >= 0 && index < (int32_t)param.count);
  702. CARLA_ASSERT(min < max);
  703. CARLA_ASSERT(def >= min);
  704. CARLA_ASSERT(def <= max);
  705. if (index >= 0 && index < (int32_t)param.count)
  706. {
  707. param.ranges[index].def = def;
  708. param.ranges[index].min = min;
  709. param.ranges[index].max = max;
  710. param.ranges[index].step = step;
  711. param.ranges[index].stepSmall = stepSmall;
  712. param.ranges[index].stepLarge = stepLarge;
  713. params[index].value = def;
  714. }
  715. break;
  716. }
  717. case PluginBridgeProgramInfo:
  718. {
  719. CARLA_BRIDGE_CHECK_OSC_TYPES(2, "is");
  720. const int32_t index = argv[0]->i;
  721. const char* const name = (const char*)&argv[1]->s;
  722. CARLA_ASSERT(index >= 0 && index < (int32_t)prog.count);
  723. CARLA_ASSERT(name);
  724. if (index >= 0 && index < (int32_t)prog.count)
  725. {
  726. if (prog.names[index])
  727. free((void*)prog.names[index]);
  728. prog.names[index] = strdup(name);
  729. }
  730. break;
  731. }
  732. case PluginBridgeMidiProgramInfo:
  733. {
  734. CARLA_BRIDGE_CHECK_OSC_TYPES(4, "iiis");
  735. const int32_t index = argv[0]->i;
  736. const int32_t bank = argv[1]->i;
  737. const int32_t program = argv[2]->i;
  738. const char* const name = (const char*)&argv[3]->s;
  739. CARLA_ASSERT(index >= 0 && index < (int32_t)midiprog.count);
  740. CARLA_ASSERT(bank >= 0);
  741. CARLA_ASSERT(program >= 0 && program < 128);
  742. CARLA_ASSERT(name);
  743. if (index >= 0 && index < (int32_t)midiprog.count)
  744. {
  745. if (midiprog.data[index].name)
  746. free((void*)midiprog.data[index].name);
  747. midiprog.data[index].bank = bank;
  748. midiprog.data[index].program = program;
  749. midiprog.data[index].name = strdup(name);
  750. }
  751. break;
  752. }
  753. case PluginBridgeConfigure:
  754. {
  755. CARLA_BRIDGE_CHECK_OSC_TYPES(2, "ss");
  756. const char* const key = (const char*)&argv[0]->s;
  757. const char* const value = (const char*)&argv[1]->s;
  758. CARLA_ASSERT(key);
  759. CARLA_ASSERT(value);
  760. if (! (key && value))
  761. {
  762. // invalid
  763. pass();
  764. }
  765. else if (std::strcmp(key, CARLA_BRIDGE_MSG_HIDE_GUI) == 0)
  766. {
  767. x_engine->callback(CALLBACK_SHOW_GUI, m_id, 0, 0, 0.0, nullptr);
  768. }
  769. else if (std::strcmp(key, CARLA_BRIDGE_MSG_SAVED) == 0)
  770. {
  771. m_saved = true;
  772. }
  773. break;
  774. }
  775. case PluginBridgeSetParameterValue:
  776. {
  777. CARLA_BRIDGE_CHECK_OSC_TYPES(2, "id");
  778. const int32_t index = argv[0]->i;
  779. const double value = argv[1]->d;
  780. CARLA_ASSERT(index != PARAMETER_NULL);
  781. setParameterValueByRIndex(index, value, false, true, true);
  782. break;
  783. }
  784. case PluginBridgeSetDefaultValue:
  785. {
  786. CARLA_BRIDGE_CHECK_OSC_TYPES(2, "id");
  787. const int32_t index = argv[0]->i;
  788. const double value = argv[1]->d;
  789. CARLA_ASSERT(index >= 0 && index < (int32_t)param.count);
  790. if (index >= 0 && index < (int32_t)param.count)
  791. param.ranges[index].def = value;
  792. break;
  793. }
  794. case PluginBridgeSetProgram:
  795. {
  796. CARLA_BRIDGE_CHECK_OSC_TYPES(1, "i");
  797. const int32_t index = argv[0]->i;
  798. CARLA_ASSERT(index < (int32_t)prog.count);
  799. setProgram(index, false, true, true, true);
  800. break;
  801. }
  802. case PluginBridgeSetMidiProgram:
  803. {
  804. CARLA_BRIDGE_CHECK_OSC_TYPES(1, "i");
  805. const int32_t index = argv[0]->i;
  806. CARLA_ASSERT(index < (int32_t)midiprog.count);
  807. setMidiProgram(index, false, true, true, true);
  808. break;
  809. }
  810. case PluginBridgeSetCustomData:
  811. {
  812. CARLA_BRIDGE_CHECK_OSC_TYPES(3, "sss");
  813. const char* const type = (const char*)&argv[0]->s;
  814. const char* const key = (const char*)&argv[1]->s;
  815. const char* const value = (const char*)&argv[2]->s;
  816. CARLA_ASSERT(type);
  817. CARLA_ASSERT(key);
  818. CARLA_ASSERT(value);
  819. setCustomData(type, key, value, false);
  820. break;
  821. }
  822. case PluginBridgeSetChunkData:
  823. {
  824. CARLA_BRIDGE_CHECK_OSC_TYPES(1, "s");
  825. const char* const chunkFileChar = (const char*)&argv[0]->s;
  826. CARLA_ASSERT(chunkFileChar);
  827. QString chunkFileStr(chunkFileChar);
  828. #ifndef Q_OS_WIN
  829. // Using Wine, fix temp dir
  830. if (m_binary == BINARY_WIN32 || m_binary == BINARY_WIN64)
  831. {
  832. // Get WINEPREFIX
  833. QString wineDir;
  834. if (const char* const WINEPREFIX = getenv("WINEPREFIX"))
  835. wineDir = QString(WINEPREFIX);
  836. else
  837. wineDir = QDir::homePath() + "/.wine";
  838. QStringList chunkFileStrSplit1 = chunkFileStr.split(":/");
  839. QStringList chunkFileStrSplit2 = chunkFileStrSplit1.at(1).split("\\");
  840. QString wineDrive = chunkFileStrSplit1.at(0).toLower();
  841. QString wineTMP = chunkFileStrSplit2.at(0);
  842. QString baseName = chunkFileStrSplit2.at(1);
  843. chunkFileStr = wineDir;
  844. chunkFileStr += "/drive_";
  845. chunkFileStr += wineDrive;
  846. chunkFileStr += "/";
  847. chunkFileStr += wineTMP;
  848. chunkFileStr += "/";
  849. chunkFileStr += baseName;
  850. chunkFileStr = QDir::toNativeSeparators(chunkFileStr);
  851. }
  852. #endif
  853. QFile chunkFile(chunkFileStr);
  854. if (chunkFile.open(QIODevice::ReadOnly))
  855. {
  856. info.chunk = chunkFile.readAll();
  857. chunkFile.close();
  858. chunkFile.remove();
  859. }
  860. break;
  861. }
  862. #endif
  863. case kPluginBridgeUpdateNow:
  864. {
  865. fInitiated = true;
  866. break;
  867. }
  868. case kPluginBridgeError:
  869. {
  870. CARLA_BRIDGE_CHECK_OSC_TYPES(1, "s");
  871. const char* const error = (const char*)&argv[0]->s;
  872. CARLA_ASSERT(error != nullptr);
  873. kData->engine->setLastError(error);
  874. fInitError = true;
  875. fInitiated = true;
  876. break;
  877. }
  878. }
  879. return 0;
  880. }
  881. // -------------------------------------------------------------------
  882. const void* getExtraStuff() override
  883. {
  884. return fBridgeBinary.isNotEmpty() ? (const char*)fBridgeBinary : nullptr;
  885. }
  886. bool init(const char* const filename, const char* const name, const char* const label, const char* const bridgeBinary)
  887. {
  888. CARLA_ASSERT(kData->engine != nullptr);
  889. CARLA_ASSERT(kData->client == nullptr);
  890. CARLA_ASSERT(filename != nullptr);
  891. // ---------------------------------------------------------------
  892. // first checks
  893. if (kData->engine == nullptr)
  894. {
  895. return false;
  896. }
  897. if (kData->client != nullptr)
  898. {
  899. kData->engine->setLastError("Plugin client is already registered");
  900. return false;
  901. }
  902. if (filename == nullptr)
  903. {
  904. kData->engine->setLastError("null filename");
  905. return false;
  906. }
  907. // ---------------------------------------------------------------
  908. // set info
  909. if (name != nullptr)
  910. fName = kData->engine->getUniquePluginName(name);
  911. fFilename = filename;
  912. // ---------------------------------------------------------------
  913. // register client
  914. kData->client = kData->engine->addClient(this);
  915. if (kData->client == nullptr || ! kData->client->isOk())
  916. {
  917. kData->engine->setLastError("Failed to register plugin client");
  918. return false;
  919. }
  920. // ---------------------------------------------------------------
  921. // SHM Audio Pool
  922. {
  923. char tmpFileBase[60];
  924. std::srand(std::time(NULL));
  925. std::sprintf(tmpFileBase, "/carla-bridge_shm_XXXXXX");
  926. fShmAudioPool.shm = shm_mkstemp(tmpFileBase);
  927. if (! carla_is_shm_valid(fShmAudioPool.shm))
  928. {
  929. //_cleanup();
  930. carla_stdout("Failed to open or create shared memory file #1");
  931. return false;
  932. }
  933. fShmAudioPool.filename = tmpFileBase;
  934. }
  935. // ---------------------------------------------------------------
  936. // SHM Control
  937. {
  938. char tmpFileBase[60];
  939. std::sprintf(tmpFileBase, "/carla-bridge_shc_XXXXXX");
  940. fShmControl.shm = shm_mkstemp(tmpFileBase);
  941. if (! carla_is_shm_valid(fShmControl.shm))
  942. {
  943. //_cleanup();
  944. carla_stdout("Failed to open or create shared memory file #2");
  945. return false;
  946. }
  947. fShmControl.filename = tmpFileBase;
  948. if (! carla_shm_map<BridgeShmControl>(fShmControl.shm, fShmControl.data))
  949. {
  950. //_cleanup();
  951. carla_stdout("Failed to mmap shared memory file");
  952. return false;
  953. }
  954. CARLA_ASSERT(fShmControl.data != nullptr);
  955. std::memset(fShmControl.data, 0, sizeof(BridgeShmControl));
  956. std::strcpy(fShmControl.data->ringBuffer.buf, "This thing is actually working!!!!");
  957. if (sem_init(&fShmControl.data->runServer, 1, 0) != 0)
  958. {
  959. //_cleanup();
  960. carla_stdout("Failed to initialize shared memory semaphore #1");
  961. return false;
  962. }
  963. if (sem_init(&fShmControl.data->runClient, 1, 0) != 0)
  964. {
  965. //_cleanup();
  966. carla_stdout("Failed to initialize shared memory semaphore #2");
  967. return false;
  968. }
  969. }
  970. // initial values
  971. rdwr_writeOpcode(&fShmControl.data->ringBuffer, kPluginBridgeOpcodeBufferSize);
  972. rdwr_writeInt(&fShmControl.data->ringBuffer, kData->engine->getBufferSize());
  973. rdwr_writeOpcode(&fShmControl.data->ringBuffer, kPluginBridgeOpcodeSampleRate);
  974. rdwr_writeFloat(&fShmControl.data->ringBuffer, kData->engine->getSampleRate());
  975. rdwr_commitWrite(&fShmControl.data->ringBuffer);
  976. // register plugin now so we can receive OSC (and wait for it)
  977. fHints |= PLUGIN_IS_BRIDGE;
  978. registerEnginePlugin(kData->engine, fId, this);
  979. // init OSC
  980. {
  981. char shmIdStr[12+1] = { 0 };
  982. std::strncpy(shmIdStr, &fShmAudioPool.filename[fShmAudioPool.filename.length()-6], 6);
  983. std::strncat(shmIdStr, &fShmControl.filename[fShmControl.filename.length()-6], 6);
  984. kData->osc.thread.setOscData(bridgeBinary, label, getPluginTypeAsString(fPluginType), shmIdStr);
  985. kData->osc.thread.start();
  986. //kData->osc.thread.waitForStarted();
  987. }
  988. for (int i=0; i < 200; i++)
  989. {
  990. if (fInitiated || ! kData->osc.thread.isRunning())
  991. break;
  992. carla_msleep(50);
  993. }
  994. if (! fInitiated)
  995. {
  996. // unregister so it gets handled properly
  997. registerEnginePlugin(kData->engine, fId, nullptr);
  998. if (kData->osc.thread.isRunning())
  999. kData->osc.thread.terminate();
  1000. kData->engine->setLastError("Timeout while waiting for a response from plugin-bridge\n(or the plugin crashed on initialization?)");
  1001. return false;
  1002. }
  1003. else if (fInitError)
  1004. {
  1005. // unregister so it gets handled properly
  1006. registerEnginePlugin(kData->engine, fId, nullptr);
  1007. kData->osc.thread.quit();
  1008. // last error was set before
  1009. return false;
  1010. }
  1011. fBridgeBinary = bridgeBinary;
  1012. resizeAudioPool(kData->engine->getBufferSize());
  1013. rdwr_writeOpcode(&fShmControl.data->ringBuffer, kPluginBridgeOpcodeReadyWait);
  1014. rdwr_writeInt(&fShmControl.data->ringBuffer, fShmAudioPool.size);
  1015. rdwr_commitWrite(&fShmControl.data->ringBuffer);
  1016. waitForServer();
  1017. return true;
  1018. }
  1019. private:
  1020. const BinaryType fBinaryType;
  1021. const PluginType fPluginType;
  1022. bool fInitiated;
  1023. bool fInitError;
  1024. bool fSaved;
  1025. CarlaString fBridgeBinary;
  1026. struct BridgeAudioPool {
  1027. CarlaString filename;
  1028. float* data;
  1029. size_t size;
  1030. shm_t shm;
  1031. BridgeAudioPool()
  1032. : data(nullptr),
  1033. size(0)
  1034. {
  1035. carla_shm_init(shm);
  1036. }
  1037. } fShmAudioPool;
  1038. struct BridgeControl {
  1039. CarlaString filename;
  1040. BridgeShmControl* data;
  1041. shm_t shm;
  1042. BridgeControl()
  1043. : data(nullptr)
  1044. {
  1045. carla_shm_init(shm);
  1046. }
  1047. } fShmControl;
  1048. struct Info {
  1049. uint32_t aIns, aOuts;
  1050. uint32_t mIns, mOuts;
  1051. PluginCategory category;
  1052. long uniqueId;
  1053. CarlaString name;
  1054. CarlaString label;
  1055. CarlaString maker;
  1056. CarlaString copyright;
  1057. //QByteArray chunk;
  1058. Info()
  1059. : aIns(0),
  1060. aOuts(0),
  1061. mIns(0),
  1062. mOuts(0),
  1063. category(PLUGIN_CATEGORY_NONE),
  1064. uniqueId(0) {}
  1065. } fInfo;
  1066. BridgeParamInfo* fParams;
  1067. void cleanup()
  1068. {
  1069. if (fShmAudioPool.filename.isNotEmpty())
  1070. fShmAudioPool.filename.clear();
  1071. if (fShmControl.filename.isNotEmpty())
  1072. fShmControl.filename.clear();
  1073. if (fShmAudioPool.data != nullptr)
  1074. {
  1075. carla_shm_unmap(fShmAudioPool.shm, fShmAudioPool.data, fShmAudioPool.size);
  1076. fShmAudioPool.data = nullptr;
  1077. }
  1078. fShmAudioPool.size = 0;
  1079. // and again
  1080. if (fShmControl.data != nullptr)
  1081. {
  1082. carla_shm_unmap(fShmControl.shm, fShmControl.data, sizeof(BridgeShmControl));
  1083. fShmControl.data = nullptr;
  1084. }
  1085. if (carla_is_shm_valid(fShmAudioPool.shm))
  1086. carla_shm_close(fShmAudioPool.shm);
  1087. if (carla_is_shm_valid(fShmControl.shm))
  1088. carla_shm_close(fShmControl.shm);
  1089. }
  1090. void resizeAudioPool(const uint32_t bufferSize)
  1091. {
  1092. if (fShmAudioPool.data != nullptr)
  1093. carla_shm_unmap(fShmAudioPool.shm, fShmAudioPool.data, fShmAudioPool.size);
  1094. fShmAudioPool.size = (fInfo.aIns+fInfo.aOuts)*bufferSize*sizeof(float);
  1095. if (fShmAudioPool.size > 0)
  1096. fShmAudioPool.data = (float*)carla_shm_map(fShmAudioPool.shm, fShmAudioPool.size);
  1097. else
  1098. fShmAudioPool.data = nullptr;
  1099. }
  1100. void waitForServer()
  1101. {
  1102. sem_post(&fShmControl.data->runServer);
  1103. #ifdef CARLA_OS_MAC
  1104. alarm(5);
  1105. if (sem_wait(&fShmControl.data->runClient) == EINTR)
  1106. {
  1107. #else
  1108. timespec timeout;
  1109. # ifdef CARLA_OS_WIN
  1110. timeval now;
  1111. gettimeofday(&now, nullptr);
  1112. ts_timeout.tv_sec = now.tv_sec;
  1113. ts_timeout.tv_nsec = now.tv_usec * 1000;
  1114. # else
  1115. clock_gettime(CLOCK_REALTIME, &timeout);
  1116. # endif
  1117. timeout.tv_sec += 5;
  1118. if (sem_timedwait(&fShmControl.data->runClient, &timeout) != 0)
  1119. {
  1120. #endif
  1121. kData->active = false; // TODO
  1122. }
  1123. }
  1124. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(BridgePlugin)
  1125. };
  1126. CARLA_BACKEND_END_NAMESPACE
  1127. #endif // ! BUILD_BRIDGE
  1128. CARLA_BACKEND_START_NAMESPACE
  1129. CarlaPlugin* CarlaPlugin::newBridge(const Initializer& init, BinaryType btype, PluginType ptype, const char* const bridgeBinary)
  1130. {
  1131. carla_debug("CarlaPlugin::newBridge({%p, \"%s\", \"%s\", \"%s\"}, %s, %s, \"%s\")", init.engine, init.filename, init.name, init.label, BinaryType2Str(btype), PluginType2Str(ptype), bridgeBinary);
  1132. #ifndef BUILD_BRIDGE
  1133. if (bridgeBinary == nullptr)
  1134. {
  1135. init.engine->setLastError("Bridge not possible, bridge-binary not found");
  1136. return nullptr;
  1137. }
  1138. BridgePlugin* const plugin(new BridgePlugin(init.engine, init.id, btype, ptype));
  1139. if (! plugin->init(init.filename, init.name, init.label, bridgeBinary))
  1140. {
  1141. delete plugin;
  1142. return nullptr;
  1143. }
  1144. plugin->reload();
  1145. if (init.engine->getProccessMode() == PROCESS_MODE_CONTINUOUS_RACK && ! CarlaPluginProtectedData::canRunInRack(plugin))
  1146. {
  1147. init.engine->setLastError("Carla's rack mode can only work with Stereo Bridged plugins, sorry!");
  1148. delete plugin;
  1149. return nullptr;
  1150. }
  1151. return plugin;
  1152. #else
  1153. init.engine->setLastError("Plugin bridge support not available");
  1154. return nullptr;
  1155. // unused
  1156. (void)bridgeBinary;
  1157. #endif
  1158. }
  1159. #ifndef BUILD_BRIDGE
  1160. // -------------------------------------------------------------------
  1161. // Bridge Helper
  1162. int CarlaPluginSetOscBridgeInfo(CarlaPlugin* const plugin, const PluginBridgeInfoType type,
  1163. const int argc, const lo_arg* const* const argv, const char* const types)
  1164. {
  1165. CARLA_ASSERT(plugin != nullptr && (plugin->hints() & PLUGIN_IS_BRIDGE) != 0);
  1166. return ((BridgePlugin*)plugin)->setOscPluginBridgeInfo(type, argc, argv, types);
  1167. }
  1168. BinaryType CarlaPluginGetBridgeBinaryType(CarlaPlugin* const plugin)
  1169. {
  1170. CARLA_ASSERT(plugin != nullptr && (plugin->hints() & PLUGIN_IS_BRIDGE) != 0);
  1171. return ((BridgePlugin*)plugin)->binaryType();
  1172. }
  1173. #endif
  1174. CARLA_BACKEND_END_NAMESPACE