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.

1475 lines
43KB

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