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.

7259 lines
266KB

  1. /*
  2. * Carla LV2 Plugin
  3. * Copyright (C) 2011-2019 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. // testing macros
  18. // #define LV2_UIS_ONLY_BRIDGES
  19. // #define LV2_UIS_ONLY_INPROCESS
  20. #include "CarlaPluginInternal.hpp"
  21. #include "CarlaEngine.hpp"
  22. #include "CarlaLv2Utils.hpp"
  23. #include "CarlaBackendUtils.hpp"
  24. #include "CarlaBase64Utils.hpp"
  25. #include "CarlaEngineUtils.hpp"
  26. #include "CarlaPipeUtils.hpp"
  27. #include "CarlaPluginUI.hpp"
  28. #include "CarlaScopeUtils.hpp"
  29. #include "Lv2AtomRingBuffer.hpp"
  30. #include "../modules/lilv/config/lilv_config.h"
  31. extern "C" {
  32. #include "rtmempool/rtmempool-lv2.h"
  33. }
  34. #include "water/files/File.h"
  35. #include "water/misc/Time.h"
  36. #include <string>
  37. #include <vector>
  38. using water::File;
  39. #define URI_CARLA_ATOM_WORKER_IN "http://kxstudio.sf.net/ns/carla/atomWorkerIn"
  40. #define URI_CARLA_ATOM_WORKER_RESP "http://kxstudio.sf.net/ns/carla/atomWorkerResp"
  41. CARLA_BACKEND_START_NAMESPACE
  42. // -------------------------------------------------------------------------------------------------------------------
  43. // Fallback data
  44. static const CustomData kCustomDataFallback = { nullptr, nullptr, nullptr };
  45. static /* */ CustomData kCustomDataFallbackNC = { nullptr, nullptr, nullptr };
  46. static const ExternalMidiNote kExternalMidiNoteFallback = { -1, 0, 0 };
  47. static const char* const kUnmapFallback = "urn:null";
  48. // -------------------------------------------------------------------------------------------------------------------
  49. // Maximum default buffer size
  50. const uint MAX_DEFAULT_BUFFER_SIZE = 8192; // 0x2000
  51. // Extra Plugin Hints
  52. const uint PLUGIN_HAS_EXTENSION_OPTIONS = 0x01000;
  53. const uint PLUGIN_HAS_EXTENSION_PROGRAMS = 0x02000;
  54. const uint PLUGIN_HAS_EXTENSION_STATE = 0x04000;
  55. const uint PLUGIN_HAS_EXTENSION_WORKER = 0x08000;
  56. const uint PLUGIN_HAS_EXTENSION_INLINE_DISPLAY = 0x10000;
  57. const uint PLUGIN_HAS_EXTENSION_MIDNAM = 0x20000;
  58. // LV2 Event Data/Types
  59. const uint CARLA_EVENT_DATA_ATOM = 0x01;
  60. const uint CARLA_EVENT_DATA_EVENT = 0x02;
  61. const uint CARLA_EVENT_DATA_MIDI_LL = 0x04;
  62. const uint CARLA_EVENT_TYPE_MESSAGE = 0x10; // unused
  63. const uint CARLA_EVENT_TYPE_MIDI = 0x20;
  64. const uint CARLA_EVENT_TYPE_TIME = 0x40;
  65. // LV2 URI Map Ids
  66. enum CarlaLv2URIDs {
  67. kUridNull = 0,
  68. kUridAtomBlank,
  69. kUridAtomBool,
  70. kUridAtomChunk,
  71. kUridAtomDouble,
  72. kUridAtomEvent,
  73. kUridAtomFloat,
  74. kUridAtomInt,
  75. kUridAtomLiteral,
  76. kUridAtomLong,
  77. kUridAtomNumber,
  78. kUridAtomObject,
  79. kUridAtomPath,
  80. kUridAtomProperty,
  81. kUridAtomResource,
  82. kUridAtomSequence,
  83. kUridAtomSound,
  84. kUridAtomString,
  85. kUridAtomTuple,
  86. kUridAtomURI,
  87. kUridAtomURID,
  88. kUridAtomVector,
  89. kUridAtomTransferAtom,
  90. kUridAtomTransferEvent,
  91. kUridBufMaxLength,
  92. kUridBufMinLength,
  93. kUridBufNominalLength,
  94. kUridBufSequenceSize,
  95. kUridLogError,
  96. kUridLogNote,
  97. kUridLogTrace,
  98. kUridLogWarning,
  99. kUridPatchSet,
  100. kUridPatchPoperty,
  101. kUridPatchValue,
  102. // time base type
  103. kUridTimePosition,
  104. // time values
  105. kUridTimeBar,
  106. kUridTimeBarBeat,
  107. kUridTimeBeat,
  108. kUridTimeBeatUnit,
  109. kUridTimeBeatsPerBar,
  110. kUridTimeBeatsPerMinute,
  111. kUridTimeFrame,
  112. kUridTimeFramesPerSecond,
  113. kUridTimeSpeed,
  114. kUridTimeTicksPerBeat,
  115. kUridMidiEvent,
  116. kUridParamSampleRate,
  117. // ui stuff
  118. kUridBackgroundColor,
  119. kUridForegroundColor,
  120. kUridScaleFactor,
  121. kUridWindowTitle,
  122. // custom carla props
  123. kUridCarlaAtomWorkerIn,
  124. kUridCarlaAtomWorkerResp,
  125. kUridCarlaTransientWindowId,
  126. // count
  127. kUridCount
  128. };
  129. // LV2 Feature Ids
  130. enum CarlaLv2Features {
  131. // DSP features
  132. kFeatureIdBufSizeBounded = 0,
  133. kFeatureIdBufSizeFixed,
  134. kFeatureIdBufSizePowerOf2,
  135. kFeatureIdEvent,
  136. kFeatureIdHardRtCapable,
  137. kFeatureIdInPlaceBroken,
  138. kFeatureIdIsLive,
  139. kFeatureIdLogs,
  140. kFeatureIdOptions,
  141. kFeatureIdPrograms,
  142. kFeatureIdResizePort,
  143. kFeatureIdRtMemPool,
  144. kFeatureIdRtMemPoolOld,
  145. kFeatureIdStateMakePath,
  146. kFeatureIdStateMapPath,
  147. kFeatureIdStrictBounds,
  148. kFeatureIdUriMap,
  149. kFeatureIdUridMap,
  150. kFeatureIdUridUnmap,
  151. kFeatureIdWorker,
  152. kFeatureIdInlineDisplay,
  153. kFeatureIdMidnam,
  154. kFeatureCountPlugin,
  155. // UI features
  156. kFeatureIdUiDataAccess = kFeatureCountPlugin,
  157. kFeatureIdUiInstanceAccess,
  158. kFeatureIdUiIdleInterface,
  159. kFeatureIdUiFixedSize,
  160. kFeatureIdUiMakeResident,
  161. kFeatureIdUiMakeResident2,
  162. kFeatureIdUiNoUserResize,
  163. kFeatureIdUiParent,
  164. kFeatureIdUiPortMap,
  165. kFeatureIdUiPortSubscribe,
  166. kFeatureIdUiResize,
  167. kFeatureIdUiTouch,
  168. kFeatureIdExternalUi,
  169. kFeatureIdExternalUiOld,
  170. kFeatureCountAll
  171. };
  172. // -------------------------------------------------------------------------------------------------------------------
  173. struct Lv2EventData {
  174. uint32_t type;
  175. uint32_t rindex;
  176. CarlaEngineEventPort* port;
  177. union {
  178. LV2_Atom_Buffer* atom;
  179. LV2_Event_Buffer* event;
  180. LV2_MIDI midi;
  181. };
  182. Lv2EventData() noexcept
  183. : type(0x0),
  184. rindex(0),
  185. port(nullptr) {}
  186. ~Lv2EventData() noexcept
  187. {
  188. if (port != nullptr)
  189. {
  190. delete port;
  191. port = nullptr;
  192. }
  193. const uint32_t rtype(type);
  194. type = 0x0;
  195. if (rtype & CARLA_EVENT_DATA_ATOM)
  196. {
  197. CARLA_SAFE_ASSERT_RETURN(atom != nullptr,);
  198. std::free(atom);
  199. atom = nullptr;
  200. }
  201. else if (rtype & CARLA_EVENT_DATA_EVENT)
  202. {
  203. CARLA_SAFE_ASSERT_RETURN(event != nullptr,);
  204. std::free(event);
  205. event = nullptr;
  206. }
  207. else if (rtype & CARLA_EVENT_DATA_MIDI_LL)
  208. {
  209. CARLA_SAFE_ASSERT_RETURN(midi.data != nullptr,);
  210. delete[] midi.data;
  211. midi.data = nullptr;
  212. }
  213. }
  214. CARLA_DECLARE_NON_COPY_STRUCT(Lv2EventData)
  215. };
  216. struct CarlaPluginLV2EventData {
  217. uint32_t count;
  218. Lv2EventData* data;
  219. Lv2EventData* ctrl; // default port, either this->data[x] or pData->portIn/Out
  220. uint32_t ctrlIndex;
  221. CarlaPluginLV2EventData() noexcept
  222. : count(0),
  223. data(nullptr),
  224. ctrl(nullptr),
  225. ctrlIndex(0) {}
  226. ~CarlaPluginLV2EventData() noexcept
  227. {
  228. CARLA_SAFE_ASSERT_INT(count == 0, count);
  229. CARLA_SAFE_ASSERT(data == nullptr);
  230. CARLA_SAFE_ASSERT(ctrl == nullptr);
  231. CARLA_SAFE_ASSERT_INT(ctrlIndex == 0, ctrlIndex);
  232. }
  233. void createNew(const uint32_t newCount)
  234. {
  235. CARLA_SAFE_ASSERT_INT(count == 0, count);
  236. CARLA_SAFE_ASSERT_INT(ctrlIndex == 0, ctrlIndex);
  237. CARLA_SAFE_ASSERT_RETURN(data == nullptr,);
  238. CARLA_SAFE_ASSERT_RETURN(ctrl == nullptr,);
  239. CARLA_SAFE_ASSERT_RETURN(newCount > 0,);
  240. data = new Lv2EventData[newCount];
  241. count = newCount;
  242. ctrl = nullptr;
  243. ctrlIndex = 0;
  244. }
  245. void clear() noexcept
  246. {
  247. if (data != nullptr)
  248. {
  249. for (uint32_t i=0; i < count; ++i)
  250. {
  251. if (data[i].port != nullptr && ctrl != nullptr && data[i].port == ctrl->port)
  252. data[i].port = nullptr;
  253. }
  254. delete[] data;
  255. data = nullptr;
  256. }
  257. count = 0;
  258. ctrl = nullptr;
  259. ctrlIndex = 0;
  260. }
  261. void initBuffers() const noexcept
  262. {
  263. for (uint32_t i=0; i < count; ++i)
  264. {
  265. if (data[i].port != nullptr && (ctrl == nullptr || data[i].port != ctrl->port))
  266. data[i].port->initBuffer();
  267. }
  268. }
  269. CARLA_DECLARE_NON_COPY_STRUCT(CarlaPluginLV2EventData)
  270. };
  271. // -------------------------------------------------------------------------------------------------------------------
  272. struct CarlaPluginLV2Options {
  273. enum OptIndex {
  274. MaxBlockLenth = 0,
  275. MinBlockLenth,
  276. NominalBlockLenth,
  277. SequenceSize,
  278. SampleRate,
  279. TransientWinId,
  280. BackgroundColor,
  281. ForegroundColor,
  282. ScaleFactor,
  283. WindowTitle,
  284. Null,
  285. Count
  286. };
  287. int maxBufferSize;
  288. int minBufferSize;
  289. int nominalBufferSize;
  290. int sequenceSize;
  291. float sampleRate;
  292. int64_t transientWinId;
  293. uint32_t bgColor;
  294. uint32_t fgColor;
  295. float uiScale;
  296. const char* windowTitle;
  297. LV2_Options_Option opts[Count];
  298. CarlaPluginLV2Options() noexcept
  299. : maxBufferSize(0),
  300. minBufferSize(0),
  301. nominalBufferSize(0),
  302. sequenceSize(MAX_DEFAULT_BUFFER_SIZE),
  303. sampleRate(0.0),
  304. transientWinId(0),
  305. bgColor(0x000000ff),
  306. fgColor(0xffffffff),
  307. uiScale(1.0f),
  308. windowTitle(nullptr)
  309. {
  310. LV2_Options_Option& optMaxBlockLenth(opts[MaxBlockLenth]);
  311. optMaxBlockLenth.context = LV2_OPTIONS_INSTANCE;
  312. optMaxBlockLenth.subject = 0;
  313. optMaxBlockLenth.key = kUridBufMaxLength;
  314. optMaxBlockLenth.size = sizeof(int);
  315. optMaxBlockLenth.type = kUridAtomInt;
  316. optMaxBlockLenth.value = &maxBufferSize;
  317. LV2_Options_Option& optMinBlockLenth(opts[MinBlockLenth]);
  318. optMinBlockLenth.context = LV2_OPTIONS_INSTANCE;
  319. optMinBlockLenth.subject = 0;
  320. optMinBlockLenth.key = kUridBufMinLength;
  321. optMinBlockLenth.size = sizeof(int);
  322. optMinBlockLenth.type = kUridAtomInt;
  323. optMinBlockLenth.value = &minBufferSize;
  324. LV2_Options_Option& optNominalBlockLenth(opts[NominalBlockLenth]);
  325. optNominalBlockLenth.context = LV2_OPTIONS_INSTANCE;
  326. optNominalBlockLenth.subject = 0;
  327. optNominalBlockLenth.key = kUridBufNominalLength;
  328. optNominalBlockLenth.size = sizeof(int);
  329. optNominalBlockLenth.type = kUridAtomInt;
  330. optNominalBlockLenth.value = &nominalBufferSize;
  331. LV2_Options_Option& optSequenceSize(opts[SequenceSize]);
  332. optSequenceSize.context = LV2_OPTIONS_INSTANCE;
  333. optSequenceSize.subject = 0;
  334. optSequenceSize.key = kUridBufSequenceSize;
  335. optSequenceSize.size = sizeof(int);
  336. optSequenceSize.type = kUridAtomInt;
  337. optSequenceSize.value = &sequenceSize;
  338. LV2_Options_Option& optBackgroundColor(opts[BackgroundColor]);
  339. optBackgroundColor.context = LV2_OPTIONS_INSTANCE;
  340. optBackgroundColor.subject = 0;
  341. optBackgroundColor.key = kUridBackgroundColor;
  342. optBackgroundColor.size = sizeof(int32_t);
  343. optBackgroundColor.type = kUridAtomInt;
  344. optBackgroundColor.value = &bgColor;
  345. LV2_Options_Option& optForegroundColor(opts[ForegroundColor]);
  346. optForegroundColor.context = LV2_OPTIONS_INSTANCE;
  347. optForegroundColor.subject = 0;
  348. optForegroundColor.key = kUridForegroundColor;
  349. optForegroundColor.size = sizeof(int32_t);
  350. optForegroundColor.type = kUridAtomInt;
  351. optForegroundColor.value = &fgColor;
  352. LV2_Options_Option& optScaleFactor(opts[ScaleFactor]);
  353. optScaleFactor.context = LV2_OPTIONS_INSTANCE;
  354. optScaleFactor.subject = 0;
  355. optScaleFactor.key = kUridScaleFactor;
  356. optScaleFactor.size = sizeof(float);
  357. optScaleFactor.type = kUridAtomFloat;
  358. optScaleFactor.value = &uiScale;
  359. LV2_Options_Option& optSampleRate(opts[SampleRate]);
  360. optSampleRate.context = LV2_OPTIONS_INSTANCE;
  361. optSampleRate.subject = 0;
  362. optSampleRate.key = kUridParamSampleRate;
  363. optSampleRate.size = sizeof(float);
  364. optSampleRate.type = kUridAtomFloat;
  365. optSampleRate.value = &sampleRate;
  366. LV2_Options_Option& optTransientWinId(opts[TransientWinId]);
  367. optTransientWinId.context = LV2_OPTIONS_INSTANCE;
  368. optTransientWinId.subject = 0;
  369. optTransientWinId.key = kUridCarlaTransientWindowId;
  370. optTransientWinId.size = sizeof(int64_t);
  371. optTransientWinId.type = kUridAtomLong;
  372. optTransientWinId.value = &transientWinId;
  373. LV2_Options_Option& optWindowTitle(opts[WindowTitle]);
  374. optWindowTitle.context = LV2_OPTIONS_INSTANCE;
  375. optWindowTitle.subject = 0;
  376. optWindowTitle.key = kUridWindowTitle;
  377. optWindowTitle.size = 0;
  378. optWindowTitle.type = kUridAtomString;
  379. optWindowTitle.value = nullptr;
  380. LV2_Options_Option& optNull(opts[Null]);
  381. optNull.context = LV2_OPTIONS_INSTANCE;
  382. optNull.subject = 0;
  383. optNull.key = kUridNull;
  384. optNull.size = 0;
  385. optNull.type = kUridNull;
  386. optNull.value = nullptr;
  387. }
  388. ~CarlaPluginLV2Options() noexcept
  389. {
  390. LV2_Options_Option& optWindowTitle(opts[WindowTitle]);
  391. optWindowTitle.size = 0;
  392. optWindowTitle.value = nullptr;
  393. if (windowTitle != nullptr)
  394. {
  395. delete[] windowTitle;
  396. windowTitle = nullptr;
  397. }
  398. }
  399. CARLA_DECLARE_NON_COPY_STRUCT(CarlaPluginLV2Options);
  400. };
  401. // -------------------------------------------------------------------------------------------------------------------
  402. class CarlaPluginLV2;
  403. class CarlaPipeServerLV2 : public CarlaPipeServer
  404. {
  405. public:
  406. enum UiState {
  407. UiNone = 0,
  408. UiHide,
  409. UiShow,
  410. UiCrashed
  411. };
  412. CarlaPipeServerLV2(CarlaEngine* const engine, CarlaPluginLV2* const plugin)
  413. : kEngine(engine),
  414. kPlugin(plugin),
  415. fFilename(),
  416. fPluginURI(),
  417. fUiURI(),
  418. fUiState(UiNone) {}
  419. ~CarlaPipeServerLV2() noexcept override
  420. {
  421. CARLA_SAFE_ASSERT_INT(fUiState == UiNone, fUiState);
  422. }
  423. UiState getAndResetUiState() noexcept
  424. {
  425. const UiState uiState(fUiState);
  426. fUiState = UiNone;
  427. return uiState;
  428. }
  429. void setData(const char* const filename, const char* const pluginURI, const char* const uiURI) noexcept
  430. {
  431. fFilename = filename;
  432. fPluginURI = pluginURI;
  433. fUiURI = uiURI;
  434. }
  435. bool startPipeServer(const int size) noexcept
  436. {
  437. char sampleRateStr[32];
  438. {
  439. const CarlaScopedLocale csl;
  440. std::snprintf(sampleRateStr, 31, "%.12g", kEngine->getSampleRate());
  441. }
  442. sampleRateStr[31] = '\0';
  443. const ScopedEngineEnvironmentLocker _seel(kEngine);
  444. const CarlaScopedEnvVar _sev1("LV2_PATH", kEngine->getOptions().pathLV2);
  445. #ifdef CARLA_OS_LINUX
  446. const CarlaScopedEnvVar _sev2("LD_PRELOAD", nullptr);
  447. #endif
  448. carla_setenv("CARLA_SAMPLE_RATE", sampleRateStr);
  449. return CarlaPipeServer::startPipeServer(fFilename, fPluginURI, fUiURI, size);
  450. }
  451. void writeUiTitleMessage(const char* const title) const noexcept
  452. {
  453. CARLA_SAFE_ASSERT_RETURN(title != nullptr && title[0] != '\0',);
  454. const CarlaMutexLocker cml(getPipeLock());
  455. if (! _writeMsgBuffer("uiTitle\n", 8))
  456. return;
  457. if (! writeAndFixMessage(title))
  458. return;
  459. flushMessages();
  460. }
  461. protected:
  462. // returns true if msg was handled
  463. bool msgReceived(const char* const msg) noexcept override;
  464. private:
  465. CarlaEngine* const kEngine;
  466. CarlaPluginLV2* const kPlugin;
  467. CarlaString fFilename;
  468. CarlaString fPluginURI;
  469. CarlaString fUiURI;
  470. UiState fUiState;
  471. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPipeServerLV2)
  472. };
  473. // -------------------------------------------------------------------------------------------------------------------
  474. class CarlaPluginLV2 : public CarlaPlugin,
  475. private CarlaPluginUI::Callback
  476. {
  477. public:
  478. CarlaPluginLV2(CarlaEngine* const engine, const uint id)
  479. : CarlaPlugin(engine, id),
  480. fHandle(nullptr),
  481. fHandle2(nullptr),
  482. fDescriptor(nullptr),
  483. fRdfDescriptor(nullptr),
  484. fAudioInBuffers(nullptr),
  485. fAudioOutBuffers(nullptr),
  486. fCvInBuffers(nullptr),
  487. fCvOutBuffers(nullptr),
  488. fParamBuffers(nullptr),
  489. fNeedsFixedBuffers(false),
  490. fNeedsUiClose(false),
  491. fInlineDisplayNeedsRedraw(false),
  492. fInlineDisplayLastRedrawTime(0),
  493. fLatencyIndex(-1),
  494. fStrictBounds(-1),
  495. fAtomBufferEvIn(),
  496. fAtomBufferUiOut(),
  497. fAtomBufferWorkerIn(),
  498. fAtomBufferWorkerResp(),
  499. fAtomForge(),
  500. fAtomBufferUiOutTmpData(nullptr),
  501. fAtomBufferWorkerInTmpData(nullptr),
  502. fEventsIn(),
  503. fEventsOut(),
  504. fLv2Options(),
  505. fPipeServer(engine, this),
  506. fCustomURIDs(kUridCount, std::string("urn:null")),
  507. fFirstActive(true),
  508. fLastStateChunk(nullptr),
  509. fLastTimeInfo(),
  510. fFilePathURI(),
  511. fExt(),
  512. fUI()
  513. {
  514. carla_debug("CarlaPluginLV2::CarlaPluginLV2(%p, %i)", engine, id);
  515. CARLA_SAFE_ASSERT(fCustomURIDs.size() == kUridCount);
  516. carla_zeroPointers(fFeatures, kFeatureCountAll+1);
  517. #if defined(__clang__)
  518. # pragma clang diagnostic push
  519. # pragma clang diagnostic ignored "-Wdeprecated-declarations"
  520. #elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
  521. # pragma GCC diagnostic push
  522. # pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  523. #endif
  524. fAtomForge.Blank = kUridAtomBlank;
  525. fAtomForge.Bool = kUridAtomBool;
  526. fAtomForge.Chunk = kUridAtomChunk;
  527. fAtomForge.Double = kUridAtomDouble;
  528. fAtomForge.Float = kUridAtomFloat;
  529. fAtomForge.Int = kUridAtomInt;
  530. fAtomForge.Literal = kUridAtomLiteral;
  531. fAtomForge.Long = kUridAtomLong;
  532. fAtomForge.Object = kUridAtomObject;
  533. fAtomForge.Path = kUridAtomPath;
  534. fAtomForge.Property = kUridAtomProperty;
  535. fAtomForge.Resource = kUridAtomResource;
  536. fAtomForge.Sequence = kUridAtomSequence;
  537. fAtomForge.String = kUridAtomString;
  538. fAtomForge.Tuple = kUridAtomTuple;
  539. fAtomForge.URI = kUridAtomURI;
  540. fAtomForge.URID = kUridAtomURID;
  541. fAtomForge.Vector = kUridAtomVector;
  542. #if defined(__clang__)
  543. # pragma clang diagnostic pop
  544. #elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
  545. # pragma GCC diagnostic pop
  546. #endif
  547. }
  548. ~CarlaPluginLV2() override
  549. {
  550. carla_debug("CarlaPluginLV2::~CarlaPluginLV2()");
  551. fInlineDisplayNeedsRedraw = false;
  552. // close UI
  553. if (fUI.type != UI::TYPE_NULL)
  554. {
  555. showCustomUI(false);
  556. if (fUI.type == UI::TYPE_BRIDGE)
  557. {
  558. fPipeServer.stopPipeServer(pData->engine->getOptions().uiBridgesTimeout);
  559. }
  560. else
  561. {
  562. if (fFeatures[kFeatureIdUiDataAccess] != nullptr && fFeatures[kFeatureIdUiDataAccess]->data != nullptr)
  563. delete (LV2_Extension_Data_Feature*)fFeatures[kFeatureIdUiDataAccess]->data;
  564. if (fFeatures[kFeatureIdUiPortMap] != nullptr && fFeatures[kFeatureIdUiPortMap]->data != nullptr)
  565. delete (LV2UI_Port_Map*)fFeatures[kFeatureIdUiPortMap]->data;
  566. if (fFeatures[kFeatureIdUiResize] != nullptr && fFeatures[kFeatureIdUiResize]->data != nullptr)
  567. delete (LV2UI_Resize*)fFeatures[kFeatureIdUiResize]->data;
  568. if (fFeatures[kFeatureIdUiTouch] != nullptr && fFeatures[kFeatureIdUiTouch]->data != nullptr)
  569. delete (LV2UI_Touch*)fFeatures[kFeatureIdUiTouch]->data;
  570. if (fFeatures[kFeatureIdExternalUi] != nullptr && fFeatures[kFeatureIdExternalUi]->data != nullptr)
  571. delete (LV2_External_UI_Host*)fFeatures[kFeatureIdExternalUi]->data;
  572. fUI.descriptor = nullptr;
  573. pData->uiLibClose();
  574. }
  575. #ifndef LV2_UIS_ONLY_BRIDGES
  576. if (fUI.window != nullptr)
  577. {
  578. delete fUI.window;
  579. fUI.window = nullptr;
  580. }
  581. #endif
  582. fUI.rdfDescriptor = nullptr;
  583. }
  584. pData->singleMutex.lock();
  585. pData->masterMutex.lock();
  586. if (pData->client != nullptr && pData->client->isActive())
  587. pData->client->deactivate();
  588. if (pData->active)
  589. {
  590. deactivate();
  591. pData->active = false;
  592. }
  593. if (fDescriptor != nullptr)
  594. {
  595. if (fDescriptor->cleanup != nullptr)
  596. {
  597. if (fHandle != nullptr)
  598. fDescriptor->cleanup(fHandle);
  599. if (fHandle2 != nullptr)
  600. fDescriptor->cleanup(fHandle2);
  601. }
  602. fHandle = nullptr;
  603. fHandle2 = nullptr;
  604. fDescriptor = nullptr;
  605. }
  606. if (fRdfDescriptor != nullptr)
  607. {
  608. delete fRdfDescriptor;
  609. fRdfDescriptor = nullptr;
  610. }
  611. if (fFeatures[kFeatureIdEvent] != nullptr && fFeatures[kFeatureIdEvent]->data != nullptr)
  612. delete (LV2_Event_Feature*)fFeatures[kFeatureIdEvent]->data;
  613. if (fFeatures[kFeatureIdLogs] != nullptr && fFeatures[kFeatureIdLogs]->data != nullptr)
  614. delete (LV2_Log_Log*)fFeatures[kFeatureIdLogs]->data;
  615. if (fFeatures[kFeatureIdStateMakePath] != nullptr && fFeatures[kFeatureIdStateMakePath]->data != nullptr)
  616. delete (LV2_State_Make_Path*)fFeatures[kFeatureIdStateMakePath]->data;
  617. if (fFeatures[kFeatureIdStateMapPath] != nullptr && fFeatures[kFeatureIdStateMapPath]->data != nullptr)
  618. delete (LV2_State_Map_Path*)fFeatures[kFeatureIdStateMapPath]->data;
  619. if (fFeatures[kFeatureIdPrograms] != nullptr && fFeatures[kFeatureIdPrograms]->data != nullptr)
  620. delete (LV2_Programs_Host*)fFeatures[kFeatureIdPrograms]->data;
  621. if (fFeatures[kFeatureIdResizePort] != nullptr && fFeatures[kFeatureIdResizePort]->data != nullptr)
  622. delete (LV2_Resize_Port_Resize*)fFeatures[kFeatureIdResizePort]->data;
  623. if (fFeatures[kFeatureIdRtMemPool] != nullptr && fFeatures[kFeatureIdRtMemPool]->data != nullptr)
  624. delete (LV2_RtMemPool_Pool*)fFeatures[kFeatureIdRtMemPool]->data;
  625. if (fFeatures[kFeatureIdRtMemPoolOld] != nullptr && fFeatures[kFeatureIdRtMemPoolOld]->data != nullptr)
  626. delete (LV2_RtMemPool_Pool_Deprecated*)fFeatures[kFeatureIdRtMemPoolOld]->data;
  627. if (fFeatures[kFeatureIdUriMap] != nullptr && fFeatures[kFeatureIdUriMap]->data != nullptr)
  628. delete (LV2_URI_Map_Feature*)fFeatures[kFeatureIdUriMap]->data;
  629. if (fFeatures[kFeatureIdUridMap] != nullptr && fFeatures[kFeatureIdUridMap]->data != nullptr)
  630. delete (LV2_URID_Map*)fFeatures[kFeatureIdUridMap]->data;
  631. if (fFeatures[kFeatureIdUridUnmap] != nullptr && fFeatures[kFeatureIdUridUnmap]->data != nullptr)
  632. delete (LV2_URID_Unmap*)fFeatures[kFeatureIdUridUnmap]->data;
  633. if (fFeatures[kFeatureIdWorker] != nullptr && fFeatures[kFeatureIdWorker]->data != nullptr)
  634. delete (LV2_Worker_Schedule*)fFeatures[kFeatureIdWorker]->data;
  635. if (fFeatures[kFeatureIdInlineDisplay] != nullptr && fFeatures[kFeatureIdInlineDisplay]->data != nullptr)
  636. delete (LV2_Inline_Display*)fFeatures[kFeatureIdInlineDisplay]->data;
  637. for (uint32_t i=0; i < kFeatureCountAll; ++i)
  638. {
  639. if (fFeatures[i] != nullptr)
  640. {
  641. delete fFeatures[i];
  642. fFeatures[i] = nullptr;
  643. }
  644. }
  645. if (fLastStateChunk != nullptr)
  646. {
  647. std::free(fLastStateChunk);
  648. fLastStateChunk = nullptr;
  649. }
  650. if (fAtomBufferUiOutTmpData != nullptr)
  651. {
  652. delete[] fAtomBufferUiOutTmpData;
  653. fAtomBufferUiOutTmpData = nullptr;
  654. }
  655. if (fAtomBufferWorkerInTmpData != nullptr)
  656. {
  657. delete[] fAtomBufferWorkerInTmpData;
  658. fAtomBufferWorkerInTmpData = nullptr;
  659. }
  660. clearBuffers();
  661. }
  662. // -------------------------------------------------------------------
  663. // Information (base)
  664. PluginType getType() const noexcept override
  665. {
  666. return PLUGIN_LV2;
  667. }
  668. PluginCategory getCategory() const noexcept override
  669. {
  670. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr, CarlaPlugin::getCategory());
  671. const LV2_Property cat1(fRdfDescriptor->Type[0]);
  672. const LV2_Property cat2(fRdfDescriptor->Type[1]);
  673. if (LV2_IS_DELAY(cat1, cat2))
  674. return PLUGIN_CATEGORY_DELAY;
  675. if (LV2_IS_DISTORTION(cat1, cat2))
  676. return PLUGIN_CATEGORY_OTHER;
  677. if (LV2_IS_DYNAMICS(cat1, cat2))
  678. return PLUGIN_CATEGORY_DYNAMICS;
  679. if (LV2_IS_EQ(cat1, cat2))
  680. return PLUGIN_CATEGORY_EQ;
  681. if (LV2_IS_FILTER(cat1, cat2))
  682. return PLUGIN_CATEGORY_FILTER;
  683. if (LV2_IS_GENERATOR(cat1, cat2))
  684. return PLUGIN_CATEGORY_SYNTH;
  685. if (LV2_IS_MODULATOR(cat1, cat2))
  686. return PLUGIN_CATEGORY_MODULATOR;
  687. if (LV2_IS_REVERB(cat1, cat2))
  688. return PLUGIN_CATEGORY_DELAY;
  689. if (LV2_IS_SIMULATOR(cat1, cat2))
  690. return PLUGIN_CATEGORY_OTHER;
  691. if (LV2_IS_SPATIAL(cat1, cat2))
  692. return PLUGIN_CATEGORY_OTHER;
  693. if (LV2_IS_SPECTRAL(cat1, cat2))
  694. return PLUGIN_CATEGORY_UTILITY;
  695. if (LV2_IS_UTILITY(cat1, cat2))
  696. return PLUGIN_CATEGORY_UTILITY;
  697. return CarlaPlugin::getCategory();
  698. }
  699. uint32_t getLatencyInFrames() const noexcept override
  700. {
  701. if (fLatencyIndex < 0 || fParamBuffers == nullptr)
  702. return 0;
  703. const float latency(fParamBuffers[fLatencyIndex]);
  704. CARLA_SAFE_ASSERT_RETURN(latency >= 0.0f, 0);
  705. return static_cast<uint32_t>(latency);
  706. }
  707. // -------------------------------------------------------------------
  708. // Information (count)
  709. uint32_t getMidiInCount() const noexcept override
  710. {
  711. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr, 0);
  712. uint32_t count = 0;
  713. for (uint32_t i=0; i < fRdfDescriptor->PortCount; ++i)
  714. {
  715. const LV2_Property portTypes(fRdfDescriptor->Ports[i].Types);
  716. if (LV2_IS_PORT_INPUT(portTypes) && LV2_PORT_SUPPORTS_MIDI_EVENT(portTypes))
  717. ++count;
  718. }
  719. return count;
  720. }
  721. uint32_t getMidiOutCount() const noexcept override
  722. {
  723. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr, 0);
  724. uint32_t count = 0;
  725. for (uint32_t i=0; i < fRdfDescriptor->PortCount; ++i)
  726. {
  727. const LV2_Property portTypes(fRdfDescriptor->Ports[i].Types);
  728. if (LV2_IS_PORT_OUTPUT(portTypes) && LV2_PORT_SUPPORTS_MIDI_EVENT(portTypes))
  729. ++count;
  730. }
  731. return count;
  732. }
  733. uint32_t getParameterScalePointCount(const uint32_t parameterId) const noexcept override
  734. {
  735. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr, 0);
  736. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, 0);
  737. const int32_t rindex(pData->param.data[parameterId].rindex);
  738. if (rindex < static_cast<int32_t>(fRdfDescriptor->PortCount))
  739. {
  740. const LV2_RDF_Port* const port(&fRdfDescriptor->Ports[rindex]);
  741. return port->ScalePointCount;
  742. }
  743. return 0;
  744. }
  745. // -------------------------------------------------------------------
  746. // Information (current data)
  747. // nothing
  748. // -------------------------------------------------------------------
  749. // Information (per-plugin data)
  750. uint getOptionsAvailable() const noexcept override
  751. {
  752. uint options = 0x0;
  753. // can't disable fixed buffers if using latency or MIDI output
  754. if (fLatencyIndex == -1 && getMidiOutCount() == 0 && ! fNeedsFixedBuffers)
  755. options |= PLUGIN_OPTION_FIXED_BUFFERS;
  756. // can't disable forced stereo if enabled in the engine
  757. if (pData->engine->getOptions().forceStereo)
  758. pass();
  759. // if inputs or outputs are just 1, then yes we can force stereo
  760. else if ((pData->audioIn.count == 1 || pData->audioOut.count == 1) || fHandle2 != nullptr)
  761. options |= PLUGIN_OPTION_FORCE_STEREO;
  762. if (fExt.programs != nullptr)
  763. options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  764. if (getMidiInCount() != 0)
  765. {
  766. options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  767. options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  768. options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  769. options |= PLUGIN_OPTION_SEND_PITCHBEND;
  770. options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  771. options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  772. }
  773. return options;
  774. }
  775. float getParameterValue(const uint32_t parameterId) const noexcept override
  776. {
  777. CARLA_SAFE_ASSERT_RETURN(fParamBuffers != nullptr, 0.0f);
  778. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, 0.0f);
  779. if (pData->param.data[parameterId].type == PARAMETER_INPUT)
  780. {
  781. if (pData->param.data[parameterId].hints & PARAMETER_IS_STRICT_BOUNDS)
  782. pData->param.ranges[parameterId].fixValue(fParamBuffers[parameterId]);
  783. }
  784. else
  785. {
  786. if (fStrictBounds >= 0 && (pData->param.data[parameterId].hints & PARAMETER_IS_STRICT_BOUNDS) == 0)
  787. pData->param.ranges[parameterId].fixValue(fParamBuffers[parameterId]);
  788. }
  789. return fParamBuffers[parameterId];
  790. }
  791. float getParameterScalePointValue(const uint32_t parameterId, const uint32_t scalePointId) const noexcept override
  792. {
  793. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr, 0.0f);
  794. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, 0.0f);
  795. const int32_t rindex(pData->param.data[parameterId].rindex);
  796. if (rindex < static_cast<int32_t>(fRdfDescriptor->PortCount))
  797. {
  798. const LV2_RDF_Port* const port(&fRdfDescriptor->Ports[rindex]);
  799. CARLA_SAFE_ASSERT_RETURN(scalePointId < port->ScalePointCount, 0.0f);
  800. const LV2_RDF_PortScalePoint* const portScalePoint(&port->ScalePoints[scalePointId]);
  801. return portScalePoint->Value;
  802. }
  803. return 0.0f;
  804. }
  805. bool getLabel(char* const strBuf) const noexcept override
  806. {
  807. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr, false);
  808. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor->URI != nullptr, false);
  809. std::strncpy(strBuf, fRdfDescriptor->URI, STR_MAX);
  810. return true;
  811. }
  812. bool getMaker(char* const strBuf) const noexcept override
  813. {
  814. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr, false);
  815. if (fRdfDescriptor->Author != nullptr)
  816. {
  817. std::strncpy(strBuf, fRdfDescriptor->Author, STR_MAX);
  818. return true;
  819. }
  820. return false;
  821. }
  822. bool getCopyright(char* const strBuf) const noexcept override
  823. {
  824. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr, false);
  825. if (fRdfDescriptor->License != nullptr)
  826. {
  827. std::strncpy(strBuf, fRdfDescriptor->License, STR_MAX);
  828. return true;
  829. }
  830. return false;
  831. }
  832. bool getRealName(char* const strBuf) const noexcept override
  833. {
  834. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr, false);
  835. if (fRdfDescriptor->Name != nullptr)
  836. {
  837. std::strncpy(strBuf, fRdfDescriptor->Name, STR_MAX);
  838. return true;
  839. }
  840. return false;
  841. }
  842. bool getParameterName(const uint32_t parameterId, char* const strBuf) const noexcept override
  843. {
  844. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr, false);
  845. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  846. int32_t rindex = pData->param.data[parameterId].rindex;
  847. CARLA_SAFE_ASSERT_RETURN(rindex >= 0, false);
  848. if (rindex < static_cast<int32_t>(fRdfDescriptor->PortCount))
  849. {
  850. std::strncpy(strBuf, fRdfDescriptor->Ports[rindex].Name, STR_MAX);
  851. return true;
  852. }
  853. rindex -= static_cast<int32_t>(fRdfDescriptor->PortCount);
  854. if (rindex < static_cast<int32_t>(fRdfDescriptor->ParameterCount))
  855. {
  856. std::strncpy(strBuf, fRdfDescriptor->Parameters[rindex].Label, STR_MAX);
  857. return true;
  858. }
  859. return CarlaPlugin::getParameterName(parameterId, strBuf);
  860. }
  861. bool getParameterSymbol(const uint32_t parameterId, char* const strBuf) const noexcept override
  862. {
  863. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr, false);
  864. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  865. int32_t rindex = pData->param.data[parameterId].rindex;
  866. CARLA_SAFE_ASSERT_RETURN(rindex >= 0, false);
  867. if (rindex < static_cast<int32_t>(fRdfDescriptor->PortCount))
  868. {
  869. std::strncpy(strBuf, fRdfDescriptor->Ports[rindex].Symbol, STR_MAX);
  870. return true;
  871. }
  872. rindex -= static_cast<int32_t>(fRdfDescriptor->PortCount);
  873. if (rindex < static_cast<int32_t>(fRdfDescriptor->ParameterCount))
  874. {
  875. std::strncpy(strBuf, fRdfDescriptor->Parameters[rindex].URI, STR_MAX);
  876. return true;
  877. }
  878. return CarlaPlugin::getParameterSymbol(parameterId, strBuf);
  879. }
  880. bool getParameterUnit(const uint32_t parameterId, char* const strBuf) const noexcept override
  881. {
  882. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr, false);
  883. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  884. LV2_RDF_PortUnit* portUnit = nullptr;
  885. int32_t rindex = pData->param.data[parameterId].rindex;
  886. CARLA_SAFE_ASSERT_RETURN(rindex >= 0, false);
  887. if (rindex < static_cast<int32_t>(fRdfDescriptor->PortCount))
  888. {
  889. portUnit = &fRdfDescriptor->Ports[rindex].Unit;
  890. }
  891. else
  892. {
  893. rindex -= static_cast<int32_t>(fRdfDescriptor->PortCount);
  894. if (rindex < static_cast<int32_t>(fRdfDescriptor->ParameterCount))
  895. {
  896. portUnit = &fRdfDescriptor->Parameters[rindex].Unit;
  897. }
  898. }
  899. if (portUnit != nullptr)
  900. {
  901. if (LV2_HAVE_PORT_UNIT_SYMBOL(portUnit->Hints) && portUnit->Symbol != nullptr)
  902. {
  903. std::strncpy(strBuf, portUnit->Symbol, STR_MAX);
  904. return true;
  905. }
  906. if (LV2_HAVE_PORT_UNIT_UNIT(portUnit->Hints))
  907. {
  908. switch (portUnit->Unit)
  909. {
  910. case LV2_PORT_UNIT_BAR:
  911. std::strncpy(strBuf, "bars", STR_MAX);
  912. return true;
  913. case LV2_PORT_UNIT_BEAT:
  914. std::strncpy(strBuf, "beats", STR_MAX);
  915. return true;
  916. case LV2_PORT_UNIT_BPM:
  917. std::strncpy(strBuf, "BPM", STR_MAX);
  918. return true;
  919. case LV2_PORT_UNIT_CENT:
  920. std::strncpy(strBuf, "ct", STR_MAX);
  921. return true;
  922. case LV2_PORT_UNIT_CM:
  923. std::strncpy(strBuf, "cm", STR_MAX);
  924. return true;
  925. case LV2_PORT_UNIT_COEF:
  926. std::strncpy(strBuf, "(coef)", STR_MAX);
  927. return true;
  928. case LV2_PORT_UNIT_DB:
  929. std::strncpy(strBuf, "dB", STR_MAX);
  930. return true;
  931. case LV2_PORT_UNIT_DEGREE:
  932. std::strncpy(strBuf, "deg", STR_MAX);
  933. return true;
  934. case LV2_PORT_UNIT_FRAME:
  935. std::strncpy(strBuf, "frames", STR_MAX);
  936. return true;
  937. case LV2_PORT_UNIT_HZ:
  938. std::strncpy(strBuf, "Hz", STR_MAX);
  939. return true;
  940. case LV2_PORT_UNIT_INCH:
  941. std::strncpy(strBuf, "in", STR_MAX);
  942. return true;
  943. case LV2_PORT_UNIT_KHZ:
  944. std::strncpy(strBuf, "kHz", STR_MAX);
  945. return true;
  946. case LV2_PORT_UNIT_KM:
  947. std::strncpy(strBuf, "km", STR_MAX);
  948. return true;
  949. case LV2_PORT_UNIT_M:
  950. std::strncpy(strBuf, "m", STR_MAX);
  951. return true;
  952. case LV2_PORT_UNIT_MHZ:
  953. std::strncpy(strBuf, "MHz", STR_MAX);
  954. return true;
  955. case LV2_PORT_UNIT_MIDINOTE:
  956. std::strncpy(strBuf, "note", STR_MAX);
  957. return true;
  958. case LV2_PORT_UNIT_MILE:
  959. std::strncpy(strBuf, "mi", STR_MAX);
  960. return true;
  961. case LV2_PORT_UNIT_MIN:
  962. std::strncpy(strBuf, "min", STR_MAX);
  963. return true;
  964. case LV2_PORT_UNIT_MM:
  965. std::strncpy(strBuf, "mm", STR_MAX);
  966. return true;
  967. case LV2_PORT_UNIT_MS:
  968. std::strncpy(strBuf, "ms", STR_MAX);
  969. return true;
  970. case LV2_PORT_UNIT_OCT:
  971. std::strncpy(strBuf, "oct", STR_MAX);
  972. return true;
  973. case LV2_PORT_UNIT_PC:
  974. std::strncpy(strBuf, "%", STR_MAX);
  975. return true;
  976. case LV2_PORT_UNIT_S:
  977. std::strncpy(strBuf, "s", STR_MAX);
  978. return true;
  979. case LV2_PORT_UNIT_SEMITONE:
  980. std::strncpy(strBuf, "semi", STR_MAX);
  981. return true;
  982. }
  983. }
  984. }
  985. return CarlaPlugin::getParameterUnit(parameterId, strBuf);
  986. }
  987. bool getParameterComment(const uint32_t parameterId, char* const strBuf) const noexcept override
  988. {
  989. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr, false);
  990. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  991. int32_t rindex = pData->param.data[parameterId].rindex;
  992. CARLA_SAFE_ASSERT_RETURN(rindex >= 0, false);
  993. if (rindex < static_cast<int32_t>(fRdfDescriptor->PortCount))
  994. {
  995. if (const char* const comment = fRdfDescriptor->Ports[rindex].Comment)
  996. {
  997. std::strncpy(strBuf, comment, STR_MAX);
  998. return true;
  999. }
  1000. return false;
  1001. }
  1002. rindex -= static_cast<int32_t>(fRdfDescriptor->PortCount);
  1003. if (rindex < static_cast<int32_t>(fRdfDescriptor->ParameterCount))
  1004. {
  1005. if (const char* const comment = fRdfDescriptor->Parameters[rindex].Comment)
  1006. {
  1007. std::strncpy(strBuf, comment, STR_MAX);
  1008. return true;
  1009. }
  1010. return false;
  1011. }
  1012. return CarlaPlugin::getParameterComment(parameterId, strBuf);
  1013. }
  1014. bool getParameterGroupName(const uint32_t parameterId, char* const strBuf) const noexcept override
  1015. {
  1016. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr, false);
  1017. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  1018. int32_t rindex = pData->param.data[parameterId].rindex;
  1019. CARLA_SAFE_ASSERT_RETURN(rindex >= 0, false);
  1020. const char* uri = nullptr;
  1021. if (rindex < static_cast<int32_t>(fRdfDescriptor->PortCount))
  1022. {
  1023. uri = fRdfDescriptor->Ports[rindex].GroupURI;
  1024. }
  1025. else
  1026. {
  1027. rindex -= static_cast<int32_t>(fRdfDescriptor->PortCount);
  1028. if (rindex < static_cast<int32_t>(fRdfDescriptor->ParameterCount))
  1029. uri = fRdfDescriptor->Parameters[rindex].GroupURI;
  1030. }
  1031. if (uri == nullptr)
  1032. return false;
  1033. for (uint32_t i=0; i<fRdfDescriptor->PortGroupCount; ++i)
  1034. {
  1035. if (std::strcmp(fRdfDescriptor->PortGroups[i].URI, uri) == 0)
  1036. {
  1037. const char* const name = fRdfDescriptor->PortGroups[i].Name;
  1038. const char* const symbol = fRdfDescriptor->PortGroups[i].Symbol;
  1039. if (name != nullptr && symbol != nullptr)
  1040. {
  1041. std::snprintf(strBuf, STR_MAX, "%s:%s", symbol, name);
  1042. return true;
  1043. }
  1044. return false;
  1045. }
  1046. }
  1047. return false;
  1048. }
  1049. bool getParameterScalePointLabel(const uint32_t parameterId, const uint32_t scalePointId, char* const strBuf) const noexcept override
  1050. {
  1051. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr, false);
  1052. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  1053. const int32_t rindex(pData->param.data[parameterId].rindex);
  1054. CARLA_SAFE_ASSERT_RETURN(rindex >= 0, false);
  1055. if (rindex < static_cast<int32_t>(fRdfDescriptor->PortCount))
  1056. {
  1057. const LV2_RDF_Port* const port(&fRdfDescriptor->Ports[rindex]);
  1058. CARLA_SAFE_ASSERT_RETURN(scalePointId < port->ScalePointCount, false);
  1059. const LV2_RDF_PortScalePoint* const portScalePoint(&port->ScalePoints[scalePointId]);
  1060. if (portScalePoint->Label != nullptr)
  1061. {
  1062. std::strncpy(strBuf, portScalePoint->Label, STR_MAX);
  1063. return true;
  1064. }
  1065. }
  1066. return CarlaPlugin::getParameterScalePointLabel(parameterId, scalePointId, strBuf);
  1067. }
  1068. // -------------------------------------------------------------------
  1069. // Set data (state)
  1070. void prepareForSave() override
  1071. {
  1072. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr,);
  1073. if (fExt.state != nullptr && fExt.state->save != nullptr)
  1074. {
  1075. fExt.state->save(fHandle, carla_lv2_state_store, this, LV2_STATE_IS_POD, fFeatures);
  1076. if (fHandle2 != nullptr)
  1077. fExt.state->save(fHandle2, carla_lv2_state_store, this, LV2_STATE_IS_POD, fFeatures);
  1078. }
  1079. }
  1080. // -------------------------------------------------------------------
  1081. // Set data (internal stuff)
  1082. void setName(const char* const newName) override
  1083. {
  1084. CarlaPlugin::setName(newName);
  1085. if (fLv2Options.windowTitle == nullptr)
  1086. return;
  1087. CarlaString guiTitle(pData->name);
  1088. guiTitle += " (GUI)";
  1089. delete[] fLv2Options.windowTitle;
  1090. fLv2Options.windowTitle = guiTitle.dup();
  1091. fLv2Options.opts[CarlaPluginLV2Options::WindowTitle].size = (uint32_t)std::strlen(fLv2Options.windowTitle);
  1092. fLv2Options.opts[CarlaPluginLV2Options::WindowTitle].value = fLv2Options.windowTitle;
  1093. if (fFeatures[kFeatureIdExternalUi] != nullptr && fFeatures[kFeatureIdExternalUi]->data != nullptr)
  1094. ((LV2_External_UI_Host*)fFeatures[kFeatureIdExternalUi]->data)->plugin_human_id = fLv2Options.windowTitle;
  1095. if (fPipeServer.isPipeRunning())
  1096. fPipeServer.writeUiTitleMessage(fLv2Options.windowTitle);
  1097. #ifndef LV2_UIS_ONLY_BRIDGES
  1098. if (fUI.window != nullptr)
  1099. fUI.window->setTitle(fLv2Options.windowTitle);
  1100. #endif
  1101. }
  1102. // -------------------------------------------------------------------
  1103. // Set data (plugin-specific stuff)
  1104. float setParamterValueCommon(const uint32_t parameterId, const float value) noexcept
  1105. {
  1106. const float fixedValue(pData->param.getFixedValue(parameterId, value));
  1107. fParamBuffers[parameterId] = fixedValue;
  1108. if (pData->param.data[parameterId].rindex >= static_cast<int32_t>(fRdfDescriptor->PortCount))
  1109. {
  1110. const uint32_t rparamId = static_cast<uint32_t>(pData->param.data[parameterId].rindex) - fRdfDescriptor->PortCount;
  1111. CARLA_SAFE_ASSERT_UINT2_RETURN(rparamId < fRdfDescriptor->ParameterCount,
  1112. rparamId, fRdfDescriptor->PortCount, fixedValue);
  1113. uint8_t atomBuf[256];
  1114. lv2_atom_forge_set_buffer(&fAtomForge, atomBuf, sizeof(atomBuf));
  1115. LV2_Atom_Forge_Frame forgeFrame;
  1116. lv2_atom_forge_object(&fAtomForge, &forgeFrame, kUridNull, kUridPatchSet);
  1117. lv2_atom_forge_key(&fAtomForge, kUridPatchPoperty);
  1118. lv2_atom_forge_urid(&fAtomForge, getCustomURID(fRdfDescriptor->Parameters[rparamId].URI));
  1119. lv2_atom_forge_key(&fAtomForge, kUridPatchValue);
  1120. switch (fRdfDescriptor->Parameters[rparamId].Type)
  1121. {
  1122. case LV2_PARAMETER_BOOL:
  1123. lv2_atom_forge_bool(&fAtomForge, fixedValue > 0.5f);
  1124. break;
  1125. case LV2_PARAMETER_INT:
  1126. lv2_atom_forge_int(&fAtomForge, static_cast<int32_t>(fixedValue + 0.5f));
  1127. break;
  1128. case LV2_PARAMETER_LONG:
  1129. lv2_atom_forge_long(&fAtomForge, static_cast<int64_t>(fixedValue + 0.5f));
  1130. break;
  1131. case LV2_PARAMETER_FLOAT:
  1132. lv2_atom_forge_float(&fAtomForge, fixedValue);
  1133. break;
  1134. case LV2_PARAMETER_DOUBLE:
  1135. lv2_atom_forge_double(&fAtomForge, fixedValue);
  1136. break;
  1137. default:
  1138. carla_stderr2("setParameterValue called for invalid parameter, expect issues!");
  1139. break;
  1140. }
  1141. lv2_atom_forge_pop(&fAtomForge, &forgeFrame);
  1142. LV2_Atom* const atom((LV2_Atom*)atomBuf);
  1143. CARLA_SAFE_ASSERT(atom->size < sizeof(atomBuf));
  1144. fAtomBufferEvIn.put(atom, fEventsIn.ctrlIndex);
  1145. }
  1146. return fixedValue;
  1147. }
  1148. void setParameterValue(const uint32_t parameterId, const float value, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  1149. {
  1150. CARLA_SAFE_ASSERT_RETURN(fParamBuffers != nullptr,);
  1151. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  1152. const float fixedValue = setParamterValueCommon(parameterId, value);
  1153. CarlaPlugin::setParameterValue(parameterId, fixedValue, sendGui, sendOsc, sendCallback);
  1154. }
  1155. void setParameterValueRT(const uint32_t parameterId, const float value, const bool sendCallbackLater) noexcept override
  1156. {
  1157. CARLA_SAFE_ASSERT_RETURN(fParamBuffers != nullptr,);
  1158. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  1159. const float fixedValue = setParamterValueCommon(parameterId, value);
  1160. CarlaPlugin::setParameterValueRT(parameterId, fixedValue, sendCallbackLater);
  1161. }
  1162. void setCustomData(const char* const type, const char* const key, const char* const value, const bool sendGui) override
  1163. {
  1164. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr,);
  1165. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr,);
  1166. CARLA_SAFE_ASSERT_RETURN(type != nullptr && type[0] != '\0',);
  1167. CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
  1168. CARLA_SAFE_ASSERT_RETURN(value != nullptr,);
  1169. carla_debug("CarlaPluginLV2::setCustomData(%s, %s, %s, %s)", type, key, value, bool2str(sendGui));
  1170. if (std::strcmp(type, CUSTOM_DATA_TYPE_PROPERTY) == 0)
  1171. return CarlaPlugin::setCustomData(type, key, value, sendGui);
  1172. CarlaPlugin::setCustomData(type, key, value, sendGui);
  1173. }
  1174. void setProgram(const int32_t index, const bool sendGui, const bool sendOsc, const bool sendCallback, const bool doingInit) noexcept override
  1175. {
  1176. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr,);
  1177. CARLA_SAFE_ASSERT_RETURN(index >= -1 && index < static_cast<int32_t>(pData->prog.count),);
  1178. CARLA_SAFE_ASSERT_RETURN(sendGui || sendOsc || sendCallback,);
  1179. if (index >= 0 && index < static_cast<int32_t>(fRdfDescriptor->PresetCount))
  1180. {
  1181. const LV2_URID_Map* const uridMap = (const LV2_URID_Map*)fFeatures[kFeatureIdUridMap]->data;
  1182. LilvState* const state = Lv2WorldClass::getInstance().getStateFromURI(fRdfDescriptor->Presets[index].URI,
  1183. uridMap);
  1184. CARLA_SAFE_ASSERT_RETURN(state != nullptr,);
  1185. // invalidate midi-program selection
  1186. CarlaPlugin::setMidiProgram(-1, false, false, sendCallback, false);
  1187. if (fExt.state != nullptr)
  1188. {
  1189. const ScopedSingleProcessLocker spl(this, (sendGui || sendOsc || sendCallback));
  1190. lilv_state_restore(state, fExt.state, fHandle, carla_lilv_set_port_value, this, 0, fFeatures);
  1191. if (fHandle2 != nullptr)
  1192. lilv_state_restore(state, fExt.state, fHandle2, carla_lilv_set_port_value, this, 0, fFeatures);
  1193. }
  1194. else
  1195. {
  1196. lilv_state_emit_port_values(state, carla_lilv_set_port_value, this);
  1197. }
  1198. lilv_state_free(state);
  1199. }
  1200. CarlaPlugin::setProgram(index, sendGui, sendOsc, sendCallback, doingInit);
  1201. }
  1202. void setMidiProgram(const int32_t index, const bool sendGui, const bool sendOsc, const bool sendCallback, const bool doingInit) noexcept override
  1203. {
  1204. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr,);
  1205. CARLA_SAFE_ASSERT_RETURN(index >= -1 && index < static_cast<int32_t>(pData->midiprog.count),);
  1206. CARLA_SAFE_ASSERT_RETURN(sendGui || sendOsc || sendCallback || doingInit,);
  1207. if (index >= 0 && fExt.programs != nullptr && fExt.programs->select_program != nullptr)
  1208. {
  1209. const uint32_t bank(pData->midiprog.data[index].bank);
  1210. const uint32_t program(pData->midiprog.data[index].program);
  1211. const ScopedSingleProcessLocker spl(this, (sendGui || sendOsc || sendCallback));
  1212. try {
  1213. fExt.programs->select_program(fHandle, bank, program);
  1214. } catch(...) {}
  1215. if (fHandle2 != nullptr)
  1216. {
  1217. try {
  1218. fExt.programs->select_program(fHandle2, bank, program);
  1219. } catch(...) {}
  1220. }
  1221. }
  1222. CarlaPlugin::setMidiProgram(index, sendGui, sendOsc, sendCallback, doingInit);
  1223. }
  1224. void setMidiProgramRT(const uint32_t uindex, const bool sendCallbackLater) noexcept override
  1225. {
  1226. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr,);
  1227. CARLA_SAFE_ASSERT_RETURN(uindex < pData->midiprog.count,);
  1228. if (fExt.programs != nullptr && fExt.programs->select_program != nullptr)
  1229. {
  1230. const uint32_t bank(pData->midiprog.data[uindex].bank);
  1231. const uint32_t program(pData->midiprog.data[uindex].program);
  1232. try {
  1233. fExt.programs->select_program(fHandle, bank, program);
  1234. } catch(...) {}
  1235. if (fHandle2 != nullptr)
  1236. {
  1237. try {
  1238. fExt.programs->select_program(fHandle2, bank, program);
  1239. } catch(...) {}
  1240. }
  1241. }
  1242. CarlaPlugin::setMidiProgramRT(uindex, sendCallbackLater);
  1243. }
  1244. // -------------------------------------------------------------------
  1245. // Set ui stuff
  1246. void showCustomUI(const bool yesNo) override
  1247. {
  1248. if (fUI.type == UI::TYPE_NULL)
  1249. {
  1250. if (fFilePathURI.isNotEmpty())
  1251. {
  1252. const char* const path = pData->engine->runFileCallback(FILE_CALLBACK_OPEN, false, "Open File", "");
  1253. if (path != nullptr && path[0] != '\0')
  1254. {
  1255. carla_stdout("LV2 file path to send: '%s'", path);
  1256. uint8_t atomBuf[4096];
  1257. lv2_atom_forge_set_buffer(&fAtomForge, atomBuf, sizeof(atomBuf));
  1258. LV2_Atom_Forge_Frame forgeFrame;
  1259. lv2_atom_forge_object(&fAtomForge, &forgeFrame, kUridNull, kUridPatchSet);
  1260. lv2_atom_forge_key(&fAtomForge, kUridPatchPoperty);
  1261. lv2_atom_forge_urid(&fAtomForge, getCustomURID(fFilePathURI));
  1262. lv2_atom_forge_key(&fAtomForge, kUridPatchValue);
  1263. lv2_atom_forge_path(&fAtomForge, path, static_cast<uint32_t>(std::strlen(path)));
  1264. lv2_atom_forge_pop(&fAtomForge, &forgeFrame);
  1265. LV2_Atom* const atom((LV2_Atom*)atomBuf);
  1266. CARLA_SAFE_ASSERT(atom->size < sizeof(atomBuf));
  1267. fAtomBufferEvIn.put(atom, fEventsIn.ctrlIndex);
  1268. }
  1269. }
  1270. else
  1271. {
  1272. CARLA_SAFE_ASSERT(!yesNo);
  1273. }
  1274. pData->engine->callback(true, true,
  1275. ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, 0, 0, 0, 0.0f, nullptr);
  1276. return;
  1277. }
  1278. const uintptr_t frontendWinId(pData->engine->getOptions().frontendWinId);
  1279. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1280. if (! yesNo)
  1281. pData->transientTryCounter = 0;
  1282. #endif
  1283. if (fUI.type == UI::TYPE_BRIDGE)
  1284. {
  1285. if (yesNo)
  1286. {
  1287. if (fPipeServer.isPipeRunning())
  1288. {
  1289. fPipeServer.writeFocusMessage();
  1290. return;
  1291. }
  1292. if (! fPipeServer.startPipeServer(std::min(fLv2Options.sequenceSize, 819200)))
  1293. {
  1294. pData->engine->callback(true, true,
  1295. ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, 0, 0, 0, 0.0f, nullptr);
  1296. return;
  1297. }
  1298. // manually write messages so we can take the lock for ourselves
  1299. {
  1300. char tmpBuf[0xff+1];
  1301. tmpBuf[0xff] = '\0';
  1302. const CarlaMutexLocker cml(fPipeServer.getPipeLock());
  1303. const CarlaScopedLocale csl;
  1304. // write URI mappings
  1305. uint32_t u = 0;
  1306. for (std::vector<std::string>::iterator it=fCustomURIDs.begin(), end=fCustomURIDs.end(); it != end; ++it, ++u)
  1307. {
  1308. if (u < kUridCount)
  1309. continue;
  1310. const std::string& uri(*it);
  1311. std::snprintf(tmpBuf, 0xff, "%u\n", u);
  1312. if (! fPipeServer.writeMessage("urid\n", 5))
  1313. return;
  1314. if (! fPipeServer.writeMessage(tmpBuf))
  1315. return;
  1316. if (! fPipeServer.writeAndFixMessage(uri.c_str()))
  1317. return;
  1318. }
  1319. // write UI options
  1320. if (! fPipeServer.writeMessage("uiOptions\n", 10))
  1321. return;
  1322. const EngineOptions& opts(pData->engine->getOptions());
  1323. std::snprintf(tmpBuf, 0xff, "%g\n", pData->engine->getSampleRate());
  1324. if (! fPipeServer.writeMessage(tmpBuf))
  1325. return;
  1326. std::snprintf(tmpBuf, 0xff, "%u\n", opts.bgColor);
  1327. if (! fPipeServer.writeMessage(tmpBuf))
  1328. return;
  1329. std::snprintf(tmpBuf, 0xff, "%u\n", opts.fgColor);
  1330. if (! fPipeServer.writeMessage(tmpBuf))
  1331. return;
  1332. std::snprintf(tmpBuf, 0xff, "%.12g\n", static_cast<double>(opts.uiScale));
  1333. if (! fPipeServer.writeMessage(tmpBuf))
  1334. return;
  1335. std::snprintf(tmpBuf, 0xff, "%s\n", bool2str(true)); // useTheme
  1336. if (! fPipeServer.writeMessage(tmpBuf))
  1337. return;
  1338. std::snprintf(tmpBuf, 0xff, "%s\n", bool2str(true)); // useThemeColors
  1339. if (! fPipeServer.writeMessage(tmpBuf))
  1340. return;
  1341. if (! fPipeServer.writeAndFixMessage(fLv2Options.windowTitle != nullptr
  1342. ? fLv2Options.windowTitle
  1343. : ""))
  1344. return;
  1345. std::snprintf(tmpBuf, 0xff, P_INTPTR "\n", frontendWinId);
  1346. if (! fPipeServer.writeMessage(tmpBuf))
  1347. return;
  1348. // write parameter values
  1349. for (uint32_t i=0; i < pData->param.count; ++i)
  1350. {
  1351. if (! fPipeServer.writeMessage("control\n", 8))
  1352. return;
  1353. std::snprintf(tmpBuf, 0xff, "%i\n", pData->param.data[i].rindex);
  1354. if (! fPipeServer.writeMessage(tmpBuf))
  1355. return;
  1356. std::snprintf(tmpBuf, 0xff, "%.12g\n", static_cast<double>(getParameterValue(i)));
  1357. if (! fPipeServer.writeMessage(tmpBuf))
  1358. return;
  1359. }
  1360. // ready to show
  1361. if (! fPipeServer.writeMessage("show\n", 5))
  1362. return;
  1363. fPipeServer.flushMessages();
  1364. }
  1365. #ifndef BUILD_BRIDGE
  1366. if (fUI.rdfDescriptor->Type == LV2_UI_MOD)
  1367. pData->tryTransient();
  1368. #endif
  1369. }
  1370. else
  1371. {
  1372. fPipeServer.stopPipeServer(pData->engine->getOptions().uiBridgesTimeout);
  1373. }
  1374. return;
  1375. }
  1376. // take some precautions
  1377. CARLA_SAFE_ASSERT_RETURN(fUI.descriptor != nullptr,);
  1378. CARLA_SAFE_ASSERT_RETURN(fUI.rdfDescriptor != nullptr,);
  1379. if (yesNo)
  1380. {
  1381. CARLA_SAFE_ASSERT_RETURN(fUI.descriptor->instantiate != nullptr,);
  1382. CARLA_SAFE_ASSERT_RETURN(fUI.descriptor->cleanup != nullptr,);
  1383. }
  1384. else
  1385. {
  1386. if (fUI.handle == nullptr)
  1387. return;
  1388. }
  1389. if (yesNo)
  1390. {
  1391. if (fUI.handle == nullptr)
  1392. {
  1393. #ifndef LV2_UIS_ONLY_BRIDGES
  1394. if (fUI.type == UI::TYPE_EMBED && fUI.rdfDescriptor->Type != LV2_UI_NONE && fUI.window == nullptr)
  1395. {
  1396. const char* msg = nullptr;
  1397. switch (fUI.rdfDescriptor->Type)
  1398. {
  1399. case LV2_UI_GTK2:
  1400. case LV2_UI_GTK3:
  1401. case LV2_UI_QT4:
  1402. case LV2_UI_QT5:
  1403. case LV2_UI_EXTERNAL:
  1404. case LV2_UI_OLD_EXTERNAL:
  1405. msg = "Invalid UI type";
  1406. break;
  1407. case LV2_UI_COCOA:
  1408. # ifdef CARLA_OS_MAC
  1409. fUI.window = CarlaPluginUI::newCocoa(this, frontendWinId, isUiResizable());
  1410. # else
  1411. msg = "UI is for MacOS only";
  1412. # endif
  1413. break;
  1414. case LV2_UI_WINDOWS:
  1415. # ifdef CARLA_OS_WIN
  1416. fUI.window = CarlaPluginUI::newWindows(this, frontendWinId, isUiResizable());
  1417. # else
  1418. msg = "UI is for Windows only";
  1419. # endif
  1420. break;
  1421. case LV2_UI_X11:
  1422. # ifdef HAVE_X11
  1423. fUI.window = CarlaPluginUI::newX11(this, frontendWinId, isUiResizable());
  1424. # else
  1425. msg = "UI is only for systems with X11";
  1426. # endif
  1427. break;
  1428. default:
  1429. msg = "Unknown UI type";
  1430. break;
  1431. }
  1432. if (fUI.window == nullptr && fExt.uishow == nullptr)
  1433. return pData->engine->callback(true, true,
  1434. ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, -1, 0, 0, 0.0f, msg);
  1435. if (fUI.window != nullptr)
  1436. fFeatures[kFeatureIdUiParent]->data = fUI.window->getPtr();
  1437. }
  1438. #endif
  1439. fUI.widget = nullptr;
  1440. fUI.handle = fUI.descriptor->instantiate(fUI.descriptor, fRdfDescriptor->URI, fUI.rdfDescriptor->Bundle,
  1441. carla_lv2_ui_write_function, this, &fUI.widget, fFeatures);
  1442. if (fUI.window != nullptr)
  1443. {
  1444. if (fUI.widget != nullptr)
  1445. fUI.window->setChildWindow(fUI.widget);
  1446. fUI.window->setTitle(fLv2Options.windowTitle);
  1447. }
  1448. }
  1449. CARLA_SAFE_ASSERT(fUI.handle != nullptr);
  1450. CARLA_SAFE_ASSERT(fUI.type != UI::TYPE_EXTERNAL || fUI.widget != nullptr);
  1451. if (fUI.handle == nullptr || (fUI.type == UI::TYPE_EXTERNAL && fUI.widget == nullptr))
  1452. {
  1453. fUI.widget = nullptr;
  1454. if (fUI.handle != nullptr)
  1455. {
  1456. fUI.descriptor->cleanup(fUI.handle);
  1457. fUI.handle = nullptr;
  1458. }
  1459. return pData->engine->callback(true, true,
  1460. ENGINE_CALLBACK_UI_STATE_CHANGED,
  1461. pData->id,
  1462. -1,
  1463. 0, 0, 0.0f,
  1464. "Plugin refused to open its own UI");
  1465. }
  1466. updateUi();
  1467. #ifndef LV2_UIS_ONLY_BRIDGES
  1468. if (fUI.type == UI::TYPE_EMBED)
  1469. {
  1470. if (fUI.window != nullptr)
  1471. {
  1472. fUI.window->show();
  1473. }
  1474. else if (fExt.uishow != nullptr)
  1475. {
  1476. fExt.uishow->show(fUI.handle);
  1477. # ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1478. pData->tryTransient();
  1479. # endif
  1480. }
  1481. }
  1482. else
  1483. #endif
  1484. {
  1485. LV2_EXTERNAL_UI_SHOW((LV2_External_UI_Widget*)fUI.widget);
  1486. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1487. pData->tryTransient();
  1488. #endif
  1489. }
  1490. }
  1491. else
  1492. {
  1493. #ifndef LV2_UIS_ONLY_BRIDGES
  1494. if (fUI.type == UI::TYPE_EMBED)
  1495. {
  1496. if (fUI.window != nullptr)
  1497. fUI.window->hide();
  1498. else if (fExt.uishow != nullptr)
  1499. fExt.uishow->hide(fUI.handle);
  1500. }
  1501. else
  1502. #endif
  1503. {
  1504. CARLA_SAFE_ASSERT(fUI.widget != nullptr);
  1505. if (fUI.widget != nullptr)
  1506. LV2_EXTERNAL_UI_HIDE((LV2_External_UI_Widget*)fUI.widget);
  1507. }
  1508. fUI.descriptor->cleanup(fUI.handle);
  1509. fUI.handle = nullptr;
  1510. fUI.widget = nullptr;
  1511. }
  1512. }
  1513. void idle() override
  1514. {
  1515. if (fAtomBufferWorkerIn.isDataAvailableForReading())
  1516. {
  1517. Lv2AtomRingBuffer tmpRingBuffer(fAtomBufferWorkerIn, fAtomBufferWorkerInTmpData);
  1518. CARLA_SAFE_ASSERT_RETURN(tmpRingBuffer.isDataAvailableForReading(),);
  1519. CARLA_SAFE_ASSERT_RETURN(fExt.worker != nullptr && fExt.worker->work != nullptr,);
  1520. uint32_t portIndex;
  1521. const LV2_Atom* atom;
  1522. for (; tmpRingBuffer.get(atom, portIndex);)
  1523. {
  1524. CARLA_SAFE_ASSERT_CONTINUE(atom->type == kUridCarlaAtomWorkerIn);
  1525. fExt.worker->work(fHandle, carla_lv2_worker_respond, this, atom->size, LV2_ATOM_BODY_CONST(atom));
  1526. }
  1527. }
  1528. if (fInlineDisplayNeedsRedraw)
  1529. {
  1530. // TESTING
  1531. CARLA_SAFE_ASSERT(pData->enabled)
  1532. CARLA_SAFE_ASSERT(!pData->engine->isAboutToClose());
  1533. CARLA_SAFE_ASSERT(pData->client->isActive());
  1534. if (pData->enabled && !pData->engine->isAboutToClose() && pData->client->isActive())
  1535. {
  1536. const int64_t timeNow = water::Time::currentTimeMillis();
  1537. if (timeNow - fInlineDisplayLastRedrawTime > (1000 / 30))
  1538. {
  1539. fInlineDisplayNeedsRedraw = false;
  1540. fInlineDisplayLastRedrawTime = timeNow;
  1541. pData->engine->callback(true, true,
  1542. ENGINE_CALLBACK_INLINE_DISPLAY_REDRAW,
  1543. pData->id,
  1544. 0, 0, 0, 0.0f, nullptr);
  1545. }
  1546. }
  1547. }
  1548. CarlaPlugin::idle();
  1549. }
  1550. void uiIdle() override
  1551. {
  1552. if (fAtomBufferUiOut.isDataAvailableForReading())
  1553. {
  1554. Lv2AtomRingBuffer tmpRingBuffer(fAtomBufferUiOut, fAtomBufferUiOutTmpData);
  1555. CARLA_SAFE_ASSERT(tmpRingBuffer.isDataAvailableForReading());
  1556. uint32_t portIndex;
  1557. const LV2_Atom* atom;
  1558. const bool hasPortEvent(fUI.handle != nullptr &&
  1559. fUI.descriptor != nullptr &&
  1560. fUI.descriptor->port_event != nullptr);
  1561. for (; tmpRingBuffer.get(atom, portIndex);)
  1562. {
  1563. if (fUI.type == UI::TYPE_BRIDGE)
  1564. {
  1565. if (fPipeServer.isPipeRunning())
  1566. fPipeServer.writeLv2AtomMessage(portIndex, atom);
  1567. }
  1568. else
  1569. {
  1570. if (hasPortEvent && ! fNeedsUiClose)
  1571. fUI.descriptor->port_event(fUI.handle, portIndex, lv2_atom_total_size(atom), kUridAtomTransferEvent, atom);
  1572. }
  1573. }
  1574. }
  1575. if (fPipeServer.isPipeRunning())
  1576. {
  1577. fPipeServer.idlePipe();
  1578. switch (fPipeServer.getAndResetUiState())
  1579. {
  1580. case CarlaPipeServerLV2::UiNone:
  1581. case CarlaPipeServerLV2::UiShow:
  1582. break;
  1583. case CarlaPipeServerLV2::UiHide:
  1584. fPipeServer.stopPipeServer(2000);
  1585. // fall through
  1586. case CarlaPipeServerLV2::UiCrashed:
  1587. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1588. pData->transientTryCounter = 0;
  1589. #endif
  1590. pData->engine->callback(true, true,
  1591. ENGINE_CALLBACK_UI_STATE_CHANGED,
  1592. pData->id,
  1593. 0,
  1594. 0, 0, 0.0f, nullptr);
  1595. break;
  1596. }
  1597. }
  1598. else
  1599. {
  1600. // TODO - detect if ui-bridge crashed
  1601. }
  1602. if (fNeedsUiClose)
  1603. {
  1604. fNeedsUiClose = false;
  1605. showCustomUI(false);
  1606. pData->engine->callback(true, true,
  1607. ENGINE_CALLBACK_UI_STATE_CHANGED,
  1608. pData->id,
  1609. 0,
  1610. 0, 0, 0.0f, nullptr);
  1611. }
  1612. else if (fUI.handle != nullptr && fUI.descriptor != nullptr)
  1613. {
  1614. if (fUI.type == UI::TYPE_EXTERNAL && fUI.widget != nullptr)
  1615. LV2_EXTERNAL_UI_RUN((LV2_External_UI_Widget*)fUI.widget);
  1616. #ifndef LV2_UIS_ONLY_BRIDGES
  1617. else if (fUI.type == UI::TYPE_EMBED && fUI.window != nullptr)
  1618. fUI.window->idle();
  1619. // note: UI might have been closed by window idle
  1620. if (fNeedsUiClose)
  1621. {
  1622. pass();
  1623. }
  1624. else if (fUI.handle != nullptr && fExt.uiidle != nullptr && fExt.uiidle->idle(fUI.handle) != 0)
  1625. {
  1626. showCustomUI(false);
  1627. pData->engine->callback(true, true,
  1628. ENGINE_CALLBACK_UI_STATE_CHANGED,
  1629. pData->id,
  1630. 0,
  1631. 0, 0, 0.0f, nullptr);
  1632. CARLA_SAFE_ASSERT(fUI.handle == nullptr);
  1633. }
  1634. #endif
  1635. }
  1636. CarlaPlugin::uiIdle();
  1637. }
  1638. // -------------------------------------------------------------------
  1639. // Plugin state
  1640. void reload() override
  1641. {
  1642. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  1643. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr,);
  1644. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr,);
  1645. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr,);
  1646. carla_debug("CarlaPluginLV2::reload() - start");
  1647. const EngineProcessMode processMode(pData->engine->getProccessMode());
  1648. // Safely disable plugin for reload
  1649. const ScopedDisabler sd(this);
  1650. if (pData->active)
  1651. deactivate();
  1652. clearBuffers();
  1653. const float sampleRate(static_cast<float>(pData->engine->getSampleRate()));
  1654. const uint32_t portCount(fRdfDescriptor->PortCount);
  1655. uint32_t aIns, aOuts, cvIns, cvOuts, params;
  1656. aIns = aOuts = cvIns = cvOuts = params = 0;
  1657. LinkedList<uint> evIns, evOuts;
  1658. const uint32_t eventBufferSize(static_cast<uint32_t>(fLv2Options.sequenceSize)+0xff);
  1659. bool forcedStereoIn, forcedStereoOut;
  1660. forcedStereoIn = forcedStereoOut = false;
  1661. bool needsCtrlIn, needsCtrlOut;
  1662. needsCtrlIn = needsCtrlOut = false;
  1663. for (uint32_t i=0; i < portCount; ++i)
  1664. {
  1665. const LV2_Property portTypes(fRdfDescriptor->Ports[i].Types);
  1666. if (LV2_IS_PORT_AUDIO(portTypes))
  1667. {
  1668. if (LV2_IS_PORT_INPUT(portTypes))
  1669. aIns += 1;
  1670. else if (LV2_IS_PORT_OUTPUT(portTypes))
  1671. aOuts += 1;
  1672. }
  1673. else if (LV2_IS_PORT_CV(portTypes))
  1674. {
  1675. if (LV2_IS_PORT_INPUT(portTypes))
  1676. cvIns += 1;
  1677. else if (LV2_IS_PORT_OUTPUT(portTypes))
  1678. cvOuts += 1;
  1679. }
  1680. else if (LV2_IS_PORT_ATOM_SEQUENCE(portTypes))
  1681. {
  1682. if (LV2_IS_PORT_INPUT(portTypes))
  1683. evIns.append(CARLA_EVENT_DATA_ATOM);
  1684. else if (LV2_IS_PORT_OUTPUT(portTypes))
  1685. evOuts.append(CARLA_EVENT_DATA_ATOM);
  1686. }
  1687. else if (LV2_IS_PORT_EVENT(portTypes))
  1688. {
  1689. if (LV2_IS_PORT_INPUT(portTypes))
  1690. evIns.append(CARLA_EVENT_DATA_EVENT);
  1691. else if (LV2_IS_PORT_OUTPUT(portTypes))
  1692. evOuts.append(CARLA_EVENT_DATA_EVENT);
  1693. }
  1694. else if (LV2_IS_PORT_MIDI_LL(portTypes))
  1695. {
  1696. if (LV2_IS_PORT_INPUT(portTypes))
  1697. evIns.append(CARLA_EVENT_DATA_MIDI_LL);
  1698. else if (LV2_IS_PORT_OUTPUT(portTypes))
  1699. evOuts.append(CARLA_EVENT_DATA_MIDI_LL);
  1700. }
  1701. else if (LV2_IS_PORT_CONTROL(portTypes))
  1702. params += 1;
  1703. }
  1704. for (uint32_t i=0; i < fRdfDescriptor->ParameterCount; ++i)
  1705. {
  1706. switch (fRdfDescriptor->Parameters[i].Type)
  1707. {
  1708. case LV2_PARAMETER_BOOL:
  1709. case LV2_PARAMETER_INT:
  1710. // case LV2_PARAMETER_LONG:
  1711. case LV2_PARAMETER_FLOAT:
  1712. case LV2_PARAMETER_DOUBLE:
  1713. params += 1;
  1714. break;
  1715. case LV2_PARAMETER_PATH:
  1716. if (fFilePathURI.isEmpty())
  1717. fFilePathURI = fRdfDescriptor->Parameters[i].URI;
  1718. break;
  1719. }
  1720. }
  1721. if ((pData->options & PLUGIN_OPTION_FORCE_STEREO) != 0 && aIns <= 1 && aOuts <= 1 && fExt.state == nullptr && fExt.worker == nullptr)
  1722. {
  1723. if (fHandle2 == nullptr)
  1724. {
  1725. try {
  1726. fHandle2 = fDescriptor->instantiate(fDescriptor, sampleRate, fRdfDescriptor->Bundle, fFeatures);
  1727. } catch(...) {}
  1728. }
  1729. if (fHandle2 != nullptr)
  1730. {
  1731. if (aIns == 1)
  1732. {
  1733. aIns = 2;
  1734. forcedStereoIn = true;
  1735. }
  1736. if (aOuts == 1)
  1737. {
  1738. aOuts = 2;
  1739. forcedStereoOut = true;
  1740. }
  1741. }
  1742. }
  1743. if (aIns > 0)
  1744. {
  1745. pData->audioIn.createNew(aIns);
  1746. fAudioInBuffers = new float*[aIns];
  1747. for (uint32_t i=0; i < aIns; ++i)
  1748. fAudioInBuffers[i] = nullptr;
  1749. }
  1750. if (aOuts > 0)
  1751. {
  1752. pData->audioOut.createNew(aOuts);
  1753. fAudioOutBuffers = new float*[aOuts];
  1754. needsCtrlIn = true;
  1755. for (uint32_t i=0; i < aOuts; ++i)
  1756. fAudioOutBuffers[i] = nullptr;
  1757. }
  1758. if (cvIns > 0)
  1759. {
  1760. pData->cvIn.createNew(cvIns);
  1761. fCvInBuffers = new float*[cvIns];
  1762. for (uint32_t i=0; i < cvIns; ++i)
  1763. fCvInBuffers[i] = nullptr;
  1764. }
  1765. if (cvOuts > 0)
  1766. {
  1767. pData->cvOut.createNew(cvOuts);
  1768. fCvOutBuffers = new float*[cvOuts];
  1769. for (uint32_t i=0; i < cvOuts; ++i)
  1770. fCvOutBuffers[i] = nullptr;
  1771. }
  1772. if (params > 0)
  1773. {
  1774. pData->param.createNew(params, true);
  1775. fParamBuffers = new float[params];
  1776. carla_zeroFloats(fParamBuffers, params);
  1777. }
  1778. if (const uint32_t count = static_cast<uint32_t>(evIns.count()))
  1779. {
  1780. fEventsIn.createNew(count);
  1781. for (uint32_t i=0; i < count; ++i)
  1782. {
  1783. const uint32_t& type(evIns.getAt(i, 0x0));
  1784. if (type == CARLA_EVENT_DATA_ATOM)
  1785. {
  1786. fEventsIn.data[i].type = CARLA_EVENT_DATA_ATOM;
  1787. fEventsIn.data[i].atom = lv2_atom_buffer_new(eventBufferSize, kUridNull, kUridAtomSequence, true);
  1788. }
  1789. else if (type == CARLA_EVENT_DATA_EVENT)
  1790. {
  1791. fEventsIn.data[i].type = CARLA_EVENT_DATA_EVENT;
  1792. fEventsIn.data[i].event = lv2_event_buffer_new(eventBufferSize, LV2_EVENT_AUDIO_STAMP);
  1793. }
  1794. else if (type == CARLA_EVENT_DATA_MIDI_LL)
  1795. {
  1796. fEventsIn.data[i].type = CARLA_EVENT_DATA_MIDI_LL;
  1797. fEventsIn.data[i].midi.capacity = eventBufferSize;
  1798. fEventsIn.data[i].midi.data = new uchar[eventBufferSize];
  1799. }
  1800. }
  1801. }
  1802. else
  1803. {
  1804. fEventsIn.createNew(1);
  1805. fEventsIn.ctrl = &fEventsIn.data[0];
  1806. }
  1807. if (const uint32_t count = static_cast<uint32_t>(evOuts.count()))
  1808. {
  1809. fEventsOut.createNew(count);
  1810. for (uint32_t i=0; i < count; ++i)
  1811. {
  1812. const uint32_t& type(evOuts.getAt(i, 0x0));
  1813. if (type == CARLA_EVENT_DATA_ATOM)
  1814. {
  1815. fEventsOut.data[i].type = CARLA_EVENT_DATA_ATOM;
  1816. fEventsOut.data[i].atom = lv2_atom_buffer_new(eventBufferSize, kUridNull, kUridAtomSequence, false);
  1817. }
  1818. else if (type == CARLA_EVENT_DATA_EVENT)
  1819. {
  1820. fEventsOut.data[i].type = CARLA_EVENT_DATA_EVENT;
  1821. fEventsOut.data[i].event = lv2_event_buffer_new(eventBufferSize, LV2_EVENT_AUDIO_STAMP);
  1822. }
  1823. else if (type == CARLA_EVENT_DATA_MIDI_LL)
  1824. {
  1825. fEventsOut.data[i].type = CARLA_EVENT_DATA_MIDI_LL;
  1826. fEventsOut.data[i].midi.capacity = eventBufferSize;
  1827. fEventsOut.data[i].midi.data = new uchar[eventBufferSize];
  1828. }
  1829. }
  1830. }
  1831. const uint portNameSize(pData->engine->getMaxPortNameSize());
  1832. CarlaString portName;
  1833. uint32_t iCtrl = 0;
  1834. for (uint32_t i=0, iAudioIn=0, iAudioOut=0, iCvIn=0, iCvOut=0, iEvIn=0, iEvOut=0; i < portCount; ++i)
  1835. {
  1836. const LV2_Property portTypes(fRdfDescriptor->Ports[i].Types);
  1837. portName.clear();
  1838. if (LV2_IS_PORT_AUDIO(portTypes) || LV2_IS_PORT_CV(portTypes) || LV2_IS_PORT_ATOM_SEQUENCE(portTypes) || LV2_IS_PORT_EVENT(portTypes) || LV2_IS_PORT_MIDI_LL(portTypes))
  1839. {
  1840. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1841. {
  1842. portName = pData->name;
  1843. portName += ":";
  1844. }
  1845. portName += fRdfDescriptor->Ports[i].Name;
  1846. portName.truncate(portNameSize);
  1847. }
  1848. if (LV2_IS_PORT_AUDIO(portTypes))
  1849. {
  1850. if (LV2_IS_PORT_INPUT(portTypes))
  1851. {
  1852. const uint32_t j = iAudioIn++;
  1853. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true, j);
  1854. pData->audioIn.ports[j].rindex = i;
  1855. if (forcedStereoIn)
  1856. {
  1857. portName += "_2";
  1858. pData->audioIn.ports[1].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true, 1);
  1859. pData->audioIn.ports[1].rindex = i;
  1860. }
  1861. }
  1862. else if (LV2_IS_PORT_OUTPUT(portTypes))
  1863. {
  1864. const uint32_t j = iAudioOut++;
  1865. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, j);
  1866. pData->audioOut.ports[j].rindex = i;
  1867. if (forcedStereoOut)
  1868. {
  1869. portName += "_2";
  1870. pData->audioOut.ports[1].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, 1);
  1871. pData->audioOut.ports[1].rindex = i;
  1872. }
  1873. }
  1874. else
  1875. carla_stderr2("WARNING - Got a broken Port (Audio, but not input or output)");
  1876. }
  1877. else if (LV2_IS_PORT_CV(portTypes))
  1878. {
  1879. const LV2_RDF_PortPoints portPoints(fRdfDescriptor->Ports[i].Points);
  1880. float min, max;
  1881. // min value
  1882. if (LV2_HAVE_MINIMUM_PORT_POINT(portPoints.Hints))
  1883. min = portPoints.Minimum;
  1884. else
  1885. min = -1.0f;
  1886. // max value
  1887. if (LV2_HAVE_MAXIMUM_PORT_POINT(portPoints.Hints))
  1888. max = portPoints.Maximum;
  1889. else
  1890. max = 1.0f;
  1891. if (LV2_IS_PORT_INPUT(portTypes))
  1892. {
  1893. const uint32_t j = iCvIn++;
  1894. pData->cvIn.ports[j].port = (CarlaEngineCVPort*)pData->client->addPort(kEnginePortTypeCV, portName, true, j);
  1895. pData->cvIn.ports[j].rindex = i;
  1896. pData->cvIn.ports[j].port->setRange(min, max);
  1897. }
  1898. else if (LV2_IS_PORT_OUTPUT(portTypes))
  1899. {
  1900. const uint32_t j = iCvOut++;
  1901. pData->cvOut.ports[j].port = (CarlaEngineCVPort*)pData->client->addPort(kEnginePortTypeCV, portName, false, j);
  1902. pData->cvOut.ports[j].rindex = i;
  1903. pData->cvOut.ports[j].port->setRange(min, max);
  1904. }
  1905. else
  1906. carla_stderr("WARNING - Got a broken Port (CV, but not input or output)");
  1907. }
  1908. else if (LV2_IS_PORT_ATOM_SEQUENCE(portTypes))
  1909. {
  1910. if (LV2_IS_PORT_INPUT(portTypes))
  1911. {
  1912. const uint32_t j = iEvIn++;
  1913. fDescriptor->connect_port(fHandle, i, &fEventsIn.data[j].atom->atoms);
  1914. if (fHandle2 != nullptr)
  1915. fDescriptor->connect_port(fHandle2, i, &fEventsIn.data[j].atom->atoms);
  1916. fEventsIn.data[j].rindex = i;
  1917. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  1918. fEventsIn.data[j].type |= CARLA_EVENT_TYPE_MIDI;
  1919. if (portTypes & LV2_PORT_DATA_PATCH_MESSAGE)
  1920. fEventsIn.data[j].type |= CARLA_EVENT_TYPE_MESSAGE;
  1921. if (portTypes & LV2_PORT_DATA_TIME_POSITION)
  1922. fEventsIn.data[j].type |= CARLA_EVENT_TYPE_TIME;
  1923. if (evIns.count() == 1)
  1924. {
  1925. fEventsIn.ctrl = &fEventsIn.data[j];
  1926. fEventsIn.ctrlIndex = j;
  1927. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  1928. needsCtrlIn = true;
  1929. }
  1930. else
  1931. {
  1932. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  1933. fEventsIn.data[j].port = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, j);
  1934. if (LV2_IS_PORT_DESIGNATION_CONTROL(fRdfDescriptor->Ports[i].Designation))
  1935. {
  1936. fEventsIn.ctrl = &fEventsIn.data[j];
  1937. fEventsIn.ctrlIndex = j;
  1938. }
  1939. }
  1940. }
  1941. else if (LV2_IS_PORT_OUTPUT(portTypes))
  1942. {
  1943. const uint32_t j = iEvOut++;
  1944. fDescriptor->connect_port(fHandle, i, &fEventsOut.data[j].atom->atoms);
  1945. if (fHandle2 != nullptr)
  1946. fDescriptor->connect_port(fHandle2, i, &fEventsOut.data[j].atom->atoms);
  1947. fEventsOut.data[j].rindex = i;
  1948. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  1949. fEventsOut.data[j].type |= CARLA_EVENT_TYPE_MIDI;
  1950. if (portTypes & LV2_PORT_DATA_PATCH_MESSAGE)
  1951. fEventsOut.data[j].type |= CARLA_EVENT_TYPE_MESSAGE;
  1952. if (portTypes & LV2_PORT_DATA_TIME_POSITION)
  1953. fEventsOut.data[j].type |= CARLA_EVENT_TYPE_TIME;
  1954. if (evOuts.count() == 1)
  1955. {
  1956. fEventsOut.ctrl = &fEventsOut.data[j];
  1957. fEventsOut.ctrlIndex = j;
  1958. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  1959. needsCtrlOut = true;
  1960. }
  1961. else
  1962. {
  1963. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  1964. fEventsOut.data[j].port = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, j);
  1965. if (LV2_IS_PORT_DESIGNATION_CONTROL(fRdfDescriptor->Ports[i].Designation))
  1966. {
  1967. fEventsOut.ctrl = &fEventsOut.data[j];
  1968. fEventsOut.ctrlIndex = j;
  1969. }
  1970. }
  1971. }
  1972. else
  1973. carla_stderr2("WARNING - Got a broken Port (Atom-Sequence, but not input or output)");
  1974. }
  1975. else if (LV2_IS_PORT_EVENT(portTypes))
  1976. {
  1977. if (LV2_IS_PORT_INPUT(portTypes))
  1978. {
  1979. const uint32_t j = iEvIn++;
  1980. fDescriptor->connect_port(fHandle, i, fEventsIn.data[j].event);
  1981. if (fHandle2 != nullptr)
  1982. fDescriptor->connect_port(fHandle2, i, fEventsIn.data[j].event);
  1983. fEventsIn.data[j].rindex = i;
  1984. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  1985. fEventsIn.data[j].type |= CARLA_EVENT_TYPE_MIDI;
  1986. if (portTypes & LV2_PORT_DATA_PATCH_MESSAGE)
  1987. fEventsIn.data[j].type |= CARLA_EVENT_TYPE_MESSAGE;
  1988. if (portTypes & LV2_PORT_DATA_TIME_POSITION)
  1989. fEventsIn.data[j].type |= CARLA_EVENT_TYPE_TIME;
  1990. if (evIns.count() == 1)
  1991. {
  1992. fEventsIn.ctrl = &fEventsIn.data[j];
  1993. fEventsIn.ctrlIndex = j;
  1994. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  1995. needsCtrlIn = true;
  1996. }
  1997. else
  1998. {
  1999. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  2000. fEventsIn.data[j].port = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, j);
  2001. if (LV2_IS_PORT_DESIGNATION_CONTROL(fRdfDescriptor->Ports[i].Designation))
  2002. {
  2003. fEventsIn.ctrl = &fEventsIn.data[j];
  2004. fEventsIn.ctrlIndex = j;
  2005. }
  2006. }
  2007. }
  2008. else if (LV2_IS_PORT_OUTPUT(portTypes))
  2009. {
  2010. const uint32_t j = iEvOut++;
  2011. fDescriptor->connect_port(fHandle, i, fEventsOut.data[j].event);
  2012. if (fHandle2 != nullptr)
  2013. fDescriptor->connect_port(fHandle2, i, fEventsOut.data[j].event);
  2014. fEventsOut.data[j].rindex = i;
  2015. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  2016. fEventsOut.data[j].type |= CARLA_EVENT_TYPE_MIDI;
  2017. if (portTypes & LV2_PORT_DATA_PATCH_MESSAGE)
  2018. fEventsOut.data[j].type |= CARLA_EVENT_TYPE_MESSAGE;
  2019. if (portTypes & LV2_PORT_DATA_TIME_POSITION)
  2020. fEventsOut.data[j].type |= CARLA_EVENT_TYPE_TIME;
  2021. if (evOuts.count() == 1)
  2022. {
  2023. fEventsOut.ctrl = &fEventsOut.data[j];
  2024. fEventsOut.ctrlIndex = j;
  2025. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  2026. needsCtrlOut = true;
  2027. }
  2028. else
  2029. {
  2030. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  2031. fEventsOut.data[j].port = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, j);
  2032. if (LV2_IS_PORT_DESIGNATION_CONTROL(fRdfDescriptor->Ports[i].Designation))
  2033. {
  2034. fEventsOut.ctrl = &fEventsOut.data[j];
  2035. fEventsOut.ctrlIndex = j;
  2036. }
  2037. }
  2038. }
  2039. else
  2040. carla_stderr2("WARNING - Got a broken Port (Event, but not input or output)");
  2041. }
  2042. else if (LV2_IS_PORT_MIDI_LL(portTypes))
  2043. {
  2044. if (LV2_IS_PORT_INPUT(portTypes))
  2045. {
  2046. const uint32_t j = iEvIn++;
  2047. fDescriptor->connect_port(fHandle, i, &fEventsIn.data[j].midi);
  2048. if (fHandle2 != nullptr)
  2049. fDescriptor->connect_port(fHandle2, i, &fEventsIn.data[j].midi);
  2050. fEventsIn.data[j].type |= CARLA_EVENT_TYPE_MIDI;
  2051. fEventsIn.data[j].rindex = i;
  2052. if (evIns.count() == 1)
  2053. {
  2054. needsCtrlIn = true;
  2055. fEventsIn.ctrl = &fEventsIn.data[j];
  2056. fEventsIn.ctrlIndex = j;
  2057. }
  2058. else
  2059. {
  2060. fEventsIn.data[j].port = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, j);
  2061. if (LV2_IS_PORT_DESIGNATION_CONTROL(fRdfDescriptor->Ports[i].Designation))
  2062. {
  2063. fEventsIn.ctrl = &fEventsIn.data[j];
  2064. fEventsIn.ctrlIndex = j;
  2065. }
  2066. }
  2067. }
  2068. else if (LV2_IS_PORT_OUTPUT(portTypes))
  2069. {
  2070. const uint32_t j = iEvOut++;
  2071. fDescriptor->connect_port(fHandle, i, &fEventsOut.data[j].midi);
  2072. if (fHandle2 != nullptr)
  2073. fDescriptor->connect_port(fHandle2, i, &fEventsOut.data[j].midi);
  2074. fEventsOut.data[j].type |= CARLA_EVENT_TYPE_MIDI;
  2075. fEventsOut.data[j].rindex = i;
  2076. if (evOuts.count() == 1)
  2077. {
  2078. needsCtrlOut = true;
  2079. fEventsOut.ctrl = &fEventsOut.data[j];
  2080. fEventsOut.ctrlIndex = j;
  2081. }
  2082. else
  2083. {
  2084. fEventsOut.data[j].port = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, j);
  2085. if (LV2_IS_PORT_DESIGNATION_CONTROL(fRdfDescriptor->Ports[i].Designation))
  2086. {
  2087. fEventsOut.ctrl = &fEventsOut.data[j];
  2088. fEventsOut.ctrlIndex = j;
  2089. }
  2090. }
  2091. }
  2092. else
  2093. carla_stderr2("WARNING - Got a broken Port (MIDI, but not input or output)");
  2094. }
  2095. else if (LV2_IS_PORT_CONTROL(portTypes))
  2096. {
  2097. const LV2_Property portProps(fRdfDescriptor->Ports[i].Properties);
  2098. const LV2_Property portDesignation(fRdfDescriptor->Ports[i].Designation);
  2099. const LV2_RDF_PortPoints portPoints(fRdfDescriptor->Ports[i].Points);
  2100. const uint32_t j = iCtrl++;
  2101. pData->param.data[j].index = static_cast<int32_t>(j);
  2102. pData->param.data[j].rindex = static_cast<int32_t>(i);
  2103. float min, max, def, step, stepSmall, stepLarge;
  2104. // min value
  2105. if (LV2_HAVE_MINIMUM_PORT_POINT(portPoints.Hints))
  2106. min = portPoints.Minimum;
  2107. else
  2108. min = 0.0f;
  2109. // max value
  2110. if (LV2_HAVE_MAXIMUM_PORT_POINT(portPoints.Hints))
  2111. max = portPoints.Maximum;
  2112. else
  2113. max = 1.0f;
  2114. if (LV2_IS_PORT_SAMPLE_RATE(portProps))
  2115. {
  2116. min *= sampleRate;
  2117. max *= sampleRate;
  2118. pData->param.data[j].hints |= PARAMETER_USES_SAMPLERATE;
  2119. }
  2120. // stupid hack for ir.lv2 (broken plugin)
  2121. if (std::strcmp(fRdfDescriptor->URI, "http://factorial.hu/plugins/lv2/ir") == 0 && std::strncmp(fRdfDescriptor->Ports[i].Name, "FileHash", 8) == 0)
  2122. {
  2123. min = 0.0f;
  2124. max = (float)0xffffff;
  2125. }
  2126. if (min >= max)
  2127. {
  2128. carla_stderr2("WARNING - Broken plugin parameter '%s': min >= max", fRdfDescriptor->Ports[i].Name);
  2129. max = min + 0.1f;
  2130. }
  2131. // default value
  2132. if (LV2_HAVE_DEFAULT_PORT_POINT(portPoints.Hints))
  2133. {
  2134. def = portPoints.Default;
  2135. }
  2136. else
  2137. {
  2138. // no default value
  2139. if (min < 0.0f && max > 0.0f)
  2140. def = 0.0f;
  2141. else
  2142. def = min;
  2143. }
  2144. if (def < min)
  2145. def = min;
  2146. else if (def > max)
  2147. def = max;
  2148. if (LV2_IS_PORT_TOGGLED(portProps))
  2149. {
  2150. step = max - min;
  2151. stepSmall = step;
  2152. stepLarge = step;
  2153. pData->param.data[j].hints |= PARAMETER_IS_BOOLEAN;
  2154. }
  2155. else if (LV2_IS_PORT_INTEGER(portProps))
  2156. {
  2157. step = 1.0f;
  2158. stepSmall = 1.0f;
  2159. stepLarge = 10.0f;
  2160. pData->param.data[j].hints |= PARAMETER_IS_INTEGER;
  2161. }
  2162. else
  2163. {
  2164. float range = max - min;
  2165. step = range/100.0f;
  2166. stepSmall = range/1000.0f;
  2167. stepLarge = range/10.0f;
  2168. }
  2169. if (LV2_IS_PORT_INPUT(portTypes))
  2170. {
  2171. pData->param.data[j].type = PARAMETER_INPUT;
  2172. if (LV2_IS_PORT_DESIGNATION_LATENCY(portDesignation))
  2173. {
  2174. carla_stderr("Plugin has latency input port, this should not happen!");
  2175. }
  2176. else if (LV2_IS_PORT_DESIGNATION_SAMPLE_RATE(portDesignation))
  2177. {
  2178. def = sampleRate;
  2179. step = 1.0f;
  2180. stepSmall = 1.0f;
  2181. stepLarge = 1.0f;
  2182. pData->param.special[j] = PARAMETER_SPECIAL_SAMPLE_RATE;
  2183. }
  2184. else if (LV2_IS_PORT_DESIGNATION_FREEWHEELING(portDesignation))
  2185. {
  2186. pData->param.special[j] = PARAMETER_SPECIAL_FREEWHEEL;
  2187. }
  2188. else if (LV2_IS_PORT_DESIGNATION_TIME(portDesignation))
  2189. {
  2190. pData->param.special[j] = PARAMETER_SPECIAL_TIME;
  2191. }
  2192. else
  2193. {
  2194. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  2195. pData->param.data[j].hints |= PARAMETER_IS_AUTOMABLE;
  2196. needsCtrlIn = true;
  2197. if (! LV2_IS_PORT_CAUSES_ARTIFACTS(portProps) &&
  2198. ! LV2_IS_PORT_ENUMERATION(portProps) &&
  2199. ! LV2_IS_PORT_EXPENSIVE(portProps) &&
  2200. ! LV2_IS_PORT_NOT_AUTOMATIC(portProps) &&
  2201. ! LV2_IS_PORT_NOT_ON_GUI(portProps) &&
  2202. ! LV2_IS_PORT_TRIGGER(portProps))
  2203. {
  2204. pData->param.data[j].hints |= PARAMETER_CAN_BE_CV_CONTROLLED;
  2205. }
  2206. }
  2207. // MIDI CC value
  2208. const LV2_RDF_PortMidiMap& portMidiMap(fRdfDescriptor->Ports[i].MidiMap);
  2209. if (LV2_IS_PORT_MIDI_MAP_CC(portMidiMap.Type))
  2210. {
  2211. if (portMidiMap.Number < MAX_MIDI_CONTROL && ! MIDI_IS_CONTROL_BANK_SELECT(portMidiMap.Number))
  2212. pData->param.data[j].mappedControlIndex = static_cast<int16_t>(portMidiMap.Number);
  2213. }
  2214. }
  2215. else if (LV2_IS_PORT_OUTPUT(portTypes))
  2216. {
  2217. pData->param.data[j].type = PARAMETER_OUTPUT;
  2218. if (LV2_IS_PORT_DESIGNATION_LATENCY(portDesignation))
  2219. {
  2220. min = 0.0f;
  2221. max = sampleRate;
  2222. def = 0.0f;
  2223. step = 1.0f;
  2224. stepSmall = 1.0f;
  2225. stepLarge = 1.0f;
  2226. pData->param.special[j] = PARAMETER_SPECIAL_LATENCY;
  2227. CARLA_SAFE_ASSERT_INT2(fLatencyIndex == static_cast<int32_t>(j), fLatencyIndex, j);
  2228. }
  2229. else if (LV2_IS_PORT_DESIGNATION_SAMPLE_RATE(portDesignation))
  2230. {
  2231. def = sampleRate;
  2232. step = 1.0f;
  2233. stepSmall = 1.0f;
  2234. stepLarge = 1.0f;
  2235. pData->param.special[j] = PARAMETER_SPECIAL_SAMPLE_RATE;
  2236. }
  2237. else if (LV2_IS_PORT_DESIGNATION_FREEWHEELING(portDesignation))
  2238. {
  2239. carla_stderr("Plugin has freewheeling output port, this should not happen!");
  2240. }
  2241. else if (LV2_IS_PORT_DESIGNATION_TIME(portDesignation))
  2242. {
  2243. pData->param.special[j] = PARAMETER_SPECIAL_TIME;
  2244. }
  2245. else
  2246. {
  2247. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  2248. pData->param.data[j].hints |= PARAMETER_IS_AUTOMABLE;
  2249. needsCtrlOut = true;
  2250. }
  2251. }
  2252. else
  2253. {
  2254. pData->param.data[j].type = PARAMETER_UNKNOWN;
  2255. carla_stderr2("WARNING - Got a broken Port (Control, but not input or output)");
  2256. }
  2257. // extra parameter hints
  2258. if (LV2_IS_PORT_LOGARITHMIC(portProps))
  2259. pData->param.data[j].hints |= PARAMETER_IS_LOGARITHMIC;
  2260. if (LV2_IS_PORT_TRIGGER(portProps))
  2261. pData->param.data[j].hints |= PARAMETER_IS_TRIGGER;
  2262. if (LV2_IS_PORT_STRICT_BOUNDS(portProps))
  2263. pData->param.data[j].hints |= PARAMETER_IS_STRICT_BOUNDS;
  2264. if (LV2_IS_PORT_ENUMERATION(portProps))
  2265. pData->param.data[j].hints |= PARAMETER_USES_SCALEPOINTS;
  2266. // check if parameter is not enabled or automable
  2267. if (LV2_IS_PORT_NOT_ON_GUI(portProps))
  2268. pData->param.data[j].hints &= ~(PARAMETER_IS_ENABLED|PARAMETER_IS_AUTOMABLE);
  2269. else if (LV2_IS_PORT_CAUSES_ARTIFACTS(portProps) || LV2_IS_PORT_EXPENSIVE(portProps))
  2270. pData->param.data[j].hints &= ~PARAMETER_IS_AUTOMABLE;
  2271. else if (LV2_IS_PORT_NOT_AUTOMATIC(portProps) || LV2_IS_PORT_NON_AUTOMABLE(portProps))
  2272. pData->param.data[j].hints &= ~PARAMETER_IS_AUTOMABLE;
  2273. pData->param.ranges[j].min = min;
  2274. pData->param.ranges[j].max = max;
  2275. pData->param.ranges[j].def = def;
  2276. pData->param.ranges[j].step = step;
  2277. pData->param.ranges[j].stepSmall = stepSmall;
  2278. pData->param.ranges[j].stepLarge = stepLarge;
  2279. // Start parameters in their default values (except freewheel, which is off by default)
  2280. if (pData->param.data[j].type == PARAMETER_INPUT && pData->param.special[j] == PARAMETER_SPECIAL_FREEWHEEL)
  2281. fParamBuffers[j] = min;
  2282. else
  2283. fParamBuffers[j] = def;
  2284. fDescriptor->connect_port(fHandle, i, &fParamBuffers[j]);
  2285. if (fHandle2 != nullptr)
  2286. fDescriptor->connect_port(fHandle2, i, &fParamBuffers[j]);
  2287. }
  2288. else
  2289. {
  2290. // Port Type not supported, but it's optional anyway
  2291. fDescriptor->connect_port(fHandle, i, nullptr);
  2292. if (fHandle2 != nullptr)
  2293. fDescriptor->connect_port(fHandle2, i, nullptr);
  2294. }
  2295. }
  2296. for (uint32_t i=0; i < fRdfDescriptor->ParameterCount; ++i)
  2297. {
  2298. const LV2_RDF_Parameter& rdfParam(fRdfDescriptor->Parameters[i]);
  2299. switch (rdfParam.Type)
  2300. {
  2301. case LV2_PARAMETER_BOOL:
  2302. case LV2_PARAMETER_INT:
  2303. // case LV2_PARAMETER_LONG:
  2304. case LV2_PARAMETER_FLOAT:
  2305. case LV2_PARAMETER_DOUBLE:
  2306. break;
  2307. default:
  2308. continue;
  2309. }
  2310. const LV2_RDF_PortPoints& portPoints(rdfParam.Points);
  2311. const uint32_t j = iCtrl++;
  2312. pData->param.data[j].index = static_cast<int32_t>(j);
  2313. pData->param.data[j].rindex = static_cast<int32_t>(fRdfDescriptor->PortCount + i);
  2314. float min, max, def, step, stepSmall, stepLarge;
  2315. // min value
  2316. if (LV2_HAVE_MINIMUM_PORT_POINT(portPoints.Hints))
  2317. min = portPoints.Minimum;
  2318. else
  2319. min = 0.0f;
  2320. // max value
  2321. if (LV2_HAVE_MAXIMUM_PORT_POINT(portPoints.Hints))
  2322. max = portPoints.Maximum;
  2323. else
  2324. max = 1.0f;
  2325. if (min >= max)
  2326. {
  2327. carla_stderr2("WARNING - Broken plugin parameter '%s': min >= max", rdfParam.Label);
  2328. max = min + 0.1f;
  2329. }
  2330. // default value
  2331. if (LV2_HAVE_DEFAULT_PORT_POINT(portPoints.Hints))
  2332. {
  2333. def = portPoints.Default;
  2334. }
  2335. else
  2336. {
  2337. // no default value
  2338. if (min < 0.0f && max > 0.0f)
  2339. def = 0.0f;
  2340. else
  2341. def = min;
  2342. }
  2343. if (def < min)
  2344. def = min;
  2345. else if (def > max)
  2346. def = max;
  2347. switch (rdfParam.Type)
  2348. {
  2349. case LV2_PARAMETER_BOOL:
  2350. step = max - min;
  2351. stepSmall = step;
  2352. stepLarge = step;
  2353. pData->param.data[j].hints |= PARAMETER_IS_BOOLEAN;
  2354. break;
  2355. case LV2_PARAMETER_INT:
  2356. case LV2_PARAMETER_LONG:
  2357. step = 1.0f;
  2358. stepSmall = 1.0f;
  2359. stepLarge = 10.0f;
  2360. pData->param.data[j].hints |= PARAMETER_IS_INTEGER;
  2361. break;
  2362. default:
  2363. const float range = max - min;
  2364. step = range/100.0f;
  2365. stepSmall = range/1000.0f;
  2366. stepLarge = range/10.0f;
  2367. break;
  2368. }
  2369. if (rdfParam.Input)
  2370. {
  2371. pData->param.data[j].type = PARAMETER_INPUT;
  2372. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  2373. pData->param.data[j].hints |= PARAMETER_IS_AUTOMABLE;
  2374. needsCtrlIn = true;
  2375. }
  2376. else
  2377. {
  2378. pData->param.data[j].type = PARAMETER_OUTPUT;
  2379. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  2380. pData->param.data[j].hints |= PARAMETER_IS_AUTOMABLE;
  2381. needsCtrlOut = true;
  2382. }
  2383. pData->param.ranges[j].min = min;
  2384. pData->param.ranges[j].max = max;
  2385. pData->param.ranges[j].def = def;
  2386. pData->param.ranges[j].step = step;
  2387. pData->param.ranges[j].stepSmall = stepSmall;
  2388. pData->param.ranges[j].stepLarge = stepLarge;
  2389. fParamBuffers[j] = def;
  2390. }
  2391. if (needsCtrlIn)
  2392. {
  2393. portName.clear();
  2394. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  2395. {
  2396. portName = pData->name;
  2397. portName += ":";
  2398. }
  2399. portName += "events-in";
  2400. portName.truncate(portNameSize);
  2401. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, 0);
  2402. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2403. pData->event.cvSourcePorts = pData->client->createCVSourcePorts();
  2404. #endif
  2405. }
  2406. if (needsCtrlOut)
  2407. {
  2408. portName.clear();
  2409. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  2410. {
  2411. portName = pData->name;
  2412. portName += ":";
  2413. }
  2414. portName += "events-out";
  2415. portName.truncate(portNameSize);
  2416. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, 0);
  2417. }
  2418. if (fExt.worker != nullptr && fEventsIn.ctrl != nullptr)
  2419. {
  2420. fAtomBufferWorkerIn.createBuffer(eventBufferSize);
  2421. fAtomBufferWorkerResp.createBuffer(eventBufferSize);
  2422. fAtomBufferWorkerInTmpData = new uint8_t[fAtomBufferWorkerIn.getSize()];
  2423. }
  2424. if (fRdfDescriptor->ParameterCount > 0 ||
  2425. (fUI.type != UI::TYPE_NULL && fEventsIn.count > 0 && (fEventsIn.data[0].type & CARLA_EVENT_DATA_ATOM) != 0))
  2426. fAtomBufferEvIn.createBuffer(eventBufferSize);
  2427. if (fUI.type != UI::TYPE_NULL && fEventsOut.count > 0 && (fEventsOut.data[0].type & CARLA_EVENT_DATA_ATOM) != 0)
  2428. {
  2429. fAtomBufferUiOut.createBuffer(std::min(eventBufferSize*32, 1638400U));
  2430. fAtomBufferUiOutTmpData = new uint8_t[fAtomBufferUiOut.getSize()];
  2431. }
  2432. if (fEventsIn.ctrl != nullptr && fEventsIn.ctrl->port == nullptr)
  2433. fEventsIn.ctrl->port = pData->event.portIn;
  2434. if (fEventsOut.ctrl != nullptr && fEventsOut.ctrl->port == nullptr)
  2435. fEventsOut.ctrl->port = pData->event.portOut;
  2436. if (fEventsIn.ctrl != nullptr && fExt.midnam != nullptr)
  2437. {
  2438. if (char* const midnam = fExt.midnam->midnam(fHandle))
  2439. {
  2440. fEventsIn.ctrl->port->setMetaData("http://www.midi.org/dtds/MIDINameDocument10.dtd",
  2441. midnam, "text/xml");
  2442. if (fExt.midnam->free != nullptr)
  2443. fExt.midnam->free(midnam);
  2444. }
  2445. }
  2446. if (forcedStereoIn || forcedStereoOut)
  2447. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  2448. else
  2449. pData->options &= ~PLUGIN_OPTION_FORCE_STEREO;
  2450. // plugin hints
  2451. pData->hints = (pData->hints & PLUGIN_HAS_INLINE_DISPLAY) ? PLUGIN_HAS_INLINE_DISPLAY : 0;
  2452. if (isRealtimeSafe())
  2453. pData->hints |= PLUGIN_IS_RTSAFE;
  2454. if (fUI.type != UI::TYPE_NULL || fFilePathURI.isNotEmpty())
  2455. {
  2456. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  2457. if (fUI.type == UI::TYPE_EMBED || fUI.type == UI::TYPE_EXTERNAL)
  2458. pData->hints |= PLUGIN_NEEDS_UI_MAIN_THREAD;
  2459. }
  2460. if (LV2_IS_GENERATOR(fRdfDescriptor->Type[0], fRdfDescriptor->Type[1]))
  2461. pData->hints |= PLUGIN_IS_SYNTH;
  2462. if (aOuts > 0 && (aIns == aOuts || aIns == 1))
  2463. pData->hints |= PLUGIN_CAN_DRYWET;
  2464. if (aOuts > 0)
  2465. pData->hints |= PLUGIN_CAN_VOLUME;
  2466. if (aOuts >= 2 && aOuts % 2 == 0)
  2467. pData->hints |= PLUGIN_CAN_BALANCE;
  2468. // extra plugin hints
  2469. pData->extraHints = 0x0;
  2470. // check initial latency
  2471. findInitialLatencyValue(aIns, aOuts);
  2472. bufferSizeChanged(pData->engine->getBufferSize());
  2473. reloadPrograms(true);
  2474. evIns.clear();
  2475. evOuts.clear();
  2476. if (pData->active)
  2477. activate();
  2478. carla_debug("CarlaPluginLV2::reload() - end");
  2479. }
  2480. void findInitialLatencyValue(const uint32_t aIns, const uint32_t aOuts) const
  2481. {
  2482. if (fLatencyIndex < 0)
  2483. return;
  2484. // we need to pre-run the plugin so it can update its latency control-port
  2485. const uint32_t bufferSize = static_cast<uint32_t>(fLv2Options.nominalBufferSize);
  2486. float tmpIn [(aIns > 0) ? aIns : 1][bufferSize];
  2487. float tmpOut[(aOuts > 0) ? aOuts : 1][bufferSize];
  2488. for (uint32_t j=0; j < aIns; ++j)
  2489. {
  2490. carla_zeroFloats(tmpIn[j], bufferSize);
  2491. try {
  2492. fDescriptor->connect_port(fHandle, pData->audioIn.ports[j].rindex, tmpIn[j]);
  2493. } CARLA_SAFE_EXCEPTION("LV2 connect_port latency input");
  2494. }
  2495. for (uint32_t j=0; j < aOuts; ++j)
  2496. {
  2497. carla_zeroFloats(tmpOut[j], bufferSize);
  2498. try {
  2499. fDescriptor->connect_port(fHandle, pData->audioOut.ports[j].rindex, tmpOut[j]);
  2500. } CARLA_SAFE_EXCEPTION("LV2 connect_port latency output");
  2501. }
  2502. if (fDescriptor->activate != nullptr)
  2503. {
  2504. try {
  2505. fDescriptor->activate(fHandle);
  2506. } CARLA_SAFE_EXCEPTION("LV2 latency activate");
  2507. }
  2508. try {
  2509. fDescriptor->run(fHandle, bufferSize);
  2510. } CARLA_SAFE_EXCEPTION("LV2 latency run");
  2511. if (fDescriptor->deactivate != nullptr)
  2512. {
  2513. try {
  2514. fDescriptor->deactivate(fHandle);
  2515. } CARLA_SAFE_EXCEPTION("LV2 latency deactivate");
  2516. }
  2517. // done, let's get the value
  2518. if (const uint32_t latency = getLatencyInFrames())
  2519. {
  2520. pData->client->setLatency(latency);
  2521. #ifndef BUILD_BRIDGE
  2522. pData->latency.recreateBuffers(std::max(aIns, aOuts), latency);
  2523. #endif
  2524. }
  2525. }
  2526. void reloadPrograms(const bool doInit) override
  2527. {
  2528. carla_debug("CarlaPluginLV2::reloadPrograms(%s)", bool2str(doInit));
  2529. const uint32_t oldCount = pData->midiprog.count;
  2530. const int32_t current = pData->midiprog.current;
  2531. // special LV2 programs handling
  2532. if (doInit)
  2533. {
  2534. pData->prog.clear();
  2535. const uint32_t presetCount(fRdfDescriptor->PresetCount);
  2536. if (presetCount > 0)
  2537. {
  2538. pData->prog.createNew(presetCount);
  2539. for (uint32_t i=0; i < presetCount; ++i)
  2540. pData->prog.names[i] = carla_strdup(fRdfDescriptor->Presets[i].Label);
  2541. }
  2542. }
  2543. // Delete old programs
  2544. pData->midiprog.clear();
  2545. // Query new programs
  2546. uint32_t newCount = 0;
  2547. if (fExt.programs != nullptr && fExt.programs->get_program != nullptr && fExt.programs->select_program != nullptr)
  2548. {
  2549. for (; fExt.programs->get_program(fHandle, newCount);)
  2550. ++newCount;
  2551. }
  2552. if (newCount > 0)
  2553. {
  2554. pData->midiprog.createNew(newCount);
  2555. // Update data
  2556. for (uint32_t i=0; i < newCount; ++i)
  2557. {
  2558. const LV2_Program_Descriptor* const pdesc(fExt.programs->get_program(fHandle, i));
  2559. CARLA_SAFE_ASSERT_CONTINUE(pdesc != nullptr);
  2560. CARLA_SAFE_ASSERT(pdesc->name != nullptr);
  2561. pData->midiprog.data[i].bank = pdesc->bank;
  2562. pData->midiprog.data[i].program = pdesc->program;
  2563. pData->midiprog.data[i].name = carla_strdup(pdesc->name);
  2564. }
  2565. }
  2566. if (doInit)
  2567. {
  2568. if (newCount > 0)
  2569. {
  2570. setMidiProgram(0, false, false, false, true);
  2571. }
  2572. else
  2573. {
  2574. // load default state
  2575. if (LilvState* const state = Lv2WorldClass::getInstance().getStateFromURI(fDescriptor->URI, (const LV2_URID_Map*)fFeatures[kFeatureIdUridMap]->data))
  2576. {
  2577. lilv_state_restore(state, fExt.state, fHandle, carla_lilv_set_port_value, this, 0, fFeatures);
  2578. if (fHandle2 != nullptr)
  2579. lilv_state_restore(state, fExt.state, fHandle2, carla_lilv_set_port_value, this, 0, fFeatures);
  2580. lilv_state_free(state);
  2581. }
  2582. }
  2583. }
  2584. else
  2585. {
  2586. // Check if current program is invalid
  2587. bool programChanged = false;
  2588. if (newCount == oldCount+1)
  2589. {
  2590. // one midi program added, probably created by user
  2591. pData->midiprog.current = static_cast<int32_t>(oldCount);
  2592. programChanged = true;
  2593. }
  2594. else if (current < 0 && newCount > 0)
  2595. {
  2596. // programs exist now, but not before
  2597. pData->midiprog.current = 0;
  2598. programChanged = true;
  2599. }
  2600. else if (current >= 0 && newCount == 0)
  2601. {
  2602. // programs existed before, but not anymore
  2603. pData->midiprog.current = -1;
  2604. programChanged = true;
  2605. }
  2606. else if (current >= static_cast<int32_t>(newCount))
  2607. {
  2608. // current midi program > count
  2609. pData->midiprog.current = 0;
  2610. programChanged = true;
  2611. }
  2612. else
  2613. {
  2614. // no change
  2615. pData->midiprog.current = current;
  2616. }
  2617. if (programChanged)
  2618. setMidiProgram(pData->midiprog.current, true, true, true, false);
  2619. pData->engine->callback(true, true, ENGINE_CALLBACK_RELOAD_PROGRAMS, pData->id, 0, 0, 0, 0.0f, nullptr);
  2620. }
  2621. }
  2622. // -------------------------------------------------------------------
  2623. // Plugin processing
  2624. void activate() noexcept override
  2625. {
  2626. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr,);
  2627. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr,);
  2628. if (fDescriptor->activate != nullptr)
  2629. {
  2630. try {
  2631. fDescriptor->activate(fHandle);
  2632. } CARLA_SAFE_EXCEPTION("LV2 activate");
  2633. if (fHandle2 != nullptr)
  2634. {
  2635. try {
  2636. fDescriptor->activate(fHandle2);
  2637. } CARLA_SAFE_EXCEPTION("LV2 activate #2");
  2638. }
  2639. }
  2640. fFirstActive = true;
  2641. }
  2642. void deactivate() noexcept override
  2643. {
  2644. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr,);
  2645. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr,);
  2646. if (fDescriptor->deactivate != nullptr)
  2647. {
  2648. try {
  2649. fDescriptor->deactivate(fHandle);
  2650. } CARLA_SAFE_EXCEPTION("LV2 deactivate");
  2651. if (fHandle2 != nullptr)
  2652. {
  2653. try {
  2654. fDescriptor->deactivate(fHandle2);
  2655. } CARLA_SAFE_EXCEPTION("LV2 deactivate #2");
  2656. }
  2657. }
  2658. }
  2659. void process(const float* const* const audioIn, float** const audioOut,
  2660. const float* const* const cvIn, float** const cvOut, const uint32_t frames) override
  2661. {
  2662. // --------------------------------------------------------------------------------------------------------
  2663. // Check if active
  2664. if (! pData->active)
  2665. {
  2666. // disable any output sound
  2667. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  2668. carla_zeroFloats(audioOut[i], frames);
  2669. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  2670. carla_zeroFloats(cvOut[i], frames);
  2671. return;
  2672. }
  2673. // --------------------------------------------------------------------------------------------------------
  2674. // Event itenerators from different APIs (input)
  2675. LV2_Atom_Buffer_Iterator evInAtomIters[fEventsIn.count];
  2676. LV2_Event_Iterator evInEventIters[fEventsIn.count];
  2677. LV2_MIDIState evInMidiStates[fEventsIn.count];
  2678. for (uint32_t i=0; i < fEventsIn.count; ++i)
  2679. {
  2680. if (fEventsIn.data[i].type & CARLA_EVENT_DATA_ATOM)
  2681. {
  2682. lv2_atom_buffer_reset(fEventsIn.data[i].atom, true);
  2683. lv2_atom_buffer_begin(&evInAtomIters[i], fEventsIn.data[i].atom);
  2684. }
  2685. else if (fEventsIn.data[i].type & CARLA_EVENT_DATA_EVENT)
  2686. {
  2687. lv2_event_buffer_reset(fEventsIn.data[i].event, LV2_EVENT_AUDIO_STAMP, fEventsIn.data[i].event->data);
  2688. lv2_event_begin(&evInEventIters[i], fEventsIn.data[i].event);
  2689. }
  2690. else if (fEventsIn.data[i].type & CARLA_EVENT_DATA_MIDI_LL)
  2691. {
  2692. fEventsIn.data[i].midi.event_count = 0;
  2693. fEventsIn.data[i].midi.size = 0;
  2694. evInMidiStates[i].midi = &fEventsIn.data[i].midi;
  2695. evInMidiStates[i].frame_count = frames;
  2696. evInMidiStates[i].position = 0;
  2697. }
  2698. }
  2699. for (uint32_t i=0; i < fEventsOut.count; ++i)
  2700. {
  2701. if (fEventsOut.data[i].type & CARLA_EVENT_DATA_ATOM)
  2702. {
  2703. lv2_atom_buffer_reset(fEventsOut.data[i].atom, false);
  2704. }
  2705. else if (fEventsOut.data[i].type & CARLA_EVENT_DATA_EVENT)
  2706. {
  2707. lv2_event_buffer_reset(fEventsOut.data[i].event, LV2_EVENT_AUDIO_STAMP, fEventsOut.data[i].event->data);
  2708. }
  2709. else if (fEventsOut.data[i].type & CARLA_EVENT_DATA_MIDI_LL)
  2710. {
  2711. // not needed
  2712. }
  2713. }
  2714. // --------------------------------------------------------------------------------------------------------
  2715. // Check if needs reset
  2716. if (pData->needsReset)
  2717. {
  2718. if (fEventsIn.ctrl != nullptr && (fEventsIn.ctrl->type & CARLA_EVENT_TYPE_MIDI) != 0)
  2719. {
  2720. const uint32_t j = fEventsIn.ctrlIndex;
  2721. CARLA_ASSERT(j < fEventsIn.count);
  2722. uint8_t midiData[3] = { 0, 0, 0 };
  2723. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  2724. {
  2725. for (uint8_t i=0; i < MAX_MIDI_CHANNELS; ++i)
  2726. {
  2727. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (i & MIDI_CHANNEL_BIT));
  2728. midiData[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  2729. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  2730. lv2_atom_buffer_write(&evInAtomIters[j], 0, 0, kUridMidiEvent, 3, midiData);
  2731. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  2732. lv2_event_write(&evInEventIters[j], 0, 0, kUridMidiEvent, 3, midiData);
  2733. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  2734. lv2midi_put_event(&evInMidiStates[j], 0.0, 3, midiData);
  2735. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (i & MIDI_CHANNEL_BIT));
  2736. midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  2737. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  2738. lv2_atom_buffer_write(&evInAtomIters[j], 0, 0, kUridMidiEvent, 3, midiData);
  2739. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  2740. lv2_event_write(&evInEventIters[j], 0, 0, kUridMidiEvent, 3, midiData);
  2741. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  2742. lv2midi_put_event(&evInMidiStates[j], 0.0, 3, midiData);
  2743. }
  2744. }
  2745. else if (pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  2746. {
  2747. for (uint8_t k=0; k < MAX_MIDI_NOTE; ++k)
  2748. {
  2749. midiData[0] = uint8_t(MIDI_STATUS_NOTE_OFF | (pData->ctrlChannel & MIDI_CHANNEL_BIT));
  2750. midiData[1] = k;
  2751. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  2752. lv2_atom_buffer_write(&evInAtomIters[j], 0, 0, kUridMidiEvent, 3, midiData);
  2753. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  2754. lv2_event_write(&evInEventIters[j], 0, 0, kUridMidiEvent, 3, midiData);
  2755. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  2756. lv2midi_put_event(&evInMidiStates[j], 0.0, 3, midiData);
  2757. }
  2758. }
  2759. }
  2760. pData->needsReset = false;
  2761. }
  2762. // --------------------------------------------------------------------------------------------------------
  2763. // TimeInfo
  2764. const EngineTimeInfo timeInfo(pData->engine->getTimeInfo());
  2765. if (fFirstActive || fLastTimeInfo != timeInfo)
  2766. {
  2767. bool doPostRt;
  2768. int32_t rindex;
  2769. const double barBeat = static_cast<double>(timeInfo.bbt.beat - 1)
  2770. + (timeInfo.bbt.tick / timeInfo.bbt.ticksPerBeat);
  2771. // update input ports
  2772. for (uint32_t k=0; k < pData->param.count; ++k)
  2773. {
  2774. if (pData->param.data[k].type != PARAMETER_INPUT)
  2775. continue;
  2776. if (pData->param.special[k] != PARAMETER_SPECIAL_TIME)
  2777. continue;
  2778. doPostRt = false;
  2779. rindex = pData->param.data[k].rindex;
  2780. CARLA_SAFE_ASSERT_CONTINUE(rindex >= 0 && rindex < static_cast<int32_t>(fRdfDescriptor->PortCount));
  2781. switch (fRdfDescriptor->Ports[rindex].Designation)
  2782. {
  2783. // Non-BBT
  2784. case LV2_PORT_DESIGNATION_TIME_SPEED:
  2785. if (fLastTimeInfo.playing != timeInfo.playing)
  2786. {
  2787. fParamBuffers[k] = timeInfo.playing ? 1.0f : 0.0f;
  2788. doPostRt = true;
  2789. }
  2790. break;
  2791. case LV2_PORT_DESIGNATION_TIME_FRAME:
  2792. if (fLastTimeInfo.frame != timeInfo.frame)
  2793. {
  2794. fParamBuffers[k] = static_cast<float>(timeInfo.frame);
  2795. doPostRt = true;
  2796. }
  2797. break;
  2798. case LV2_PORT_DESIGNATION_TIME_FRAMES_PER_SECOND:
  2799. break;
  2800. // BBT
  2801. case LV2_PORT_DESIGNATION_TIME_BAR:
  2802. if (timeInfo.bbt.valid && fLastTimeInfo.bbt.bar != timeInfo.bbt.bar)
  2803. {
  2804. fParamBuffers[k] = static_cast<float>(timeInfo.bbt.bar - 1);
  2805. doPostRt = true;
  2806. }
  2807. break;
  2808. case LV2_PORT_DESIGNATION_TIME_BAR_BEAT:
  2809. if (timeInfo.bbt.valid && (carla_isNotEqual(fLastTimeInfo.bbt.tick, timeInfo.bbt.tick) ||
  2810. fLastTimeInfo.bbt.beat != timeInfo.bbt.beat))
  2811. {
  2812. fParamBuffers[k] = static_cast<float>(barBeat);
  2813. doPostRt = true;
  2814. }
  2815. break;
  2816. case LV2_PORT_DESIGNATION_TIME_BEAT:
  2817. if (timeInfo.bbt.valid && fLastTimeInfo.bbt.beat != timeInfo.bbt.beat)
  2818. {
  2819. fParamBuffers[k] = static_cast<float>(timeInfo.bbt.beat - 1);
  2820. doPostRt = true;
  2821. }
  2822. break;
  2823. case LV2_PORT_DESIGNATION_TIME_BEAT_UNIT:
  2824. if (timeInfo.bbt.valid && carla_isNotEqual(fLastTimeInfo.bbt.beatType, timeInfo.bbt.beatType))
  2825. {
  2826. fParamBuffers[k] = timeInfo.bbt.beatType;
  2827. doPostRt = true;
  2828. }
  2829. break;
  2830. case LV2_PORT_DESIGNATION_TIME_BEATS_PER_BAR:
  2831. if (timeInfo.bbt.valid && carla_isNotEqual(fLastTimeInfo.bbt.beatsPerBar, timeInfo.bbt.beatsPerBar))
  2832. {
  2833. fParamBuffers[k] = timeInfo.bbt.beatsPerBar;
  2834. doPostRt = true;
  2835. }
  2836. break;
  2837. case LV2_PORT_DESIGNATION_TIME_BEATS_PER_MINUTE:
  2838. if (timeInfo.bbt.valid && carla_isNotEqual(fLastTimeInfo.bbt.beatsPerMinute, timeInfo.bbt.beatsPerMinute))
  2839. {
  2840. fParamBuffers[k] = static_cast<float>(timeInfo.bbt.beatsPerMinute);
  2841. doPostRt = true;
  2842. }
  2843. break;
  2844. case LV2_PORT_DESIGNATION_TIME_TICKS_PER_BEAT:
  2845. if (timeInfo.bbt.valid && carla_isNotEqual(fLastTimeInfo.bbt.ticksPerBeat, timeInfo.bbt.ticksPerBeat))
  2846. {
  2847. fParamBuffers[k] = static_cast<float>(timeInfo.bbt.ticksPerBeat);
  2848. doPostRt = true;
  2849. }
  2850. break;
  2851. }
  2852. if (doPostRt)
  2853. pData->postponeRtEvent(kPluginPostRtEventParameterChange,
  2854. true,
  2855. static_cast<int32_t>(k),
  2856. 0,
  2857. 0,
  2858. fParamBuffers[k]);
  2859. }
  2860. for (uint32_t i=0; i < fEventsIn.count; ++i)
  2861. {
  2862. if ((fEventsIn.data[i].type & CARLA_EVENT_DATA_ATOM) == 0 || (fEventsIn.data[i].type & CARLA_EVENT_TYPE_TIME) == 0)
  2863. continue;
  2864. uint8_t timeInfoBuf[256];
  2865. lv2_atom_forge_set_buffer(&fAtomForge, timeInfoBuf, sizeof(timeInfoBuf));
  2866. LV2_Atom_Forge_Frame forgeFrame;
  2867. lv2_atom_forge_object(&fAtomForge, &forgeFrame, kUridNull, kUridTimePosition);
  2868. lv2_atom_forge_key(&fAtomForge, kUridTimeSpeed);
  2869. lv2_atom_forge_float(&fAtomForge, timeInfo.playing ? 1.0f : 0.0f);
  2870. lv2_atom_forge_key(&fAtomForge, kUridTimeFrame);
  2871. lv2_atom_forge_long(&fAtomForge, static_cast<int64_t>(timeInfo.frame));
  2872. if (timeInfo.bbt.valid)
  2873. {
  2874. lv2_atom_forge_key(&fAtomForge, kUridTimeBar);
  2875. lv2_atom_forge_long(&fAtomForge, timeInfo.bbt.bar - 1);
  2876. lv2_atom_forge_key(&fAtomForge, kUridTimeBarBeat);
  2877. lv2_atom_forge_float(&fAtomForge, static_cast<float>(barBeat));
  2878. lv2_atom_forge_key(&fAtomForge, kUridTimeBeat);
  2879. lv2_atom_forge_double(&fAtomForge, timeInfo.bbt.beat - 1);
  2880. lv2_atom_forge_key(&fAtomForge, kUridTimeBeatUnit);
  2881. lv2_atom_forge_int(&fAtomForge, static_cast<int32_t>(timeInfo.bbt.beatType));
  2882. lv2_atom_forge_key(&fAtomForge, kUridTimeBeatsPerBar);
  2883. lv2_atom_forge_float(&fAtomForge, timeInfo.bbt.beatsPerBar);
  2884. lv2_atom_forge_key(&fAtomForge, kUridTimeBeatsPerMinute);
  2885. lv2_atom_forge_float(&fAtomForge, static_cast<float>(timeInfo.bbt.beatsPerMinute));
  2886. lv2_atom_forge_key(&fAtomForge, kUridTimeTicksPerBeat);
  2887. lv2_atom_forge_double(&fAtomForge, timeInfo.bbt.ticksPerBeat);
  2888. }
  2889. lv2_atom_forge_pop(&fAtomForge, &forgeFrame);
  2890. LV2_Atom* const atom((LV2_Atom*)timeInfoBuf);
  2891. CARLA_SAFE_ASSERT_BREAK(atom->size < 256);
  2892. // send only deprecated blank object for now
  2893. lv2_atom_buffer_write(&evInAtomIters[i], 0, 0, kUridAtomBlank, atom->size, LV2_ATOM_BODY_CONST(atom));
  2894. // for atom:object
  2895. //lv2_atom_buffer_write(&evInAtomIters[i], 0, 0, atom->type, atom->size, LV2_ATOM_BODY_CONST(atom));
  2896. }
  2897. pData->postRtEvents.trySplice();
  2898. fLastTimeInfo = timeInfo;
  2899. }
  2900. // --------------------------------------------------------------------------------------------------------
  2901. // Event Input and Processing
  2902. if (fEventsIn.ctrl != nullptr)
  2903. {
  2904. // ----------------------------------------------------------------------------------------------------
  2905. // Message Input
  2906. if (fAtomBufferEvIn.tryLock())
  2907. {
  2908. if (fAtomBufferEvIn.isDataAvailableForReading())
  2909. {
  2910. const LV2_Atom* atom;
  2911. uint32_t j, portIndex;
  2912. for (; fAtomBufferEvIn.get(atom, portIndex);)
  2913. {
  2914. j = (portIndex < fEventsIn.count) ? portIndex : fEventsIn.ctrlIndex;
  2915. if (! lv2_atom_buffer_write(&evInAtomIters[j], 0, 0, atom->type, atom->size, LV2_ATOM_BODY_CONST(atom)))
  2916. {
  2917. carla_stderr2("Event input buffer full, at least 1 message lost");
  2918. continue;
  2919. }
  2920. }
  2921. }
  2922. fAtomBufferEvIn.unlock();
  2923. }
  2924. if (fExt.worker != nullptr && fAtomBufferWorkerIn.tryLock())
  2925. {
  2926. if (fAtomBufferWorkerIn.isDataAvailableForReading())
  2927. {
  2928. const LV2_Atom* atom;
  2929. uint32_t portIndex;
  2930. for (; fAtomBufferWorkerIn.get(atom, portIndex);)
  2931. {
  2932. CARLA_SAFE_ASSERT_CONTINUE(atom->type == kUridCarlaAtomWorkerIn);
  2933. fExt.worker->work(fHandle, carla_lv2_worker_respond, this, atom->size, LV2_ATOM_BODY_CONST(atom));
  2934. }
  2935. }
  2936. fAtomBufferWorkerIn.unlock();
  2937. }
  2938. // ----------------------------------------------------------------------------------------------------
  2939. // MIDI Input (External)
  2940. if (pData->extNotes.mutex.tryLock())
  2941. {
  2942. if ((fEventsIn.ctrl->type & CARLA_EVENT_TYPE_MIDI) == 0)
  2943. {
  2944. // does not handle MIDI
  2945. pData->extNotes.data.clear();
  2946. }
  2947. else
  2948. {
  2949. const uint32_t j = fEventsIn.ctrlIndex;
  2950. for (RtLinkedList<ExternalMidiNote>::Itenerator it = pData->extNotes.data.begin2(); it.valid(); it.next())
  2951. {
  2952. const ExternalMidiNote& note(it.getValue(kExternalMidiNoteFallback));
  2953. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  2954. uint8_t midiEvent[3];
  2955. midiEvent[0] = uint8_t((note.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT));
  2956. midiEvent[1] = note.note;
  2957. midiEvent[2] = note.velo;
  2958. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  2959. lv2_atom_buffer_write(&evInAtomIters[j], 0, 0, kUridMidiEvent, 3, midiEvent);
  2960. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  2961. lv2_event_write(&evInEventIters[j], 0, 0, kUridMidiEvent, 3, midiEvent);
  2962. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  2963. lv2midi_put_event(&evInMidiStates[j], 0.0, 3, midiEvent);
  2964. }
  2965. pData->extNotes.data.clear();
  2966. }
  2967. pData->extNotes.mutex.unlock();
  2968. } // End of MIDI Input (External)
  2969. // ----------------------------------------------------------------------------------------------------
  2970. // Event Input (System)
  2971. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2972. bool allNotesOffSent = false;
  2973. #endif
  2974. bool isSampleAccurate = (pData->options & PLUGIN_OPTION_FIXED_BUFFERS) == 0;
  2975. uint32_t startTime = 0;
  2976. uint32_t timeOffset = 0;
  2977. uint32_t nextBankId;
  2978. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0)
  2979. nextBankId = pData->midiprog.data[pData->midiprog.current].bank;
  2980. else
  2981. nextBankId = 0;
  2982. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2983. if (cvIn != nullptr && pData->event.cvSourcePorts != nullptr)
  2984. pData->event.cvSourcePorts->initPortBuffers(cvIn + pData->cvIn.count, frames, isSampleAccurate, pData->event.portIn);
  2985. #endif
  2986. const uint32_t numEvents = (fEventsIn.ctrl->port != nullptr) ? fEventsIn.ctrl->port->getEventCount() : 0;
  2987. for (uint32_t i=0; i < numEvents; ++i)
  2988. {
  2989. const EngineEvent& event(fEventsIn.ctrl->port->getEvent(i));
  2990. uint32_t eventTime = event.time;
  2991. CARLA_SAFE_ASSERT_UINT2_CONTINUE(eventTime < frames, eventTime, frames);
  2992. if (eventTime < timeOffset)
  2993. {
  2994. carla_stderr2("Timing error, eventTime:%u < timeOffset:%u for '%s'",
  2995. eventTime, timeOffset, pData->name);
  2996. eventTime = timeOffset;
  2997. }
  2998. if (isSampleAccurate && eventTime > timeOffset)
  2999. {
  3000. if (processSingle(audioIn, audioOut, cvIn, cvOut, eventTime - timeOffset, timeOffset))
  3001. {
  3002. startTime = 0;
  3003. timeOffset = eventTime;
  3004. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0)
  3005. nextBankId = pData->midiprog.data[pData->midiprog.current].bank;
  3006. else
  3007. nextBankId = 0;
  3008. for (uint32_t j=0; j < fEventsIn.count; ++j)
  3009. {
  3010. if (fEventsIn.data[j].type & CARLA_EVENT_DATA_ATOM)
  3011. {
  3012. lv2_atom_buffer_reset(fEventsIn.data[j].atom, true);
  3013. lv2_atom_buffer_begin(&evInAtomIters[j], fEventsIn.data[j].atom);
  3014. }
  3015. else if (fEventsIn.data[j].type & CARLA_EVENT_DATA_EVENT)
  3016. {
  3017. lv2_event_buffer_reset(fEventsIn.data[j].event, LV2_EVENT_AUDIO_STAMP, fEventsIn.data[j].event->data);
  3018. lv2_event_begin(&evInEventIters[j], fEventsIn.data[j].event);
  3019. }
  3020. else if (fEventsIn.data[j].type & CARLA_EVENT_DATA_MIDI_LL)
  3021. {
  3022. fEventsIn.data[j].midi.event_count = 0;
  3023. fEventsIn.data[j].midi.size = 0;
  3024. evInMidiStates[j].position = eventTime;
  3025. }
  3026. }
  3027. for (uint32_t j=0; j < fEventsOut.count; ++j)
  3028. {
  3029. if (fEventsOut.data[j].type & CARLA_EVENT_DATA_ATOM)
  3030. {
  3031. lv2_atom_buffer_reset(fEventsOut.data[j].atom, false);
  3032. }
  3033. else if (fEventsOut.data[j].type & CARLA_EVENT_DATA_EVENT)
  3034. {
  3035. lv2_event_buffer_reset(fEventsOut.data[j].event, LV2_EVENT_AUDIO_STAMP, fEventsOut.data[j].event->data);
  3036. }
  3037. else if (fEventsOut.data[j].type & CARLA_EVENT_DATA_MIDI_LL)
  3038. {
  3039. // not needed
  3040. }
  3041. }
  3042. }
  3043. else
  3044. {
  3045. startTime += timeOffset;
  3046. }
  3047. }
  3048. switch (event.type)
  3049. {
  3050. case kEngineEventTypeNull:
  3051. break;
  3052. case kEngineEventTypeControl: {
  3053. const EngineControlEvent& ctrlEvent(event.ctrl);
  3054. switch (ctrlEvent.type)
  3055. {
  3056. case kEngineControlEventTypeNull:
  3057. break;
  3058. case kEngineControlEventTypeParameter: {
  3059. float value;
  3060. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  3061. // non-midi
  3062. if (event.channel == kEngineEventNonMidiChannel)
  3063. {
  3064. const uint32_t k = ctrlEvent.param;
  3065. CARLA_SAFE_ASSERT_CONTINUE(k < pData->param.count);
  3066. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.value);
  3067. setParameterValueRT(k, value, true);
  3068. continue;
  3069. }
  3070. // Control backend stuff
  3071. if (event.channel == pData->ctrlChannel)
  3072. {
  3073. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  3074. {
  3075. value = ctrlEvent.value;
  3076. setDryWetRT(value, true);
  3077. }
  3078. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  3079. {
  3080. value = ctrlEvent.value*127.0f/100.0f;
  3081. setVolumeRT(value, true);
  3082. }
  3083. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  3084. {
  3085. float left, right;
  3086. value = ctrlEvent.value/0.5f - 1.0f;
  3087. if (value < 0.0f)
  3088. {
  3089. left = -1.0f;
  3090. right = (value*2.0f)+1.0f;
  3091. }
  3092. else if (value > 0.0f)
  3093. {
  3094. left = (value*2.0f)-1.0f;
  3095. right = 1.0f;
  3096. }
  3097. else
  3098. {
  3099. left = -1.0f;
  3100. right = 1.0f;
  3101. }
  3102. setBalanceLeftRT(left, true);
  3103. setBalanceRightRT(right, true);
  3104. }
  3105. }
  3106. #endif
  3107. // Control plugin parameters
  3108. uint32_t k;
  3109. for (k=0; k < pData->param.count; ++k)
  3110. {
  3111. if (pData->param.data[k].midiChannel != event.channel)
  3112. continue;
  3113. if (pData->param.data[k].mappedControlIndex != ctrlEvent.param)
  3114. continue;
  3115. if (pData->param.data[k].type != PARAMETER_INPUT)
  3116. continue;
  3117. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  3118. continue;
  3119. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.value);
  3120. setParameterValueRT(k, value, true);
  3121. }
  3122. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param < MAX_MIDI_VALUE)
  3123. {
  3124. uint8_t midiData[3];
  3125. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  3126. midiData[1] = uint8_t(ctrlEvent.param);
  3127. midiData[2] = uint8_t(ctrlEvent.value*127.0f);
  3128. const uint32_t mtime(isSampleAccurate ? startTime : eventTime);
  3129. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  3130. lv2_atom_buffer_write(&evInAtomIters[fEventsIn.ctrlIndex], mtime, 0, kUridMidiEvent, 3, midiData);
  3131. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  3132. lv2_event_write(&evInEventIters[fEventsIn.ctrlIndex], mtime, 0, kUridMidiEvent, 3, midiData);
  3133. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  3134. lv2midi_put_event(&evInMidiStates[fEventsIn.ctrlIndex], mtime, 3, midiData);
  3135. }
  3136. break;
  3137. } // case kEngineControlEventTypeParameter
  3138. case kEngineControlEventTypeMidiBank:
  3139. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  3140. {
  3141. if (event.channel == pData->ctrlChannel)
  3142. nextBankId = ctrlEvent.param;
  3143. }
  3144. else if (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES)
  3145. {
  3146. uint8_t midiData[3];
  3147. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  3148. midiData[1] = MIDI_CONTROL_BANK_SELECT;
  3149. midiData[2] = uint8_t(ctrlEvent.param);
  3150. const uint32_t mtime(isSampleAccurate ? startTime : eventTime);
  3151. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  3152. lv2_atom_buffer_write(&evInAtomIters[fEventsIn.ctrlIndex], mtime, 0, kUridMidiEvent, 3, midiData);
  3153. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  3154. lv2_event_write(&evInEventIters[fEventsIn.ctrlIndex], mtime, 0, kUridMidiEvent, 3, midiData);
  3155. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  3156. lv2midi_put_event(&evInMidiStates[fEventsIn.ctrlIndex], mtime, 3, midiData);
  3157. }
  3158. break;
  3159. case kEngineControlEventTypeMidiProgram:
  3160. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  3161. {
  3162. if (event.channel == pData->ctrlChannel)
  3163. {
  3164. const uint32_t nextProgramId(ctrlEvent.param);
  3165. for (uint32_t k=0; k < pData->midiprog.count; ++k)
  3166. {
  3167. if (pData->midiprog.data[k].bank == nextBankId && pData->midiprog.data[k].program == nextProgramId)
  3168. {
  3169. setMidiProgramRT(k, true);
  3170. break;
  3171. }
  3172. }
  3173. }
  3174. }
  3175. else if (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES)
  3176. {
  3177. uint8_t midiData[2];
  3178. midiData[0] = uint8_t(MIDI_STATUS_PROGRAM_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  3179. midiData[1] = uint8_t(ctrlEvent.param);
  3180. const uint32_t mtime(isSampleAccurate ? startTime : eventTime);
  3181. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  3182. lv2_atom_buffer_write(&evInAtomIters[fEventsIn.ctrlIndex], mtime, 0, kUridMidiEvent, 2, midiData);
  3183. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  3184. lv2_event_write(&evInEventIters[fEventsIn.ctrlIndex], mtime, 0, kUridMidiEvent, 2, midiData);
  3185. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  3186. lv2midi_put_event(&evInMidiStates[fEventsIn.ctrlIndex], mtime, 2, midiData);
  3187. }
  3188. break;
  3189. case kEngineControlEventTypeAllSoundOff:
  3190. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  3191. {
  3192. const uint32_t mtime(isSampleAccurate ? startTime : eventTime);
  3193. uint8_t midiData[3];
  3194. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  3195. midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  3196. midiData[2] = 0;
  3197. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  3198. lv2_atom_buffer_write(&evInAtomIters[fEventsIn.ctrlIndex], mtime, 0, kUridMidiEvent, 3, midiData);
  3199. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  3200. lv2_event_write(&evInEventIters[fEventsIn.ctrlIndex], mtime, 0, kUridMidiEvent, 3, midiData);
  3201. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  3202. lv2midi_put_event(&evInMidiStates[fEventsIn.ctrlIndex], mtime, 3, midiData);
  3203. }
  3204. break;
  3205. case kEngineControlEventTypeAllNotesOff:
  3206. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  3207. {
  3208. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  3209. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  3210. {
  3211. allNotesOffSent = true;
  3212. postponeRtAllNotesOff();
  3213. }
  3214. #endif
  3215. const uint32_t mtime(isSampleAccurate ? startTime : eventTime);
  3216. uint8_t midiData[3];
  3217. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  3218. midiData[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  3219. midiData[2] = 0;
  3220. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  3221. lv2_atom_buffer_write(&evInAtomIters[fEventsIn.ctrlIndex], mtime, 0, kUridMidiEvent, 3, midiData);
  3222. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  3223. lv2_event_write(&evInEventIters[fEventsIn.ctrlIndex], mtime, 0, kUridMidiEvent, 3, midiData);
  3224. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  3225. lv2midi_put_event(&evInMidiStates[fEventsIn.ctrlIndex], mtime, 3, midiData);
  3226. }
  3227. break;
  3228. } // switch (ctrlEvent.type)
  3229. break;
  3230. } // case kEngineEventTypeControl
  3231. case kEngineEventTypeMidi: {
  3232. const EngineMidiEvent& midiEvent(event.midi);
  3233. const uint8_t* const midiData(midiEvent.size > EngineMidiEvent::kDataSize ? midiEvent.dataExt : midiEvent.data);
  3234. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiData));
  3235. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  3236. continue;
  3237. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  3238. continue;
  3239. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  3240. continue;
  3241. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  3242. continue;
  3243. // Fix bad note-off (per LV2 spec)
  3244. if (status == MIDI_STATUS_NOTE_ON && midiData[2] == 0)
  3245. status = MIDI_STATUS_NOTE_OFF;
  3246. const uint32_t j = fEventsIn.ctrlIndex;
  3247. const uint32_t mtime = isSampleAccurate ? startTime : eventTime;
  3248. // put back channel in data
  3249. uint8_t midiData2[midiEvent.size];
  3250. midiData2[0] = uint8_t(status | (event.channel & MIDI_CHANNEL_BIT));
  3251. std::memcpy(midiData2+1, midiData+1, static_cast<std::size_t>(midiEvent.size-1));
  3252. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  3253. lv2_atom_buffer_write(&evInAtomIters[j], mtime, 0, kUridMidiEvent, midiEvent.size, midiData2);
  3254. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  3255. lv2_event_write(&evInEventIters[j], mtime, 0, kUridMidiEvent, midiEvent.size, midiData2);
  3256. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  3257. lv2midi_put_event(&evInMidiStates[j], mtime, midiEvent.size, midiData2);
  3258. if (status == MIDI_STATUS_NOTE_ON)
  3259. {
  3260. pData->postponeRtEvent(kPluginPostRtEventNoteOn,
  3261. true,
  3262. event.channel,
  3263. midiData[1],
  3264. midiData[2],
  3265. 0.0f);
  3266. }
  3267. else if (status == MIDI_STATUS_NOTE_OFF)
  3268. {
  3269. pData->postponeRtEvent(kPluginPostRtEventNoteOff,
  3270. true,
  3271. event.channel,
  3272. midiData[1],
  3273. 0, 0.0f);
  3274. }
  3275. } break;
  3276. } // switch (event.type)
  3277. }
  3278. pData->postRtEvents.trySplice();
  3279. if (frames > timeOffset)
  3280. processSingle(audioIn, audioOut, cvIn, cvOut, frames - timeOffset, timeOffset);
  3281. } // End of Event Input and Processing
  3282. // --------------------------------------------------------------------------------------------------------
  3283. // Plugin processing (no events)
  3284. else
  3285. {
  3286. processSingle(audioIn, audioOut, cvIn, cvOut, frames, 0);
  3287. } // End of Plugin processing (no events)
  3288. // --------------------------------------------------------------------------------------------------------
  3289. // Events/MIDI Output
  3290. for (uint32_t i=0; i < fEventsOut.count; ++i)
  3291. {
  3292. uint32_t lastFrame = 0;
  3293. Lv2EventData& evData(fEventsOut.data[i]);
  3294. if (evData.type & CARLA_EVENT_DATA_ATOM)
  3295. {
  3296. const LV2_Atom_Event* ev;
  3297. LV2_Atom_Buffer_Iterator iter;
  3298. uint8_t* data;
  3299. lv2_atom_buffer_begin(&iter, evData.atom);
  3300. for (;;)
  3301. {
  3302. data = nullptr;
  3303. ev = lv2_atom_buffer_get(&iter, &data);
  3304. if (ev == nullptr || ev->body.size == 0 || data == nullptr)
  3305. break;
  3306. if (ev->body.type == kUridMidiEvent)
  3307. {
  3308. if (evData.port != nullptr)
  3309. {
  3310. CARLA_SAFE_ASSERT_CONTINUE(ev->time.frames >= 0);
  3311. CARLA_SAFE_ASSERT_CONTINUE(ev->body.size < 0xFF);
  3312. uint32_t currentFrame = static_cast<uint32_t>(ev->time.frames);
  3313. if (currentFrame < lastFrame)
  3314. currentFrame = lastFrame;
  3315. else if (currentFrame >= frames)
  3316. currentFrame = frames - 1;
  3317. evData.port->writeMidiEvent(currentFrame, static_cast<uint8_t>(ev->body.size), data);
  3318. }
  3319. }
  3320. else if (fAtomBufferUiOutTmpData != nullptr)
  3321. {
  3322. fAtomBufferUiOut.put(&ev->body, evData.rindex);
  3323. }
  3324. lv2_atom_buffer_increment(&iter);
  3325. }
  3326. }
  3327. else if ((evData.type & CARLA_EVENT_DATA_EVENT) != 0 && evData.port != nullptr)
  3328. {
  3329. const LV2_Event* ev;
  3330. LV2_Event_Iterator iter;
  3331. uint8_t* data;
  3332. lv2_event_begin(&iter, evData.event);
  3333. for (;;)
  3334. {
  3335. data = nullptr;
  3336. ev = lv2_event_get(&iter, &data);
  3337. if (ev == nullptr || data == nullptr)
  3338. break;
  3339. uint32_t currentFrame = ev->frames;
  3340. if (currentFrame < lastFrame)
  3341. currentFrame = lastFrame;
  3342. else if (currentFrame >= frames)
  3343. currentFrame = frames - 1;
  3344. if (ev->type == kUridMidiEvent)
  3345. {
  3346. CARLA_SAFE_ASSERT_CONTINUE(ev->size < 0xFF);
  3347. evData.port->writeMidiEvent(currentFrame, static_cast<uint8_t>(ev->size), data);
  3348. }
  3349. lv2_event_increment(&iter);
  3350. }
  3351. }
  3352. else if ((evData.type & CARLA_EVENT_DATA_MIDI_LL) != 0 && evData.port != nullptr)
  3353. {
  3354. LV2_MIDIState state = { &evData.midi, frames, 0 };
  3355. uint32_t eventSize;
  3356. double eventTime;
  3357. uchar* eventData;
  3358. for (;;)
  3359. {
  3360. eventSize = 0;
  3361. eventTime = 0.0;
  3362. eventData = nullptr;
  3363. lv2midi_get_event(&state, &eventTime, &eventSize, &eventData);
  3364. if (eventData == nullptr || eventSize == 0)
  3365. break;
  3366. CARLA_SAFE_ASSERT_CONTINUE(eventSize < 0xFF);
  3367. CARLA_SAFE_ASSERT_CONTINUE(eventTime >= 0.0);
  3368. evData.port->writeMidiEvent(static_cast<uint32_t>(eventTime), static_cast<uint8_t>(eventSize), eventData);
  3369. lv2midi_step(&state);
  3370. }
  3371. }
  3372. }
  3373. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  3374. // --------------------------------------------------------------------------------------------------------
  3375. // Control Output
  3376. if (pData->event.portOut != nullptr)
  3377. {
  3378. uint8_t channel;
  3379. uint16_t param;
  3380. float value;
  3381. for (uint32_t k=0; k < pData->param.count; ++k)
  3382. {
  3383. if (pData->param.data[k].type != PARAMETER_OUTPUT)
  3384. continue;
  3385. if (fStrictBounds >= 0 && (pData->param.data[k].hints & PARAMETER_IS_STRICT_BOUNDS) != 0)
  3386. // plugin is responsible to ensure correct bounds
  3387. pData->param.ranges[k].fixValue(fParamBuffers[k]);
  3388. if (pData->param.data[k].mappedControlIndex > 0)
  3389. {
  3390. channel = pData->param.data[k].midiChannel;
  3391. param = static_cast<uint16_t>(pData->param.data[k].mappedControlIndex);
  3392. value = pData->param.ranges[k].getNormalizedValue(fParamBuffers[k]);
  3393. pData->event.portOut->writeControlEvent(0, channel, kEngineControlEventTypeParameter, param, value);
  3394. }
  3395. }
  3396. } // End of Control Output
  3397. #endif
  3398. // --------------------------------------------------------------------------------------------------------
  3399. // Final work
  3400. if (fEventsIn.ctrl != nullptr && fExt.worker != nullptr && fAtomBufferWorkerResp.tryLock())
  3401. {
  3402. if (fAtomBufferWorkerResp.isDataAvailableForReading())
  3403. {
  3404. const LV2_Atom* atom;
  3405. uint32_t portIndex;
  3406. for (; fAtomBufferWorkerResp.get(atom, portIndex);)
  3407. {
  3408. CARLA_SAFE_ASSERT_CONTINUE(atom->type == kUridCarlaAtomWorkerResp);
  3409. fExt.worker->work_response(fHandle, atom->size, LV2_ATOM_BODY_CONST(atom));
  3410. }
  3411. }
  3412. fAtomBufferWorkerResp.unlock();
  3413. }
  3414. if (fExt.worker != nullptr && fExt.worker->end_run != nullptr)
  3415. {
  3416. fExt.worker->end_run(fHandle);
  3417. if (fHandle2 != nullptr)
  3418. fExt.worker->end_run(fHandle2);
  3419. }
  3420. fFirstActive = false;
  3421. // --------------------------------------------------------------------------------------------------------
  3422. }
  3423. bool processSingle(const float* const* const audioIn, float** const audioOut,
  3424. const float* const* const cvIn, float** const cvOut,
  3425. const uint32_t frames, const uint32_t timeOffset)
  3426. {
  3427. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  3428. if (pData->audioIn.count > 0)
  3429. {
  3430. CARLA_SAFE_ASSERT_RETURN(audioIn != nullptr, false);
  3431. CARLA_SAFE_ASSERT_RETURN(fAudioInBuffers != nullptr, false);
  3432. }
  3433. if (pData->audioOut.count > 0)
  3434. {
  3435. CARLA_SAFE_ASSERT_RETURN(audioOut != nullptr, false);
  3436. CARLA_SAFE_ASSERT_RETURN(fAudioOutBuffers != nullptr, false);
  3437. }
  3438. if (pData->cvIn.count > 0)
  3439. {
  3440. CARLA_SAFE_ASSERT_RETURN(cvIn != nullptr, false);
  3441. }
  3442. if (pData->cvOut.count > 0)
  3443. {
  3444. CARLA_SAFE_ASSERT_RETURN(cvOut != nullptr, false);
  3445. }
  3446. // --------------------------------------------------------------------------------------------------------
  3447. // Try lock, silence otherwise
  3448. #ifndef STOAT_TEST_BUILD
  3449. if (pData->engine->isOffline())
  3450. {
  3451. pData->singleMutex.lock();
  3452. }
  3453. else
  3454. #endif
  3455. if (! pData->singleMutex.tryLock())
  3456. {
  3457. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  3458. {
  3459. for (uint32_t k=0; k < frames; ++k)
  3460. audioOut[i][k+timeOffset] = 0.0f;
  3461. }
  3462. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  3463. {
  3464. for (uint32_t k=0; k < frames; ++k)
  3465. cvOut[i][k+timeOffset] = 0.0f;
  3466. }
  3467. return false;
  3468. }
  3469. // --------------------------------------------------------------------------------------------------------
  3470. // Set audio buffers
  3471. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  3472. carla_copyFloats(fAudioInBuffers[i], audioIn[i]+timeOffset, frames);
  3473. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  3474. carla_zeroFloats(fAudioOutBuffers[i], frames);
  3475. // --------------------------------------------------------------------------------------------------------
  3476. // Set CV buffers
  3477. for (uint32_t i=0; i < pData->cvIn.count; ++i)
  3478. carla_copyFloats(fCvInBuffers[i], cvIn[i]+timeOffset, frames);
  3479. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  3480. carla_zeroFloats(fCvOutBuffers[i], frames);
  3481. // --------------------------------------------------------------------------------------------------------
  3482. // Run plugin
  3483. fDescriptor->run(fHandle, frames);
  3484. if (fHandle2 != nullptr)
  3485. fDescriptor->run(fHandle2, frames);
  3486. // --------------------------------------------------------------------------------------------------------
  3487. // Handle trigger parameters
  3488. for (uint32_t k=0; k < pData->param.count; ++k)
  3489. {
  3490. if (pData->param.data[k].type != PARAMETER_INPUT)
  3491. continue;
  3492. if (pData->param.data[k].hints & PARAMETER_IS_TRIGGER)
  3493. {
  3494. if (carla_isNotEqual(fParamBuffers[k], pData->param.ranges[k].def))
  3495. {
  3496. fParamBuffers[k] = pData->param.ranges[k].def;
  3497. pData->postponeRtEvent(kPluginPostRtEventParameterChange,
  3498. true,
  3499. static_cast<int32_t>(k),
  3500. 1, 0,
  3501. fParamBuffers[k]);
  3502. }
  3503. }
  3504. }
  3505. pData->postRtEvents.trySplice();
  3506. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  3507. // --------------------------------------------------------------------------------------------------------
  3508. // Post-processing (dry/wet, volume and balance)
  3509. {
  3510. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  3511. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  3512. const bool isMono = (pData->audioIn.count == 1);
  3513. bool isPair;
  3514. float bufValue, oldBufLeft[doBalance ? frames : 1];
  3515. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  3516. {
  3517. // Dry/Wet
  3518. if (doDryWet)
  3519. {
  3520. const uint32_t c = isMono ? 0 : i;
  3521. for (uint32_t k=0; k < frames; ++k)
  3522. {
  3523. # ifndef BUILD_BRIDGE
  3524. if (k < pData->latency.frames && pData->latency.buffers != nullptr)
  3525. bufValue = pData->latency.buffers[c][k];
  3526. else if (pData->latency.frames < frames)
  3527. bufValue = fAudioInBuffers[c][k-pData->latency.frames];
  3528. else
  3529. # endif
  3530. bufValue = fAudioInBuffers[c][k];
  3531. fAudioOutBuffers[i][k] = (fAudioOutBuffers[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  3532. }
  3533. }
  3534. // Balance
  3535. if (doBalance)
  3536. {
  3537. isPair = (i % 2 == 0);
  3538. if (isPair)
  3539. {
  3540. CARLA_ASSERT(i+1 < pData->audioOut.count);
  3541. carla_copyFloats(oldBufLeft, fAudioOutBuffers[i], frames);
  3542. }
  3543. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  3544. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  3545. for (uint32_t k=0; k < frames; ++k)
  3546. {
  3547. if (isPair)
  3548. {
  3549. // left
  3550. fAudioOutBuffers[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  3551. fAudioOutBuffers[i][k] += fAudioOutBuffers[i+1][k] * (1.0f - balRangeR);
  3552. }
  3553. else
  3554. {
  3555. // right
  3556. fAudioOutBuffers[i][k] = fAudioOutBuffers[i][k] * balRangeR;
  3557. fAudioOutBuffers[i][k] += oldBufLeft[k] * balRangeL;
  3558. }
  3559. }
  3560. }
  3561. // Volume (and buffer copy)
  3562. {
  3563. for (uint32_t k=0; k < frames; ++k)
  3564. audioOut[i][k+timeOffset] = fAudioOutBuffers[i][k] * pData->postProc.volume;
  3565. }
  3566. }
  3567. } // End of Post-processing
  3568. # ifndef BUILD_BRIDGE
  3569. // --------------------------------------------------------------------------------------------------------
  3570. // Save latency values for next callback
  3571. if (pData->latency.frames != 0 && pData->latency.buffers != nullptr)
  3572. {
  3573. CARLA_SAFE_ASSERT(timeOffset == 0);
  3574. const uint32_t latframes = pData->latency.frames;
  3575. if (latframes <= frames)
  3576. {
  3577. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  3578. carla_copyFloats(pData->latency.buffers[i], audioIn[i]+(frames-latframes), latframes);
  3579. }
  3580. else
  3581. {
  3582. const uint32_t diff = latframes - frames;
  3583. for (uint32_t i=0, k; i<pData->audioIn.count; ++i)
  3584. {
  3585. // push back buffer by 'frames'
  3586. for (k=0; k < diff; ++k)
  3587. pData->latency.buffers[i][k] = pData->latency.buffers[i][k+frames];
  3588. // put current input at the end
  3589. for (uint32_t j=0; k < latframes; ++j, ++k)
  3590. pData->latency.buffers[i][k] = audioIn[i][j];
  3591. }
  3592. }
  3593. }
  3594. # endif
  3595. #else // BUILD_BRIDGE_ALTERNATIVE_ARCH
  3596. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  3597. {
  3598. for (uint32_t k=0; k < frames; ++k)
  3599. audioOut[i][k+timeOffset] = fAudioOutBuffers[i][k];
  3600. }
  3601. #endif
  3602. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  3603. {
  3604. for (uint32_t k=0; k < frames; ++k)
  3605. cvOut[i][k+timeOffset] = fCvOutBuffers[i][k];
  3606. }
  3607. // --------------------------------------------------------------------------------------------------------
  3608. pData->singleMutex.unlock();
  3609. return true;
  3610. }
  3611. void bufferSizeChanged(const uint32_t newBufferSize) override
  3612. {
  3613. CARLA_ASSERT_INT(newBufferSize > 0, newBufferSize);
  3614. carla_debug("CarlaPluginLV2::bufferSizeChanged(%i) - start", newBufferSize);
  3615. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  3616. {
  3617. if (fAudioInBuffers[i] != nullptr)
  3618. delete[] fAudioInBuffers[i];
  3619. fAudioInBuffers[i] = new float[newBufferSize];
  3620. }
  3621. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  3622. {
  3623. if (fAudioOutBuffers[i] != nullptr)
  3624. delete[] fAudioOutBuffers[i];
  3625. fAudioOutBuffers[i] = new float[newBufferSize];
  3626. }
  3627. if (fHandle2 == nullptr)
  3628. {
  3629. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  3630. {
  3631. CARLA_ASSERT(fAudioInBuffers[i] != nullptr);
  3632. fDescriptor->connect_port(fHandle, pData->audioIn.ports[i].rindex, fAudioInBuffers[i]);
  3633. }
  3634. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  3635. {
  3636. CARLA_ASSERT(fAudioOutBuffers[i] != nullptr);
  3637. fDescriptor->connect_port(fHandle, pData->audioOut.ports[i].rindex, fAudioOutBuffers[i]);
  3638. }
  3639. }
  3640. else
  3641. {
  3642. if (pData->audioIn.count > 0)
  3643. {
  3644. CARLA_ASSERT(pData->audioIn.count == 2);
  3645. CARLA_ASSERT(fAudioInBuffers[0] != nullptr);
  3646. CARLA_ASSERT(fAudioInBuffers[1] != nullptr);
  3647. fDescriptor->connect_port(fHandle, pData->audioIn.ports[0].rindex, fAudioInBuffers[0]);
  3648. fDescriptor->connect_port(fHandle2, pData->audioIn.ports[1].rindex, fAudioInBuffers[1]);
  3649. }
  3650. if (pData->audioOut.count > 0)
  3651. {
  3652. CARLA_ASSERT(pData->audioOut.count == 2);
  3653. CARLA_ASSERT(fAudioOutBuffers[0] != nullptr);
  3654. CARLA_ASSERT(fAudioOutBuffers[1] != nullptr);
  3655. fDescriptor->connect_port(fHandle, pData->audioOut.ports[0].rindex, fAudioOutBuffers[0]);
  3656. fDescriptor->connect_port(fHandle2, pData->audioOut.ports[1].rindex, fAudioOutBuffers[1]);
  3657. }
  3658. }
  3659. for (uint32_t i=0; i < pData->cvIn.count; ++i)
  3660. {
  3661. if (fCvInBuffers[i] != nullptr)
  3662. delete[] fCvInBuffers[i];
  3663. fCvInBuffers[i] = new float[newBufferSize];
  3664. fDescriptor->connect_port(fHandle, pData->cvIn.ports[i].rindex, fCvInBuffers[i]);
  3665. if (fHandle2 != nullptr)
  3666. fDescriptor->connect_port(fHandle2, pData->cvIn.ports[i].rindex, fCvInBuffers[i]);
  3667. }
  3668. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  3669. {
  3670. if (fCvOutBuffers[i] != nullptr)
  3671. delete[] fCvOutBuffers[i];
  3672. fCvOutBuffers[i] = new float[newBufferSize];
  3673. fDescriptor->connect_port(fHandle, pData->cvOut.ports[i].rindex, fCvOutBuffers[i]);
  3674. if (fHandle2 != nullptr)
  3675. fDescriptor->connect_port(fHandle2, pData->cvOut.ports[i].rindex, fCvOutBuffers[i]);
  3676. }
  3677. const int newBufferSizeInt(static_cast<int>(newBufferSize));
  3678. if (fLv2Options.maxBufferSize != newBufferSizeInt || (fLv2Options.minBufferSize != 1 && fLv2Options.minBufferSize != newBufferSizeInt))
  3679. {
  3680. fLv2Options.maxBufferSize = fLv2Options.nominalBufferSize = newBufferSizeInt;
  3681. if (fLv2Options.minBufferSize != 1)
  3682. fLv2Options.minBufferSize = newBufferSizeInt;
  3683. if (fExt.options != nullptr && fExt.options->set != nullptr)
  3684. {
  3685. fExt.options->set(fHandle, &fLv2Options.opts[CarlaPluginLV2Options::MaxBlockLenth]);
  3686. fExt.options->set(fHandle, &fLv2Options.opts[CarlaPluginLV2Options::NominalBlockLenth]);
  3687. if (fLv2Options.minBufferSize != 1)
  3688. fExt.options->set(fHandle, &fLv2Options.opts[CarlaPluginLV2Options::MinBlockLenth]);
  3689. }
  3690. }
  3691. carla_debug("CarlaPluginLV2::bufferSizeChanged(%i) - end", newBufferSize);
  3692. }
  3693. void sampleRateChanged(const double newSampleRate) override
  3694. {
  3695. CARLA_ASSERT_INT(newSampleRate > 0.0, newSampleRate);
  3696. carla_debug("CarlaPluginLV2::sampleRateChanged(%g) - start", newSampleRate);
  3697. const float sampleRatef = static_cast<float>(newSampleRate);
  3698. if (carla_isNotEqual(fLv2Options.sampleRate, sampleRatef))
  3699. {
  3700. fLv2Options.sampleRate = sampleRatef;
  3701. if (fExt.options != nullptr && fExt.options->set != nullptr)
  3702. {
  3703. LV2_Options_Option options[2];
  3704. carla_zeroStructs(options, 2);
  3705. LV2_Options_Option& optSampleRate(options[0]);
  3706. optSampleRate.context = LV2_OPTIONS_INSTANCE;
  3707. optSampleRate.subject = 0;
  3708. optSampleRate.key = kUridParamSampleRate;
  3709. optSampleRate.size = sizeof(float);
  3710. optSampleRate.type = kUridAtomFloat;
  3711. optSampleRate.value = &fLv2Options.sampleRate;
  3712. fExt.options->set(fHandle, options);
  3713. }
  3714. }
  3715. for (uint32_t k=0; k < pData->param.count; ++k)
  3716. {
  3717. if (pData->param.data[k].type != PARAMETER_INPUT)
  3718. continue;
  3719. if (pData->param.special[k] != PARAMETER_SPECIAL_SAMPLE_RATE)
  3720. continue;
  3721. fParamBuffers[k] = sampleRatef;
  3722. pData->postponeRtEvent(kPluginPostRtEventParameterChange,
  3723. true,
  3724. static_cast<int32_t>(k),
  3725. 0,
  3726. 0,
  3727. fParamBuffers[k]);
  3728. break;
  3729. }
  3730. carla_debug("CarlaPluginLV2::sampleRateChanged(%g) - end", newSampleRate);
  3731. }
  3732. void offlineModeChanged(const bool isOffline) override
  3733. {
  3734. for (uint32_t k=0; k < pData->param.count; ++k)
  3735. {
  3736. if (pData->param.data[k].type == PARAMETER_INPUT && pData->param.special[k] == PARAMETER_SPECIAL_FREEWHEEL)
  3737. {
  3738. fParamBuffers[k] = isOffline ? pData->param.ranges[k].max : pData->param.ranges[k].min;
  3739. pData->postponeRtEvent(kPluginPostRtEventParameterChange,
  3740. true,
  3741. static_cast<int32_t>(k),
  3742. 0,
  3743. 0,
  3744. fParamBuffers[k]);
  3745. break;
  3746. }
  3747. }
  3748. }
  3749. // -------------------------------------------------------------------
  3750. // Plugin buffers
  3751. void initBuffers() const noexcept override
  3752. {
  3753. fEventsIn.initBuffers();
  3754. fEventsOut.initBuffers();
  3755. CarlaPlugin::initBuffers();
  3756. }
  3757. void clearBuffers() noexcept override
  3758. {
  3759. carla_debug("CarlaPluginLV2::clearBuffers() - start");
  3760. if (fAudioInBuffers != nullptr)
  3761. {
  3762. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  3763. {
  3764. if (fAudioInBuffers[i] != nullptr)
  3765. {
  3766. delete[] fAudioInBuffers[i];
  3767. fAudioInBuffers[i] = nullptr;
  3768. }
  3769. }
  3770. delete[] fAudioInBuffers;
  3771. fAudioInBuffers = nullptr;
  3772. }
  3773. if (fAudioOutBuffers != nullptr)
  3774. {
  3775. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  3776. {
  3777. if (fAudioOutBuffers[i] != nullptr)
  3778. {
  3779. delete[] fAudioOutBuffers[i];
  3780. fAudioOutBuffers[i] = nullptr;
  3781. }
  3782. }
  3783. delete[] fAudioOutBuffers;
  3784. fAudioOutBuffers = nullptr;
  3785. }
  3786. if (fCvInBuffers != nullptr)
  3787. {
  3788. for (uint32_t i=0; i < pData->cvIn.count; ++i)
  3789. {
  3790. if (fCvInBuffers[i] != nullptr)
  3791. {
  3792. delete[] fCvInBuffers[i];
  3793. fCvInBuffers[i] = nullptr;
  3794. }
  3795. }
  3796. delete[] fCvInBuffers;
  3797. fCvInBuffers = nullptr;
  3798. }
  3799. if (fCvOutBuffers != nullptr)
  3800. {
  3801. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  3802. {
  3803. if (fCvOutBuffers[i] != nullptr)
  3804. {
  3805. delete[] fCvOutBuffers[i];
  3806. fCvOutBuffers[i] = nullptr;
  3807. }
  3808. }
  3809. delete[] fCvOutBuffers;
  3810. fCvOutBuffers = nullptr;
  3811. }
  3812. if (fParamBuffers != nullptr)
  3813. {
  3814. delete[] fParamBuffers;
  3815. fParamBuffers = nullptr;
  3816. }
  3817. fEventsIn.clear();
  3818. fEventsOut.clear();
  3819. CarlaPlugin::clearBuffers();
  3820. carla_debug("CarlaPluginLV2::clearBuffers() - end");
  3821. }
  3822. // -------------------------------------------------------------------
  3823. // Post-poned UI Stuff
  3824. void uiParameterChange(const uint32_t index, const float value) noexcept override
  3825. {
  3826. CARLA_SAFE_ASSERT_RETURN(fUI.type != UI::TYPE_NULL || fFilePathURI.isNotEmpty(),);
  3827. CARLA_SAFE_ASSERT_RETURN(index < pData->param.count,);
  3828. if (fUI.type == UI::TYPE_BRIDGE)
  3829. {
  3830. if (fPipeServer.isPipeRunning())
  3831. fPipeServer.writeControlMessage(static_cast<uint32_t>(pData->param.data[index].rindex), value);
  3832. }
  3833. else
  3834. {
  3835. if (fUI.handle != nullptr && fUI.descriptor != nullptr && fUI.descriptor->port_event != nullptr && ! fNeedsUiClose)
  3836. {
  3837. CARLA_SAFE_ASSERT_RETURN(pData->param.data[index].rindex >= 0,);
  3838. fUI.descriptor->port_event(fUI.handle, static_cast<uint32_t>(pData->param.data[index].rindex), sizeof(float), kUridNull, &value);
  3839. }
  3840. }
  3841. }
  3842. void uiMidiProgramChange(const uint32_t index) noexcept override
  3843. {
  3844. CARLA_SAFE_ASSERT_RETURN(fUI.type != UI::TYPE_NULL || fFilePathURI.isNotEmpty(),);
  3845. CARLA_SAFE_ASSERT_RETURN(index < pData->midiprog.count,);
  3846. if (fUI.type == UI::TYPE_BRIDGE)
  3847. {
  3848. if (fPipeServer.isPipeRunning())
  3849. fPipeServer.writeMidiProgramMessage(pData->midiprog.data[index].bank, pData->midiprog.data[index].program);
  3850. }
  3851. else
  3852. {
  3853. if (fExt.uiprograms != nullptr && fExt.uiprograms->select_program != nullptr && ! fNeedsUiClose)
  3854. fExt.uiprograms->select_program(fUI.handle, pData->midiprog.data[index].bank, pData->midiprog.data[index].program);
  3855. }
  3856. }
  3857. void uiNoteOn(const uint8_t channel, const uint8_t note, const uint8_t velo) noexcept override
  3858. {
  3859. CARLA_SAFE_ASSERT_RETURN(fUI.type != UI::TYPE_NULL || fFilePathURI.isNotEmpty(),);
  3860. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  3861. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  3862. CARLA_SAFE_ASSERT_RETURN(velo > 0 && velo < MAX_MIDI_VALUE,);
  3863. #if 0
  3864. if (fUI.type == UI::TYPE_BRIDGE)
  3865. {
  3866. if (fPipeServer.isPipeRunning())
  3867. fPipeServer.writeMidiNoteMessage(false, channel, note, velo);
  3868. }
  3869. else
  3870. {
  3871. if (fUI.handle != nullptr && fUI.descriptor != nullptr && fUI.descriptor->port_event != nullptr && fEventsIn.ctrl != nullptr && ! fNeedsUiClose)
  3872. {
  3873. LV2_Atom_MidiEvent midiEv;
  3874. midiEv.atom.type = kUridMidiEvent;
  3875. midiEv.atom.size = 3;
  3876. midiEv.data[0] = uint8_t(MIDI_STATUS_NOTE_ON | (channel & MIDI_CHANNEL_BIT));
  3877. midiEv.data[1] = note;
  3878. midiEv.data[2] = velo;
  3879. fUI.descriptor->port_event(fUI.handle, fEventsIn.ctrl->rindex, lv2_atom_total_size(midiEv), kUridAtomTransferEvent, &midiEv);
  3880. }
  3881. }
  3882. #endif
  3883. }
  3884. void uiNoteOff(const uint8_t channel, const uint8_t note) noexcept override
  3885. {
  3886. CARLA_SAFE_ASSERT_RETURN(fUI.type != UI::TYPE_NULL || fFilePathURI.isNotEmpty(),);
  3887. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  3888. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  3889. #if 0
  3890. if (fUI.type == UI::TYPE_BRIDGE)
  3891. {
  3892. if (fPipeServer.isPipeRunning())
  3893. fPipeServer.writeMidiNoteMessage(false, channel, note, 0);
  3894. }
  3895. else
  3896. {
  3897. if (fUI.handle != nullptr && fUI.descriptor != nullptr && fUI.descriptor->port_event != nullptr && fEventsIn.ctrl != nullptr && ! fNeedsUiClose)
  3898. {
  3899. LV2_Atom_MidiEvent midiEv;
  3900. midiEv.atom.type = kUridMidiEvent;
  3901. midiEv.atom.size = 3;
  3902. midiEv.data[0] = uint8_t(MIDI_STATUS_NOTE_OFF | (channel & MIDI_CHANNEL_BIT));
  3903. midiEv.data[1] = note;
  3904. midiEv.data[2] = 0;
  3905. fUI.descriptor->port_event(fUI.handle, fEventsIn.ctrl->rindex, lv2_atom_total_size(midiEv), kUridAtomTransferEvent, &midiEv);
  3906. }
  3907. }
  3908. #endif
  3909. }
  3910. // -------------------------------------------------------------------
  3911. // Internal helper functions
  3912. void restoreLV2State() noexcept override
  3913. {
  3914. if (fExt.state == nullptr)
  3915. return;
  3916. LV2_State_Status status = LV2_STATE_ERR_UNKNOWN;
  3917. {
  3918. const ScopedSingleProcessLocker spl(this, true);
  3919. try {
  3920. status = fExt.state->restore(fHandle, carla_lv2_state_retrieve, this, 0, fFeatures);
  3921. } catch(...) {}
  3922. if (fHandle2 != nullptr)
  3923. {
  3924. try {
  3925. fExt.state->restore(fHandle, carla_lv2_state_retrieve, this, 0, fFeatures);
  3926. } catch(...) {}
  3927. }
  3928. }
  3929. switch (status)
  3930. {
  3931. case LV2_STATE_SUCCESS:
  3932. carla_debug("CarlaPluginLV2::updateLV2State() - success");
  3933. break;
  3934. case LV2_STATE_ERR_UNKNOWN:
  3935. carla_stderr("CarlaPluginLV2::updateLV2State() - unknown error");
  3936. break;
  3937. case LV2_STATE_ERR_BAD_TYPE:
  3938. carla_stderr("CarlaPluginLV2::updateLV2State() - error, bad type");
  3939. break;
  3940. case LV2_STATE_ERR_BAD_FLAGS:
  3941. carla_stderr("CarlaPluginLV2::updateLV2State() - error, bad flags");
  3942. break;
  3943. case LV2_STATE_ERR_NO_FEATURE:
  3944. carla_stderr("CarlaPluginLV2::updateLV2State() - error, missing feature");
  3945. break;
  3946. case LV2_STATE_ERR_NO_PROPERTY:
  3947. carla_stderr("CarlaPluginLV2::updateLV2State() - error, missing property");
  3948. break;
  3949. case LV2_STATE_ERR_NO_SPACE:
  3950. carla_stderr("CarlaPluginLV2::updateLV2State() - error, insufficient space");
  3951. break;
  3952. }
  3953. }
  3954. // -------------------------------------------------------------------
  3955. bool isRealtimeSafe() const noexcept
  3956. {
  3957. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr, false);
  3958. for (uint32_t i=0; i < fRdfDescriptor->FeatureCount; ++i)
  3959. {
  3960. if (std::strcmp(fRdfDescriptor->Features[i].URI, LV2_CORE__hardRTCapable) == 0)
  3961. return true;
  3962. }
  3963. return false;
  3964. }
  3965. // -------------------------------------------------------------------
  3966. bool isUiBridgeable(const uint32_t uiId) const noexcept
  3967. {
  3968. CARLA_SAFE_ASSERT_RETURN(uiId < fRdfDescriptor->UICount, false);
  3969. #ifndef LV2_UIS_ONLY_INPROCESS
  3970. const LV2_RDF_UI* const rdfUI(&fRdfDescriptor->UIs[uiId]);
  3971. for (uint32_t i=0; i < rdfUI->FeatureCount; ++i)
  3972. {
  3973. const LV2_RDF_Feature& feat(rdfUI->Features[i]);
  3974. if (! feat.Required)
  3975. continue;
  3976. if (std::strcmp(feat.URI, LV2_INSTANCE_ACCESS_URI) == 0)
  3977. return false;
  3978. if (std::strcmp(feat.URI, LV2_DATA_ACCESS_URI) == 0)
  3979. return false;
  3980. }
  3981. // Calf UIs are mostly useless without their special graphs
  3982. // but they can be crashy under certain conditions, so follow user preferences
  3983. if (std::strstr(rdfUI->URI, "http://calf.sourceforge.net/plugins/gui/") != nullptr)
  3984. return pData->engine->getOptions().preferUiBridges;
  3985. // LSP-Plugins UIs make heavy use of URIDs, for which carla right now is very slow
  3986. // FIXME after some optimization, remove this
  3987. if (std::strstr(rdfUI->URI, "http://lsp-plug.in/ui/lv2/") != nullptr)
  3988. return false;
  3989. return true;
  3990. #else
  3991. return false;
  3992. #endif
  3993. }
  3994. bool isUiResizable() const noexcept
  3995. {
  3996. CARLA_SAFE_ASSERT_RETURN(fUI.rdfDescriptor != nullptr, false);
  3997. for (uint32_t i=0; i < fUI.rdfDescriptor->FeatureCount; ++i)
  3998. {
  3999. if (std::strcmp(fUI.rdfDescriptor->Features[i].URI, LV2_UI__fixedSize) == 0)
  4000. return false;
  4001. if (std::strcmp(fUI.rdfDescriptor->Features[i].URI, LV2_UI__noUserResize) == 0)
  4002. return false;
  4003. }
  4004. return true;
  4005. }
  4006. const char* getUiBridgeBinary(const LV2_Property type) const
  4007. {
  4008. CarlaString bridgeBinary(pData->engine->getOptions().binaryDir);
  4009. if (bridgeBinary.isEmpty())
  4010. return nullptr;
  4011. switch (type)
  4012. {
  4013. case LV2_UI_GTK2:
  4014. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-gtk2";
  4015. break;
  4016. case LV2_UI_GTK3:
  4017. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-gtk3";
  4018. break;
  4019. case LV2_UI_QT4:
  4020. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-qt4";
  4021. break;
  4022. case LV2_UI_QT5:
  4023. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-qt5";
  4024. break;
  4025. case LV2_UI_COCOA:
  4026. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-cocoa";
  4027. break;
  4028. case LV2_UI_WINDOWS:
  4029. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-windows";
  4030. break;
  4031. case LV2_UI_X11:
  4032. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-x11";
  4033. break;
  4034. case LV2_UI_MOD:
  4035. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-modgui";
  4036. break;
  4037. #if 0
  4038. case LV2_UI_EXTERNAL:
  4039. case LV2_UI_OLD_EXTERNAL:
  4040. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-external";
  4041. break;
  4042. #endif
  4043. default:
  4044. return nullptr;
  4045. }
  4046. #ifdef CARLA_OS_WIN
  4047. bridgeBinary += ".exe";
  4048. #endif
  4049. if (! File(bridgeBinary.buffer()).existsAsFile())
  4050. return nullptr;
  4051. return bridgeBinary.dupSafe();
  4052. }
  4053. // -------------------------------------------------------------------
  4054. void recheckExtensions()
  4055. {
  4056. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr,);
  4057. carla_debug("CarlaPluginLV2::recheckExtensions()");
  4058. fExt.options = nullptr;
  4059. fExt.programs = nullptr;
  4060. fExt.state = nullptr;
  4061. fExt.worker = nullptr;
  4062. fExt.inlineDisplay = nullptr;
  4063. for (uint32_t i=0; i < fRdfDescriptor->ExtensionCount; ++i)
  4064. {
  4065. const char* const extension = fRdfDescriptor->Extensions[i];
  4066. CARLA_SAFE_ASSERT_CONTINUE(extension != nullptr);
  4067. /**/ if (std::strcmp(extension, LV2_OPTIONS__interface) == 0)
  4068. pData->hints |= PLUGIN_HAS_EXTENSION_OPTIONS;
  4069. else if (std::strcmp(extension, LV2_PROGRAMS__Interface) == 0)
  4070. pData->hints |= PLUGIN_HAS_EXTENSION_PROGRAMS;
  4071. else if (std::strcmp(extension, LV2_STATE__interface) == 0)
  4072. pData->hints |= PLUGIN_HAS_EXTENSION_STATE;
  4073. else if (std::strcmp(extension, LV2_WORKER__interface) == 0)
  4074. pData->hints |= PLUGIN_HAS_EXTENSION_WORKER;
  4075. else if (std::strcmp(extension, LV2_INLINEDISPLAY__interface) == 0)
  4076. pData->hints |= PLUGIN_HAS_EXTENSION_INLINE_DISPLAY;
  4077. else if (std::strcmp(extension, LV2_MIDNAM__interface) == 0)
  4078. pData->hints |= PLUGIN_HAS_EXTENSION_MIDNAM;
  4079. else
  4080. carla_stdout("Plugin '%s' has non-supported extension: '%s'", fRdfDescriptor->URI, extension);
  4081. }
  4082. // Fix for broken plugins, nasty!
  4083. for (uint32_t i=0; i < fRdfDescriptor->FeatureCount; ++i)
  4084. {
  4085. const LV2_RDF_Feature& feature(fRdfDescriptor->Features[i]);
  4086. if (std::strcmp(feature.URI, LV2_INLINEDISPLAY__queue_draw) == 0)
  4087. {
  4088. if (pData->hints & PLUGIN_HAS_EXTENSION_INLINE_DISPLAY)
  4089. break;
  4090. carla_stdout("Plugin '%s' uses inline-display but does not set extension data, nasty!", fRdfDescriptor->URI);
  4091. pData->hints |= PLUGIN_HAS_EXTENSION_INLINE_DISPLAY;
  4092. }
  4093. else if (std::strcmp(feature.URI, LV2_MIDNAM__update) == 0)
  4094. {
  4095. if (pData->hints & PLUGIN_HAS_EXTENSION_MIDNAM)
  4096. break;
  4097. carla_stdout("Plugin '%s' uses midnam but does not set extension data, nasty!", fRdfDescriptor->URI);
  4098. pData->hints |= PLUGIN_HAS_EXTENSION_MIDNAM;
  4099. }
  4100. }
  4101. if (fDescriptor->extension_data != nullptr)
  4102. {
  4103. if (pData->hints & PLUGIN_HAS_EXTENSION_OPTIONS)
  4104. fExt.options = (const LV2_Options_Interface*)fDescriptor->extension_data(LV2_OPTIONS__interface);
  4105. if (pData->hints & PLUGIN_HAS_EXTENSION_PROGRAMS)
  4106. fExt.programs = (const LV2_Programs_Interface*)fDescriptor->extension_data(LV2_PROGRAMS__Interface);
  4107. if (pData->hints & PLUGIN_HAS_EXTENSION_STATE)
  4108. fExt.state = (const LV2_State_Interface*)fDescriptor->extension_data(LV2_STATE__interface);
  4109. if (pData->hints & PLUGIN_HAS_EXTENSION_WORKER)
  4110. fExt.worker = (const LV2_Worker_Interface*)fDescriptor->extension_data(LV2_WORKER__interface);
  4111. if (pData->hints & PLUGIN_HAS_EXTENSION_INLINE_DISPLAY)
  4112. fExt.inlineDisplay = (const LV2_Inline_Display_Interface*)fDescriptor->extension_data(LV2_INLINEDISPLAY__interface);
  4113. if (pData->hints & PLUGIN_HAS_EXTENSION_MIDNAM)
  4114. fExt.midnam = (const LV2_Midnam_Interface*)fDescriptor->extension_data(LV2_MIDNAM__interface);
  4115. // check if invalid
  4116. if (fExt.options != nullptr && fExt.options->get == nullptr && fExt.options->set == nullptr)
  4117. fExt.options = nullptr;
  4118. if (fExt.programs != nullptr && (fExt.programs->get_program == nullptr || fExt.programs->select_program == nullptr))
  4119. fExt.programs = nullptr;
  4120. if (fExt.state != nullptr && (fExt.state->save == nullptr || fExt.state->restore == nullptr))
  4121. fExt.state = nullptr;
  4122. if (fExt.worker != nullptr && fExt.worker->work == nullptr)
  4123. fExt.worker = nullptr;
  4124. if (fExt.inlineDisplay != nullptr)
  4125. {
  4126. if (fExt.inlineDisplay->render != nullptr)
  4127. {
  4128. pData->hints |= PLUGIN_HAS_INLINE_DISPLAY;
  4129. pData->setCanDeleteLib(false);
  4130. }
  4131. else
  4132. {
  4133. fExt.inlineDisplay = nullptr;
  4134. }
  4135. }
  4136. if (fExt.midnam != nullptr && fExt.midnam->midnam == nullptr)
  4137. fExt.midnam = nullptr;
  4138. }
  4139. CARLA_SAFE_ASSERT_RETURN(fLatencyIndex == -1,);
  4140. int32_t iCtrl=0;
  4141. for (uint32_t i=0, count=fRdfDescriptor->PortCount; i<count; ++i)
  4142. {
  4143. const LV2_Property portTypes(fRdfDescriptor->Ports[i].Types);
  4144. if (! LV2_IS_PORT_CONTROL(portTypes))
  4145. continue;
  4146. const CarlaScopedValueSetter<int32_t> svs(iCtrl, iCtrl, iCtrl+1);
  4147. if (! LV2_IS_PORT_OUTPUT(portTypes))
  4148. continue;
  4149. const LV2_Property portDesignation(fRdfDescriptor->Ports[i].Designation);
  4150. if (! LV2_IS_PORT_DESIGNATION_LATENCY(portDesignation))
  4151. continue;
  4152. fLatencyIndex = iCtrl;
  4153. break;
  4154. }
  4155. }
  4156. // -------------------------------------------------------------------
  4157. void updateUi()
  4158. {
  4159. CARLA_SAFE_ASSERT_RETURN(fUI.handle != nullptr,);
  4160. CARLA_SAFE_ASSERT_RETURN(fUI.descriptor != nullptr,);
  4161. carla_debug("CarlaPluginLV2::updateUi()");
  4162. // update midi program
  4163. if (fExt.uiprograms != nullptr && pData->midiprog.count > 0 && pData->midiprog.current >= 0)
  4164. {
  4165. const MidiProgramData& curData(pData->midiprog.getCurrent());
  4166. fExt.uiprograms->select_program(fUI.handle, curData.bank, curData.program);
  4167. }
  4168. // update control ports
  4169. if (fUI.descriptor->port_event != nullptr)
  4170. {
  4171. float value;
  4172. for (uint32_t i=0; i < pData->param.count; ++i)
  4173. {
  4174. value = getParameterValue(i);
  4175. fUI.descriptor->port_event(fUI.handle, static_cast<uint32_t>(pData->param.data[i].rindex), sizeof(float), kUridNull, &value);
  4176. }
  4177. }
  4178. }
  4179. // -------------------------------------------------------------------
  4180. LV2_URID getCustomURID(const char* const uri)
  4181. {
  4182. CARLA_SAFE_ASSERT_RETURN(uri != nullptr && uri[0] != '\0', kUridNull);
  4183. carla_debug("CarlaPluginLV2::getCustomURID(\"%s\")", uri);
  4184. const std::string s_uri(uri);
  4185. const std::ptrdiff_t s_pos(std::find(fCustomURIDs.begin(), fCustomURIDs.end(), s_uri) - fCustomURIDs.begin());
  4186. if (s_pos <= 0 || s_pos >= INT32_MAX)
  4187. return kUridNull;
  4188. const LV2_URID urid = static_cast<LV2_URID>(s_pos);
  4189. const LV2_URID uriCount = static_cast<LV2_URID>(fCustomURIDs.size());
  4190. if (urid < uriCount)
  4191. return urid;
  4192. CARLA_SAFE_ASSERT(urid == uriCount);
  4193. fCustomURIDs.push_back(uri);
  4194. if (fUI.type == UI::TYPE_BRIDGE && fPipeServer.isPipeRunning())
  4195. fPipeServer.writeLv2UridMessage(urid, uri);
  4196. return urid;
  4197. }
  4198. const char* getCustomURIDString(const LV2_URID urid) const noexcept
  4199. {
  4200. CARLA_SAFE_ASSERT_RETURN(urid != kUridNull, kUnmapFallback);
  4201. CARLA_SAFE_ASSERT_RETURN(urid < fCustomURIDs.size(), kUnmapFallback);
  4202. carla_debug("CarlaPluginLV2::getCustomURIString(%i)", urid);
  4203. return fCustomURIDs[urid].c_str();
  4204. }
  4205. // -------------------------------------------------------------------
  4206. void handleProgramChanged(const int32_t index)
  4207. {
  4208. CARLA_SAFE_ASSERT_RETURN(index >= -1,);
  4209. carla_debug("CarlaPluginLV2::handleProgramChanged(%i)", index);
  4210. if (index == -1)
  4211. {
  4212. const ScopedSingleProcessLocker spl(this, true);
  4213. return reloadPrograms(false);
  4214. }
  4215. if (index < static_cast<int32_t>(pData->midiprog.count) && fExt.programs != nullptr && fExt.programs->get_program != nullptr)
  4216. {
  4217. if (const LV2_Program_Descriptor* const progDesc = fExt.programs->get_program(fHandle, static_cast<uint32_t>(index)))
  4218. {
  4219. CARLA_SAFE_ASSERT_RETURN(progDesc->name != nullptr,);
  4220. if (pData->midiprog.data[index].name != nullptr)
  4221. delete[] pData->midiprog.data[index].name;
  4222. pData->midiprog.data[index].name = carla_strdup(progDesc->name);
  4223. if (index == pData->midiprog.current)
  4224. pData->engine->callback(true, true, ENGINE_CALLBACK_UPDATE, pData->id, 0, 0, 0, 0.0, nullptr);
  4225. else
  4226. pData->engine->callback(true, true, ENGINE_CALLBACK_RELOAD_PROGRAMS, pData->id, 0, 0, 0, 0.0, nullptr);
  4227. }
  4228. }
  4229. }
  4230. // -------------------------------------------------------------------
  4231. LV2_Resize_Port_Status handleResizePort(const uint32_t index, const size_t size)
  4232. {
  4233. CARLA_SAFE_ASSERT_RETURN(size > 0, LV2_RESIZE_PORT_ERR_UNKNOWN);
  4234. carla_debug("CarlaPluginLV2::handleResizePort(%i, " P_SIZE ")", index, size);
  4235. // TODO
  4236. return LV2_RESIZE_PORT_ERR_NO_SPACE;
  4237. (void)index;
  4238. }
  4239. // -------------------------------------------------------------------
  4240. LV2_State_Status handleStateStore(const uint32_t key, const void* const value, const size_t size, const uint32_t type, const uint32_t flags)
  4241. {
  4242. CARLA_SAFE_ASSERT_RETURN(key != kUridNull, LV2_STATE_ERR_NO_PROPERTY);
  4243. CARLA_SAFE_ASSERT_RETURN(value != nullptr, LV2_STATE_ERR_NO_PROPERTY);
  4244. CARLA_SAFE_ASSERT_RETURN(size > 0, LV2_STATE_ERR_NO_PROPERTY);
  4245. CARLA_SAFE_ASSERT_RETURN(type != kUridNull, LV2_STATE_ERR_BAD_TYPE);
  4246. // FIXME linuxsampler does not set POD flag
  4247. // CARLA_SAFE_ASSERT_RETURN(flags & LV2_STATE_IS_POD, LV2_STATE_ERR_BAD_FLAGS);
  4248. carla_debug("CarlaPluginLV2::handleStateStore(%i:\"%s\", %p, " P_SIZE ", %i:\"%s\", %i)",
  4249. key, carla_lv2_urid_unmap(this, key), value, size, type, carla_lv2_urid_unmap(this, type), flags);
  4250. const char* const skey(carla_lv2_urid_unmap(this, key));
  4251. const char* const stype(carla_lv2_urid_unmap(this, type));
  4252. CARLA_SAFE_ASSERT_RETURN(skey != nullptr && skey != kUnmapFallback, LV2_STATE_ERR_BAD_TYPE);
  4253. CARLA_SAFE_ASSERT_RETURN(stype != nullptr && stype != kUnmapFallback, LV2_STATE_ERR_BAD_TYPE);
  4254. // Check if we already have this key
  4255. for (LinkedList<CustomData>::Itenerator it = pData->custom.begin2(); it.valid(); it.next())
  4256. {
  4257. CustomData& cData(it.getValue(kCustomDataFallbackNC));
  4258. CARLA_SAFE_ASSERT_CONTINUE(cData.isValid());
  4259. if (std::strcmp(cData.key, skey) == 0)
  4260. {
  4261. // found it
  4262. delete[] cData.value;
  4263. if (type == kUridAtomString || type == kUridAtomPath)
  4264. cData.value = carla_strdup((const char*)value);
  4265. else
  4266. cData.value = CarlaString::asBase64(value, size).dup();
  4267. return LV2_STATE_SUCCESS;
  4268. }
  4269. }
  4270. // Otherwise store it
  4271. CustomData newData;
  4272. newData.type = carla_strdup(stype);
  4273. newData.key = carla_strdup(skey);
  4274. if (type == kUridAtomString || type == kUridAtomPath)
  4275. newData.value = carla_strdup((const char*)value);
  4276. else
  4277. newData.value = CarlaString::asBase64(value, size).dup();
  4278. pData->custom.append(newData);
  4279. return LV2_STATE_SUCCESS;
  4280. // unused
  4281. (void)flags;
  4282. }
  4283. const void* handleStateRetrieve(const uint32_t key, size_t* const size, uint32_t* const type, uint32_t* const flags)
  4284. {
  4285. CARLA_SAFE_ASSERT_RETURN(key != kUridNull, nullptr);
  4286. CARLA_SAFE_ASSERT_RETURN(size != nullptr, nullptr);
  4287. CARLA_SAFE_ASSERT_RETURN(type != nullptr, nullptr);
  4288. CARLA_SAFE_ASSERT_RETURN(flags != nullptr, nullptr);
  4289. carla_debug("CarlaPluginLV2::handleStateRetrieve(%i, %p, %p, %p)", key, size, type, flags);
  4290. const char* const skey(carla_lv2_urid_unmap(this, key));
  4291. CARLA_SAFE_ASSERT_RETURN(skey != nullptr && skey != kUnmapFallback, nullptr);
  4292. const char* stype = nullptr;
  4293. const char* stringData = nullptr;
  4294. for (LinkedList<CustomData>::Itenerator it = pData->custom.begin2(); it.valid(); it.next())
  4295. {
  4296. const CustomData& cData(it.getValue(kCustomDataFallback));
  4297. CARLA_SAFE_ASSERT_CONTINUE(cData.isValid());
  4298. if (std::strcmp(cData.key, skey) == 0)
  4299. {
  4300. stype = cData.type;
  4301. stringData = cData.value;
  4302. break;
  4303. }
  4304. }
  4305. if (stype == nullptr || stringData == nullptr)
  4306. {
  4307. carla_stderr("Plugin requested value for '%s' which is not available", skey);
  4308. *size = *type = *flags = 0;
  4309. return nullptr;
  4310. }
  4311. *type = carla_lv2_urid_map(this, stype);
  4312. *flags = LV2_STATE_IS_POD;
  4313. if (*type == kUridAtomString || *type == kUridAtomPath)
  4314. {
  4315. *size = std::strlen(stringData);
  4316. return stringData;
  4317. }
  4318. if (fLastStateChunk != nullptr)
  4319. {
  4320. std::free(fLastStateChunk);
  4321. fLastStateChunk = nullptr;
  4322. }
  4323. std::vector<uint8_t> chunk(carla_getChunkFromBase64String(stringData));
  4324. CARLA_SAFE_ASSERT_RETURN(chunk.size() > 0, nullptr);
  4325. fLastStateChunk = std::malloc(chunk.size());
  4326. CARLA_SAFE_ASSERT_RETURN(fLastStateChunk != nullptr, nullptr);
  4327. #ifdef CARLA_PROPER_CPP11_SUPPORT
  4328. std::memcpy(fLastStateChunk, chunk.data(), chunk.size());
  4329. #else
  4330. std::memcpy(fLastStateChunk, &chunk.front(), chunk.size());
  4331. #endif
  4332. *size = chunk.size();
  4333. return fLastStateChunk;
  4334. }
  4335. // -------------------------------------------------------------------
  4336. LV2_Worker_Status handleWorkerSchedule(const uint32_t size, const void* const data)
  4337. {
  4338. CARLA_SAFE_ASSERT_RETURN(fExt.worker != nullptr && fExt.worker->work != nullptr, LV2_WORKER_ERR_UNKNOWN);
  4339. CARLA_SAFE_ASSERT_RETURN(fEventsIn.ctrl != nullptr, LV2_WORKER_ERR_UNKNOWN);
  4340. carla_debug("CarlaPluginLV2::handleWorkerSchedule(%i, %p)", size, data);
  4341. if (pData->engine->isOffline())
  4342. {
  4343. fExt.worker->work(fHandle, carla_lv2_worker_respond, this, size, data);
  4344. return LV2_WORKER_SUCCESS;
  4345. }
  4346. LV2_Atom atom;
  4347. atom.size = size;
  4348. atom.type = kUridCarlaAtomWorkerIn;
  4349. return fAtomBufferWorkerIn.putChunk(&atom, data, fEventsOut.ctrlIndex) ? LV2_WORKER_SUCCESS : LV2_WORKER_ERR_NO_SPACE;
  4350. }
  4351. LV2_Worker_Status handleWorkerRespond(const uint32_t size, const void* const data)
  4352. {
  4353. CARLA_SAFE_ASSERT_RETURN(fExt.worker != nullptr && fExt.worker->work_response != nullptr, LV2_WORKER_ERR_UNKNOWN);
  4354. carla_debug("CarlaPluginLV2::handleWorkerRespond(%i, %p)", size, data);
  4355. LV2_Atom atom;
  4356. atom.size = size;
  4357. atom.type = kUridCarlaAtomWorkerResp;
  4358. return fAtomBufferWorkerResp.putChunk(&atom, data, fEventsIn.ctrlIndex) ? LV2_WORKER_SUCCESS : LV2_WORKER_ERR_NO_SPACE;
  4359. }
  4360. // -------------------------------------------------------------------
  4361. void handleInlineDisplayQueueRedraw()
  4362. {
  4363. fInlineDisplayNeedsRedraw = true;
  4364. }
  4365. const LV2_Inline_Display_Image_Surface* renderInlineDisplay(const uint32_t width, const uint32_t height)
  4366. {
  4367. CARLA_SAFE_ASSERT_RETURN(fExt.inlineDisplay != nullptr && fExt.inlineDisplay->render != nullptr, nullptr);
  4368. CARLA_SAFE_ASSERT_RETURN(width > 0, nullptr);
  4369. CARLA_SAFE_ASSERT_RETURN(height > 0, nullptr);
  4370. return fExt.inlineDisplay->render(fHandle, width, height);
  4371. }
  4372. // -------------------------------------------------------------------
  4373. void handleMidnamUpdate()
  4374. {
  4375. CARLA_SAFE_ASSERT_RETURN(fExt.midnam != nullptr,);
  4376. if (fEventsIn.ctrl == nullptr)
  4377. return;
  4378. char* const midnam = fExt.midnam->midnam(fHandle);
  4379. CARLA_SAFE_ASSERT_RETURN(midnam != nullptr,);
  4380. fEventsIn.ctrl->port->setMetaData("http://www.midi.org/dtds/MIDINameDocument10.dtd", midnam, "text/xml");
  4381. if (fExt.midnam->free != nullptr)
  4382. fExt.midnam->free(midnam);
  4383. }
  4384. // -------------------------------------------------------------------
  4385. void handleExternalUIClosed()
  4386. {
  4387. CARLA_SAFE_ASSERT_RETURN(fUI.type == UI::TYPE_EXTERNAL,);
  4388. carla_debug("CarlaPluginLV2::handleExternalUIClosed()");
  4389. fNeedsUiClose = true;
  4390. }
  4391. void handlePluginUIClosed() override
  4392. {
  4393. CARLA_SAFE_ASSERT_RETURN(fUI.type == UI::TYPE_EMBED,);
  4394. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  4395. carla_debug("CarlaPluginLV2::handlePluginUIClosed()");
  4396. fNeedsUiClose = true;
  4397. }
  4398. void handlePluginUIResized(const uint width, const uint height) override
  4399. {
  4400. CARLA_SAFE_ASSERT_RETURN(fUI.type == UI::TYPE_EMBED,);
  4401. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  4402. carla_debug("CarlaPluginLV2::handlePluginUIResized(%u, %u)", width, height);
  4403. if (fUI.handle != nullptr && fExt.uiresize != nullptr)
  4404. fExt.uiresize->ui_resize(fUI.handle, static_cast<int>(width), static_cast<int>(height));
  4405. }
  4406. // -------------------------------------------------------------------
  4407. uint32_t handleUIPortMap(const char* const symbol) const noexcept
  4408. {
  4409. CARLA_SAFE_ASSERT_RETURN(symbol != nullptr && symbol[0] != '\0', LV2UI_INVALID_PORT_INDEX);
  4410. carla_debug("CarlaPluginLV2::handleUIPortMap(\"%s\")", symbol);
  4411. for (uint32_t i=0; i < fRdfDescriptor->PortCount; ++i)
  4412. {
  4413. if (std::strcmp(fRdfDescriptor->Ports[i].Symbol, symbol) == 0)
  4414. return i;
  4415. }
  4416. return LV2UI_INVALID_PORT_INDEX;
  4417. }
  4418. int handleUIResize(const int width, const int height)
  4419. {
  4420. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr, 1);
  4421. CARLA_SAFE_ASSERT_RETURN(width > 0, 1);
  4422. CARLA_SAFE_ASSERT_RETURN(height > 0, 1);
  4423. carla_debug("CarlaPluginLV2::handleUIResize(%i, %i)", width, height);
  4424. fUI.window->setSize(static_cast<uint>(width), static_cast<uint>(height), true);
  4425. return 0;
  4426. }
  4427. void handleUITouch(const uint32_t rindex, const bool touch)
  4428. {
  4429. carla_debug("CarlaPluginLV2::handleUITouch(%u, %s)", rindex, bool2str(touch));
  4430. uint32_t index = LV2UI_INVALID_PORT_INDEX;
  4431. for (uint32_t i=0; i < pData->param.count; ++i)
  4432. {
  4433. if (pData->param.data[i].rindex != static_cast<int32_t>(rindex))
  4434. continue;
  4435. index = i;
  4436. break;
  4437. }
  4438. CARLA_SAFE_ASSERT_RETURN(index != LV2UI_INVALID_PORT_INDEX,);
  4439. pData->engine->touchPluginParameter(pData->id, index, touch);
  4440. }
  4441. void handleUIWrite(const uint32_t rindex, const uint32_t bufferSize, const uint32_t format, const void* const buffer)
  4442. {
  4443. CARLA_SAFE_ASSERT_RETURN(buffer != nullptr,);
  4444. CARLA_SAFE_ASSERT_RETURN(bufferSize > 0,);
  4445. carla_debug("CarlaPluginLV2::handleUIWrite(%i, %i, %i, %p)", rindex, bufferSize, format, buffer);
  4446. uint32_t index = LV2UI_INVALID_PORT_INDEX;
  4447. switch (format)
  4448. {
  4449. case kUridNull: {
  4450. CARLA_SAFE_ASSERT_RETURN(rindex < fRdfDescriptor->PortCount,);
  4451. CARLA_SAFE_ASSERT_RETURN(bufferSize == sizeof(float),);
  4452. for (uint32_t i=0; i < pData->param.count; ++i)
  4453. {
  4454. if (pData->param.data[i].rindex != static_cast<int32_t>(rindex))
  4455. continue;
  4456. index = i;
  4457. break;
  4458. }
  4459. CARLA_SAFE_ASSERT_RETURN(index != LV2UI_INVALID_PORT_INDEX,);
  4460. const float value(*(const float*)buffer);
  4461. // check if we should feedback message back to UI
  4462. bool sendGui = false;
  4463. if (const uint32_t notifCount = fUI.rdfDescriptor->PortNotificationCount)
  4464. {
  4465. const char* const portSymbol = fRdfDescriptor->Ports[rindex].Symbol;
  4466. for (uint32_t i=0; i < notifCount; ++i)
  4467. {
  4468. const LV2_RDF_UI_PortNotification& portNotif(fUI.rdfDescriptor->PortNotifications[i]);
  4469. if (portNotif.Protocol != LV2_UI_PORT_PROTOCOL_FLOAT)
  4470. continue;
  4471. if (portNotif.Symbol != nullptr)
  4472. {
  4473. if (std::strcmp(portNotif.Symbol, portSymbol) != 0)
  4474. continue;
  4475. }
  4476. else if (portNotif.Index != rindex)
  4477. {
  4478. continue;
  4479. }
  4480. sendGui = true;
  4481. break;
  4482. }
  4483. }
  4484. setParameterValue(index, value, sendGui, true, true);
  4485. } break;
  4486. case kUridAtomTransferAtom:
  4487. case kUridAtomTransferEvent: {
  4488. CARLA_SAFE_ASSERT_RETURN(bufferSize >= sizeof(LV2_Atom),);
  4489. const LV2_Atom* const atom((const LV2_Atom*)buffer);
  4490. // plugins sometimes fail on this, not good...
  4491. const uint32_t totalSize = lv2_atom_total_size(atom);
  4492. const uint32_t paddedSize = lv2_atom_pad_size(totalSize);
  4493. if (bufferSize != totalSize && bufferSize != paddedSize)
  4494. carla_stderr2("Warning: LV2 UI sending atom with invalid size %u! size: %u, padded-size: %u",
  4495. bufferSize, totalSize, paddedSize);
  4496. for (uint32_t i=0; i < fEventsIn.count; ++i)
  4497. {
  4498. if (fEventsIn.data[i].rindex != rindex)
  4499. continue;
  4500. index = i;
  4501. break;
  4502. }
  4503. // for bad plugins
  4504. if (index == LV2UI_INVALID_PORT_INDEX)
  4505. {
  4506. CARLA_SAFE_ASSERT(index != LV2UI_INVALID_PORT_INDEX); // FIXME
  4507. index = fEventsIn.ctrlIndex;
  4508. }
  4509. fAtomBufferEvIn.put(atom, index);
  4510. } break;
  4511. default:
  4512. carla_stdout("CarlaPluginLV2::handleUIWrite(%i, %i, %i:\"%s\", %p) - unknown format",
  4513. rindex, bufferSize, format, carla_lv2_urid_unmap(this, format), buffer);
  4514. break;
  4515. }
  4516. }
  4517. // -------------------------------------------------------------------
  4518. void handleLilvSetPortValue(const char* const portSymbol, const void* const value, const uint32_t size, const uint32_t type)
  4519. {
  4520. CARLA_SAFE_ASSERT_RETURN(portSymbol != nullptr && portSymbol[0] != '\0',);
  4521. CARLA_SAFE_ASSERT_RETURN(value != nullptr,);
  4522. CARLA_SAFE_ASSERT_RETURN(size > 0,);
  4523. CARLA_SAFE_ASSERT_RETURN(type != kUridNull,);
  4524. carla_debug("CarlaPluginLV2::handleLilvSetPortValue(\"%s\", %p, %i, %i)", portSymbol, value, size, type);
  4525. int32_t rindex = -1;
  4526. for (uint32_t i=0; i < fRdfDescriptor->PortCount; ++i)
  4527. {
  4528. if (std::strcmp(fRdfDescriptor->Ports[i].Symbol, portSymbol) == 0)
  4529. {
  4530. rindex = static_cast<int32_t>(i);
  4531. break;
  4532. }
  4533. }
  4534. CARLA_SAFE_ASSERT_RETURN(rindex >= 0,);
  4535. float paramValue;
  4536. switch (type)
  4537. {
  4538. case kUridAtomBool:
  4539. CARLA_SAFE_ASSERT_RETURN(size == sizeof(bool),);
  4540. paramValue = (*(const bool*)value) ? 1.0f : 0.0f;
  4541. break;
  4542. case kUridAtomDouble:
  4543. CARLA_SAFE_ASSERT_RETURN(size == sizeof(double),);
  4544. paramValue = static_cast<float>((*(const double*)value));
  4545. break;
  4546. case kUridAtomFloat:
  4547. CARLA_SAFE_ASSERT_RETURN(size == sizeof(float),);
  4548. paramValue = (*(const float*)value);
  4549. break;
  4550. case kUridAtomInt:
  4551. CARLA_SAFE_ASSERT_RETURN(size == sizeof(int32_t),);
  4552. paramValue = static_cast<float>((*(const int32_t*)value));
  4553. break;
  4554. case kUridAtomLong:
  4555. CARLA_SAFE_ASSERT_RETURN(size == sizeof(int64_t),);
  4556. paramValue = static_cast<float>((*(const int64_t*)value));
  4557. break;
  4558. default:
  4559. carla_stdout("CarlaPluginLV2::handleLilvSetPortValue(\"%s\", %p, %i, %i:\"%s\") - unknown type",
  4560. portSymbol, value, size, type, carla_lv2_urid_unmap(this, type));
  4561. return;
  4562. }
  4563. for (uint32_t i=0; i < pData->param.count; ++i)
  4564. {
  4565. if (pData->param.data[i].rindex == rindex)
  4566. {
  4567. setParameterValueRT(i, paramValue, true);
  4568. break;
  4569. }
  4570. }
  4571. }
  4572. // -------------------------------------------------------------------
  4573. void* getNativeHandle() const noexcept override
  4574. {
  4575. return fHandle;
  4576. }
  4577. const void* getNativeDescriptor() const noexcept override
  4578. {
  4579. return fDescriptor;
  4580. }
  4581. uintptr_t getUiBridgeProcessId() const noexcept override
  4582. {
  4583. return fPipeServer.isPipeRunning() ? fPipeServer.getPID() : 0;
  4584. }
  4585. // -------------------------------------------------------------------
  4586. public:
  4587. bool init(const char* const name, const char* const uri, const uint options)
  4588. {
  4589. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  4590. // ---------------------------------------------------------------
  4591. // first checks
  4592. if (pData->client != nullptr)
  4593. {
  4594. pData->engine->setLastError("Plugin client is already registered");
  4595. return false;
  4596. }
  4597. if (uri == nullptr || uri[0] == '\0')
  4598. {
  4599. pData->engine->setLastError("null uri");
  4600. return false;
  4601. }
  4602. const EngineOptions& opts(pData->engine->getOptions());
  4603. // ---------------------------------------------------------------
  4604. // Init LV2 World if needed, sets LV2_PATH for lilv
  4605. Lv2WorldClass& lv2World(Lv2WorldClass::getInstance());
  4606. if (opts.pathLV2 != nullptr && opts.pathLV2[0] != '\0')
  4607. lv2World.initIfNeeded(opts.pathLV2);
  4608. else if (const char* const LV2_PATH = std::getenv("LV2_PATH"))
  4609. lv2World.initIfNeeded(LV2_PATH);
  4610. else
  4611. lv2World.initIfNeeded(LILV_DEFAULT_LV2_PATH);
  4612. // ---------------------------------------------------------------
  4613. // get plugin from lv2_rdf (lilv)
  4614. fRdfDescriptor = lv2_rdf_new(uri, true);
  4615. if (fRdfDescriptor == nullptr)
  4616. {
  4617. pData->engine->setLastError("Failed to find the requested plugin");
  4618. return false;
  4619. }
  4620. // ---------------------------------------------------------------
  4621. // open DLL
  4622. if (! pData->libOpen(fRdfDescriptor->Binary))
  4623. {
  4624. pData->engine->setLastError(pData->libError(fRdfDescriptor->Binary));
  4625. return false;
  4626. }
  4627. // ---------------------------------------------------------------
  4628. // try to get DLL main entry via new mode
  4629. if (const LV2_Lib_Descriptor_Function libDescFn = pData->libSymbol<LV2_Lib_Descriptor_Function>("lv2_lib_descriptor"))
  4630. {
  4631. // -----------------------------------------------------------
  4632. // all ok, get lib descriptor
  4633. const LV2_Lib_Descriptor* const libDesc = libDescFn(fRdfDescriptor->Bundle, nullptr);
  4634. if (libDesc == nullptr)
  4635. {
  4636. pData->engine->setLastError("Could not find the LV2 Descriptor");
  4637. return false;
  4638. }
  4639. // -----------------------------------------------------------
  4640. // get descriptor that matches URI (new mode)
  4641. uint32_t i = 0;
  4642. while ((fDescriptor = libDesc->get_plugin(libDesc->handle, i++)))
  4643. {
  4644. if (std::strcmp(fDescriptor->URI, uri) == 0)
  4645. break;
  4646. }
  4647. }
  4648. else
  4649. {
  4650. // -----------------------------------------------------------
  4651. // get DLL main entry (old mode)
  4652. const LV2_Descriptor_Function descFn = pData->libSymbol<LV2_Descriptor_Function>("lv2_descriptor");
  4653. if (descFn == nullptr)
  4654. {
  4655. pData->engine->setLastError("Could not find the LV2 Descriptor in the plugin library");
  4656. return false;
  4657. }
  4658. // -----------------------------------------------------------
  4659. // get descriptor that matches URI (old mode)
  4660. uint32_t i = 0;
  4661. while ((fDescriptor = descFn(i++)))
  4662. {
  4663. if (std::strcmp(fDescriptor->URI, uri) == 0)
  4664. break;
  4665. }
  4666. }
  4667. if (fDescriptor == nullptr)
  4668. {
  4669. pData->engine->setLastError("Could not find the requested plugin URI in the plugin library");
  4670. return false;
  4671. }
  4672. // ---------------------------------------------------------------
  4673. // check supported port-types and features
  4674. bool canContinue = true;
  4675. // Check supported ports
  4676. for (uint32_t j=0; j < fRdfDescriptor->PortCount; ++j)
  4677. {
  4678. const LV2_Property portTypes(fRdfDescriptor->Ports[j].Types);
  4679. if (! is_lv2_port_supported(portTypes))
  4680. {
  4681. if (! LV2_IS_PORT_OPTIONAL(fRdfDescriptor->Ports[j].Properties))
  4682. {
  4683. pData->engine->setLastError("Plugin requires a port type that is not currently supported");
  4684. canContinue = false;
  4685. break;
  4686. }
  4687. }
  4688. }
  4689. // Check supported features
  4690. for (uint32_t j=0; j < fRdfDescriptor->FeatureCount && canContinue; ++j)
  4691. {
  4692. const LV2_RDF_Feature& feature(fRdfDescriptor->Features[j]);
  4693. if (std::strcmp(feature.URI, LV2_DATA_ACCESS_URI) == 0 || std::strcmp(feature.URI, LV2_INSTANCE_ACCESS_URI) == 0)
  4694. {
  4695. carla_stderr("Plugin DSP wants UI feature '%s', ignoring this", feature.URI);
  4696. }
  4697. else if (std::strcmp(feature.URI, LV2_BUF_SIZE__fixedBlockLength) == 0)
  4698. {
  4699. fNeedsFixedBuffers = true;
  4700. }
  4701. else if (std::strcmp(feature.URI, LV2_PORT_PROPS__supportsStrictBounds) == 0)
  4702. {
  4703. fStrictBounds = feature.Required ? 1 : 0;
  4704. }
  4705. else if (feature.Required && ! is_lv2_feature_supported(feature.URI))
  4706. {
  4707. CarlaString msg("Plugin wants a feature that is not supported:\n");
  4708. msg += feature.URI;
  4709. canContinue = false;
  4710. pData->engine->setLastError(msg);
  4711. break;
  4712. }
  4713. }
  4714. if (! canContinue)
  4715. {
  4716. // error already set
  4717. return false;
  4718. }
  4719. if (fNeedsFixedBuffers && ! pData->engine->usesConstantBufferSize())
  4720. {
  4721. pData->engine->setLastError("Cannot use this plugin under the current engine.\n"
  4722. "The plugin requires a fixed block size which is not possible right now.");
  4723. return false;
  4724. }
  4725. // ---------------------------------------------------------------
  4726. // set icon
  4727. if (std::strncmp(fDescriptor->URI, "http://distrho.sf.net/", 22) == 0)
  4728. pData->iconName = carla_strdup_safe("distrho");
  4729. // ---------------------------------------------------------------
  4730. // set info
  4731. if (name != nullptr && name[0] != '\0')
  4732. pData->name = pData->engine->getUniquePluginName(name);
  4733. else
  4734. pData->name = pData->engine->getUniquePluginName(fRdfDescriptor->Name);
  4735. // ---------------------------------------------------------------
  4736. // register client
  4737. pData->client = pData->engine->addClient(this);
  4738. if (pData->client == nullptr || ! pData->client->isOk())
  4739. {
  4740. pData->engine->setLastError("Failed to register plugin client");
  4741. return false;
  4742. }
  4743. // ---------------------------------------------------------------
  4744. // initialize options
  4745. const int bufferSize = static_cast<int>(pData->engine->getBufferSize());
  4746. fLv2Options.minBufferSize = fNeedsFixedBuffers ? bufferSize : 1;
  4747. fLv2Options.maxBufferSize = bufferSize;
  4748. fLv2Options.nominalBufferSize = bufferSize;
  4749. fLv2Options.sampleRate = static_cast<float>(pData->engine->getSampleRate());
  4750. fLv2Options.transientWinId = static_cast<int64_t>(opts.frontendWinId);
  4751. uint32_t eventBufferSize = MAX_DEFAULT_BUFFER_SIZE;
  4752. for (uint32_t j=0; j < fRdfDescriptor->PortCount; ++j)
  4753. {
  4754. const LV2_Property portTypes(fRdfDescriptor->Ports[j].Types);
  4755. if (LV2_IS_PORT_ATOM_SEQUENCE(portTypes) || LV2_IS_PORT_EVENT(portTypes) || LV2_IS_PORT_MIDI_LL(portTypes))
  4756. {
  4757. if (fRdfDescriptor->Ports[j].MinimumSize > eventBufferSize)
  4758. eventBufferSize = fRdfDescriptor->Ports[j].MinimumSize;
  4759. }
  4760. }
  4761. fLv2Options.sequenceSize = static_cast<int>(eventBufferSize);
  4762. fLv2Options.bgColor = opts.bgColor;
  4763. fLv2Options.fgColor = opts.fgColor;
  4764. fLv2Options.uiScale = opts.uiScale;
  4765. // ---------------------------------------------------------------
  4766. // initialize features (part 1)
  4767. LV2_Event_Feature* const eventFt = new LV2_Event_Feature;
  4768. eventFt->callback_data = this;
  4769. eventFt->lv2_event_ref = carla_lv2_event_ref;
  4770. eventFt->lv2_event_unref = carla_lv2_event_unref;
  4771. LV2_Log_Log* const logFt = new LV2_Log_Log;
  4772. logFt->handle = this;
  4773. logFt->printf = carla_lv2_log_printf;
  4774. logFt->vprintf = carla_lv2_log_vprintf;
  4775. LV2_State_Make_Path* const stateMakePathFt = new LV2_State_Make_Path;
  4776. stateMakePathFt->handle = this;
  4777. stateMakePathFt->path = carla_lv2_state_make_path;
  4778. LV2_State_Map_Path* const stateMapPathFt = new LV2_State_Map_Path;
  4779. stateMapPathFt->handle = this;
  4780. stateMapPathFt->abstract_path = carla_lv2_state_map_abstract_path;
  4781. stateMapPathFt->absolute_path = carla_lv2_state_map_absolute_path;
  4782. LV2_Programs_Host* const programsFt = new LV2_Programs_Host;
  4783. programsFt->handle = this;
  4784. programsFt->program_changed = carla_lv2_program_changed;
  4785. LV2_Resize_Port_Resize* const rsPortFt = new LV2_Resize_Port_Resize;
  4786. rsPortFt->data = this;
  4787. rsPortFt->resize = carla_lv2_resize_port;
  4788. LV2_RtMemPool_Pool* const rtMemPoolFt = new LV2_RtMemPool_Pool;
  4789. lv2_rtmempool_init(rtMemPoolFt);
  4790. LV2_RtMemPool_Pool_Deprecated* const rtMemPoolOldFt = new LV2_RtMemPool_Pool_Deprecated;
  4791. lv2_rtmempool_init_deprecated(rtMemPoolOldFt);
  4792. LV2_URI_Map_Feature* const uriMapFt = new LV2_URI_Map_Feature;
  4793. uriMapFt->callback_data = this;
  4794. uriMapFt->uri_to_id = carla_lv2_uri_to_id;
  4795. LV2_URID_Map* const uridMapFt = new LV2_URID_Map;
  4796. uridMapFt->handle = this;
  4797. uridMapFt->map = carla_lv2_urid_map;
  4798. LV2_URID_Unmap* const uridUnmapFt = new LV2_URID_Unmap;
  4799. uridUnmapFt->handle = this;
  4800. uridUnmapFt->unmap = carla_lv2_urid_unmap;
  4801. LV2_Worker_Schedule* const workerFt = new LV2_Worker_Schedule;
  4802. workerFt->handle = this;
  4803. workerFt->schedule_work = carla_lv2_worker_schedule;
  4804. LV2_Inline_Display* const inlineDisplay = new LV2_Inline_Display;
  4805. inlineDisplay->handle = this;
  4806. inlineDisplay->queue_draw = carla_lv2_inline_display_queue_draw;
  4807. LV2_Midnam* const midnam = new LV2_Midnam;
  4808. midnam->handle = this;
  4809. midnam->update = carla_lv2_midnam_update;
  4810. // ---------------------------------------------------------------
  4811. // initialize features (part 2)
  4812. for (uint32_t j=0; j < kFeatureCountPlugin; ++j)
  4813. fFeatures[j] = new LV2_Feature;
  4814. fFeatures[kFeatureIdBufSizeBounded]->URI = LV2_BUF_SIZE__boundedBlockLength;
  4815. fFeatures[kFeatureIdBufSizeBounded]->data = nullptr;
  4816. fFeatures[kFeatureIdBufSizeFixed]->URI = fNeedsFixedBuffers
  4817. ? LV2_BUF_SIZE__fixedBlockLength
  4818. : LV2_BUF_SIZE__boundedBlockLength;
  4819. fFeatures[kFeatureIdBufSizeFixed]->data = nullptr;
  4820. fFeatures[kFeatureIdBufSizePowerOf2]->URI = LV2_BUF_SIZE__powerOf2BlockLength;
  4821. fFeatures[kFeatureIdBufSizePowerOf2]->data = nullptr;
  4822. fFeatures[kFeatureIdEvent]->URI = LV2_EVENT_URI;
  4823. fFeatures[kFeatureIdEvent]->data = eventFt;
  4824. fFeatures[kFeatureIdHardRtCapable]->URI = LV2_CORE__hardRTCapable;
  4825. fFeatures[kFeatureIdHardRtCapable]->data = nullptr;
  4826. fFeatures[kFeatureIdInPlaceBroken]->URI = LV2_CORE__inPlaceBroken;
  4827. fFeatures[kFeatureIdInPlaceBroken]->data = nullptr;
  4828. fFeatures[kFeatureIdIsLive]->URI = LV2_CORE__isLive;
  4829. fFeatures[kFeatureIdIsLive]->data = nullptr;
  4830. fFeatures[kFeatureIdLogs]->URI = LV2_LOG__log;
  4831. fFeatures[kFeatureIdLogs]->data = logFt;
  4832. fFeatures[kFeatureIdOptions]->URI = LV2_OPTIONS__options;
  4833. fFeatures[kFeatureIdOptions]->data = fLv2Options.opts;
  4834. fFeatures[kFeatureIdPrograms]->URI = LV2_PROGRAMS__Host;
  4835. fFeatures[kFeatureIdPrograms]->data = programsFt;
  4836. fFeatures[kFeatureIdResizePort]->URI = LV2_RESIZE_PORT__resize;
  4837. fFeatures[kFeatureIdResizePort]->data = rsPortFt;
  4838. fFeatures[kFeatureIdRtMemPool]->URI = LV2_RTSAFE_MEMORY_POOL__Pool;
  4839. fFeatures[kFeatureIdRtMemPool]->data = rtMemPoolFt;
  4840. fFeatures[kFeatureIdRtMemPoolOld]->URI = LV2_RTSAFE_MEMORY_POOL_DEPRECATED_URI;
  4841. fFeatures[kFeatureIdRtMemPoolOld]->data = rtMemPoolOldFt;
  4842. fFeatures[kFeatureIdStateMakePath]->URI = LV2_STATE__makePath;
  4843. fFeatures[kFeatureIdStateMakePath]->data = stateMakePathFt;
  4844. fFeatures[kFeatureIdStateMapPath]->URI = LV2_STATE__mapPath;
  4845. fFeatures[kFeatureIdStateMapPath]->data = stateMapPathFt;
  4846. fFeatures[kFeatureIdStrictBounds]->URI = LV2_PORT_PROPS__supportsStrictBounds;
  4847. fFeatures[kFeatureIdStrictBounds]->data = nullptr;
  4848. fFeatures[kFeatureIdUriMap]->URI = LV2_URI_MAP_URI;
  4849. fFeatures[kFeatureIdUriMap]->data = uriMapFt;
  4850. fFeatures[kFeatureIdUridMap]->URI = LV2_URID__map;
  4851. fFeatures[kFeatureIdUridMap]->data = uridMapFt;
  4852. fFeatures[kFeatureIdUridUnmap]->URI = LV2_URID__unmap;
  4853. fFeatures[kFeatureIdUridUnmap]->data = uridUnmapFt;
  4854. fFeatures[kFeatureIdWorker]->URI = LV2_WORKER__schedule;
  4855. fFeatures[kFeatureIdWorker]->data = workerFt;
  4856. fFeatures[kFeatureIdInlineDisplay]->URI = LV2_INLINEDISPLAY__queue_draw;
  4857. fFeatures[kFeatureIdInlineDisplay]->data = inlineDisplay;
  4858. fFeatures[kFeatureIdMidnam]->URI = LV2_MIDNAM__update;
  4859. fFeatures[kFeatureIdMidnam]->data = midnam;
  4860. // ---------------------------------------------------------------
  4861. // initialize plugin
  4862. try {
  4863. fHandle = fDescriptor->instantiate(fDescriptor, pData->engine->getSampleRate(), fRdfDescriptor->Bundle, fFeatures);
  4864. } catch(...) {}
  4865. if (fHandle == nullptr)
  4866. {
  4867. pData->engine->setLastError("Plugin failed to initialize");
  4868. return false;
  4869. }
  4870. recheckExtensions();
  4871. // ---------------------------------------------------------------
  4872. // set options
  4873. pData->options = 0x0;
  4874. if (fLatencyIndex >= 0 || getMidiOutCount() != 0 || fNeedsFixedBuffers)
  4875. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  4876. else if (options & PLUGIN_OPTION_FIXED_BUFFERS)
  4877. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  4878. if (opts.forceStereo)
  4879. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  4880. else if (options & PLUGIN_OPTION_FORCE_STEREO)
  4881. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  4882. if (getMidiInCount() != 0)
  4883. {
  4884. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CONTROL_CHANGES))
  4885. pData->options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  4886. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CHANNEL_PRESSURE))
  4887. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  4888. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH))
  4889. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  4890. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PITCHBEND))
  4891. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  4892. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_ALL_SOUND_OFF))
  4893. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  4894. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PROGRAM_CHANGES))
  4895. pData->options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  4896. }
  4897. if (fExt.programs != nullptr && (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) == 0)
  4898. {
  4899. if (isPluginOptionEnabled(options, PLUGIN_OPTION_MAP_PROGRAM_CHANGES))
  4900. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  4901. }
  4902. // ---------------------------------------------------------------
  4903. // gui stuff
  4904. if (fRdfDescriptor->UICount != 0)
  4905. initUi();
  4906. return true;
  4907. }
  4908. // -------------------------------------------------------------------
  4909. void initUi()
  4910. {
  4911. // ---------------------------------------------------------------
  4912. // find the most appropriate ui
  4913. int eQt4, eQt5, eGtk2, eGtk3, eCocoa, eWindows, eX11, eMod, iCocoa, iWindows, iX11, iExt, iFinal;
  4914. eQt4 = eQt5 = eGtk2 = eGtk3 = eCocoa = eWindows = eX11 = eMod = iCocoa = iWindows = iX11 = iExt = iFinal = -1;
  4915. #if defined(LV2_UIS_ONLY_BRIDGES)
  4916. const bool preferUiBridges = true;
  4917. #elif defined(BUILD_BRIDGE)
  4918. const bool preferUiBridges = false;
  4919. #else
  4920. const bool preferUiBridges = pData->engine->getOptions().preferUiBridges;
  4921. #endif
  4922. bool hasShowInterface = false;
  4923. for (uint32_t i=0; i < fRdfDescriptor->UICount; ++i)
  4924. {
  4925. CARLA_SAFE_ASSERT_CONTINUE(fRdfDescriptor->UIs[i].URI != nullptr);
  4926. const int ii(static_cast<int>(i));
  4927. switch (fRdfDescriptor->UIs[i].Type)
  4928. {
  4929. case LV2_UI_QT4:
  4930. if (isUiBridgeable(i))
  4931. eQt4 = ii;
  4932. break;
  4933. case LV2_UI_QT5:
  4934. if (isUiBridgeable(i))
  4935. eQt5 = ii;
  4936. break;
  4937. case LV2_UI_GTK2:
  4938. if (isUiBridgeable(i))
  4939. eGtk2 = ii;
  4940. break;
  4941. case LV2_UI_GTK3:
  4942. if (isUiBridgeable(i))
  4943. eGtk3 = ii;
  4944. break;
  4945. #ifdef CARLA_OS_MAC
  4946. case LV2_UI_COCOA:
  4947. if (isUiBridgeable(i) && preferUiBridges)
  4948. eCocoa = ii;
  4949. iCocoa = ii;
  4950. break;
  4951. #endif
  4952. #ifdef CARLA_OS_WIN
  4953. case LV2_UI_WINDOWS:
  4954. if (isUiBridgeable(i) && preferUiBridges)
  4955. eWindows = ii;
  4956. iWindows = ii;
  4957. break;
  4958. #endif
  4959. case LV2_UI_X11:
  4960. if (isUiBridgeable(i) && preferUiBridges)
  4961. eX11 = ii;
  4962. iX11 = ii;
  4963. break;
  4964. case LV2_UI_EXTERNAL:
  4965. case LV2_UI_OLD_EXTERNAL:
  4966. iExt = ii;
  4967. break;
  4968. case LV2_UI_MOD:
  4969. eMod = ii;
  4970. break;
  4971. default:
  4972. break;
  4973. }
  4974. }
  4975. /**/ if (eQt4 >= 0)
  4976. iFinal = eQt4;
  4977. else if (eQt5 >= 0)
  4978. iFinal = eQt5;
  4979. else if (eGtk2 >= 0)
  4980. iFinal = eGtk2;
  4981. else if (eGtk3 >= 0)
  4982. iFinal = eGtk3;
  4983. #ifdef CARLA_OS_MAC
  4984. else if (eCocoa >= 0)
  4985. iFinal = eCocoa;
  4986. #endif
  4987. #ifdef CARLA_OS_WIN
  4988. else if (eWindows >= 0)
  4989. iFinal = eWindows;
  4990. #endif
  4991. #ifdef HAVE_X11
  4992. else if (eX11 >= 0)
  4993. iFinal = eX11;
  4994. #endif
  4995. #ifndef LV2_UIS_ONLY_BRIDGES
  4996. # ifdef CARLA_OS_MAC
  4997. else if (iCocoa >= 0)
  4998. iFinal = iCocoa;
  4999. # endif
  5000. # ifdef CARLA_OS_WIN
  5001. else if (iWindows >= 0)
  5002. iFinal = iWindows;
  5003. # endif
  5004. # ifdef HAVE_X11
  5005. else if (iX11 >= 0)
  5006. iFinal = iX11;
  5007. # endif
  5008. #endif
  5009. else if (iExt >= 0)
  5010. iFinal = iExt;
  5011. #ifndef BUILD_BRIDGE
  5012. if (iFinal < 0)
  5013. #endif
  5014. {
  5015. // no suitable UI found, see if there's one which supports ui:showInterface
  5016. for (uint32_t i=0; i < fRdfDescriptor->UICount && ! hasShowInterface; ++i)
  5017. {
  5018. LV2_RDF_UI* const ui(&fRdfDescriptor->UIs[i]);
  5019. for (uint32_t j=0; j < ui->ExtensionCount; ++j)
  5020. {
  5021. CARLA_SAFE_ASSERT_CONTINUE(ui->Extensions[j] != nullptr);
  5022. if (std::strcmp(ui->Extensions[j], LV2_UI__showInterface) != 0)
  5023. continue;
  5024. iFinal = static_cast<int>(i);
  5025. hasShowInterface = true;
  5026. break;
  5027. }
  5028. }
  5029. if (iFinal < 0)
  5030. {
  5031. if (eMod < 0)
  5032. {
  5033. carla_stderr("Failed to find an appropriate LV2 UI for this plugin");
  5034. return;
  5035. }
  5036. // use MODGUI as last resort
  5037. iFinal = eMod;
  5038. }
  5039. }
  5040. fUI.rdfDescriptor = &fRdfDescriptor->UIs[iFinal];
  5041. // ---------------------------------------------------------------
  5042. // check supported ui features
  5043. bool canContinue = true;
  5044. bool canDelete = true;
  5045. for (uint32_t i=0; i < fUI.rdfDescriptor->FeatureCount; ++i)
  5046. {
  5047. const char* const uri(fUI.rdfDescriptor->Features[i].URI);
  5048. CARLA_SAFE_ASSERT_CONTINUE(uri != nullptr && uri[0] != '\0');
  5049. if (! is_lv2_ui_feature_supported(uri))
  5050. {
  5051. if (fUI.rdfDescriptor->Features[i].Required)
  5052. {
  5053. carla_stderr("Plugin UI requires a feature that is not supported:\n%s", uri);
  5054. canContinue = false;
  5055. break;
  5056. }
  5057. carla_stderr("Plugin UI wants a feature that is not supported (ignored):\n%s", uri);
  5058. }
  5059. if (std::strcmp(uri, LV2_UI__makeResident) == 0 || std::strcmp(uri, LV2_UI__makeSONameResident) == 0)
  5060. canDelete = false;
  5061. }
  5062. if (! canContinue)
  5063. {
  5064. fUI.rdfDescriptor = nullptr;
  5065. return;
  5066. }
  5067. // ---------------------------------------------------------------
  5068. // initialize ui according to type
  5069. const LV2_Property uiType(fUI.rdfDescriptor->Type);
  5070. if (
  5071. (iFinal == eQt4 ||
  5072. iFinal == eQt5 ||
  5073. iFinal == eGtk2 ||
  5074. iFinal == eGtk3 ||
  5075. iFinal == eCocoa ||
  5076. iFinal == eWindows ||
  5077. iFinal == eX11 ||
  5078. iFinal == eMod)
  5079. #ifdef BUILD_BRIDGE
  5080. && ! hasShowInterface
  5081. #endif
  5082. )
  5083. {
  5084. // -----------------------------------------------------------
  5085. // initialize ui-bridge
  5086. if (const char* const bridgeBinary = getUiBridgeBinary(uiType))
  5087. {
  5088. carla_stdout("Will use UI-Bridge for '%s', binary: \"%s\"", pData->name, bridgeBinary);
  5089. CarlaString guiTitle(pData->name);
  5090. guiTitle += " (GUI)";
  5091. fLv2Options.windowTitle = guiTitle.dup();
  5092. fUI.type = UI::TYPE_BRIDGE;
  5093. fPipeServer.setData(bridgeBinary, fRdfDescriptor->URI, fUI.rdfDescriptor->URI);
  5094. delete[] bridgeBinary;
  5095. return;
  5096. }
  5097. if (iFinal == eQt4 || iFinal == eQt5 || iFinal == eGtk2 || iFinal == eGtk3 || iFinal == eMod)
  5098. {
  5099. carla_stderr2("Failed to find UI bridge binary for '%s', cannot use UI", pData->name);
  5100. fUI.rdfDescriptor = nullptr;
  5101. return;
  5102. }
  5103. }
  5104. #ifdef LV2_UIS_ONLY_BRIDGES
  5105. carla_stderr2("Failed to get an UI working, canBridge:%s", bool2str(isUiBridgeable(static_cast<uint32_t>(iFinal))));
  5106. fUI.rdfDescriptor = nullptr;
  5107. return;
  5108. #endif
  5109. // ---------------------------------------------------------------
  5110. // open UI DLL
  5111. if (! pData->uiLibOpen(fUI.rdfDescriptor->Binary, canDelete))
  5112. {
  5113. carla_stderr2("Could not load UI library, error was:\n%s", pData->libError(fUI.rdfDescriptor->Binary));
  5114. fUI.rdfDescriptor = nullptr;
  5115. return;
  5116. }
  5117. // ---------------------------------------------------------------
  5118. // get UI DLL main entry
  5119. LV2UI_DescriptorFunction uiDescFn = pData->uiLibSymbol<LV2UI_DescriptorFunction>("lv2ui_descriptor");
  5120. if (uiDescFn == nullptr)
  5121. {
  5122. carla_stderr2("Could not find the LV2UI Descriptor in the UI library");
  5123. pData->uiLibClose();
  5124. fUI.rdfDescriptor = nullptr;
  5125. return;
  5126. }
  5127. // ---------------------------------------------------------------
  5128. // get UI descriptor that matches UI URI
  5129. uint32_t i = 0;
  5130. while ((fUI.descriptor = uiDescFn(i++)))
  5131. {
  5132. if (std::strcmp(fUI.descriptor->URI, fUI.rdfDescriptor->URI) == 0)
  5133. break;
  5134. }
  5135. if (fUI.descriptor == nullptr)
  5136. {
  5137. carla_stderr2("Could not find the requested GUI in the plugin UI library");
  5138. pData->uiLibClose();
  5139. fUI.rdfDescriptor = nullptr;
  5140. return;
  5141. }
  5142. // ---------------------------------------------------------------
  5143. // check if ui is usable
  5144. switch (uiType)
  5145. {
  5146. case LV2_UI_NONE:
  5147. carla_stdout("Will use LV2 Show Interface for '%s'", pData->name);
  5148. fUI.type = UI::TYPE_EMBED;
  5149. break;
  5150. case LV2_UI_QT4:
  5151. carla_stdout("Will use LV2 Qt4 UI for '%s', NOT!", pData->name);
  5152. fUI.type = UI::TYPE_EMBED;
  5153. break;
  5154. case LV2_UI_QT5:
  5155. carla_stdout("Will use LV2 Qt5 UI for '%s', NOT!", pData->name);
  5156. fUI.type = UI::TYPE_EMBED;
  5157. break;
  5158. case LV2_UI_GTK2:
  5159. carla_stdout("Will use LV2 Gtk2 UI for '%s', NOT!", pData->name);
  5160. fUI.type = UI::TYPE_EMBED;
  5161. break;
  5162. case LV2_UI_GTK3:
  5163. carla_stdout("Will use LV2 Gtk3 UI for '%s', NOT!", pData->name);
  5164. fUI.type = UI::TYPE_EMBED;
  5165. break;
  5166. #ifdef CARLA_OS_MAC
  5167. case LV2_UI_COCOA:
  5168. carla_stdout("Will use LV2 Cocoa UI for '%s'", pData->name);
  5169. fUI.type = UI::TYPE_EMBED;
  5170. break;
  5171. #endif
  5172. #ifdef CARLA_OS_WIN
  5173. case LV2_UI_WINDOWS:
  5174. carla_stdout("Will use LV2 Windows UI for '%s'", pData->name);
  5175. fUI.type = UI::TYPE_EMBED;
  5176. break;
  5177. #endif
  5178. case LV2_UI_X11:
  5179. #ifdef HAVE_X11
  5180. carla_stdout("Will use LV2 X11 UI for '%s'", pData->name);
  5181. #else
  5182. carla_stdout("Will use LV2 X11 UI for '%s', NOT!", pData->name);
  5183. #endif
  5184. fUI.type = UI::TYPE_EMBED;
  5185. break;
  5186. case LV2_UI_EXTERNAL:
  5187. case LV2_UI_OLD_EXTERNAL:
  5188. carla_stdout("Will use LV2 External UI for '%s'", pData->name);
  5189. fUI.type = UI::TYPE_EXTERNAL;
  5190. break;
  5191. }
  5192. if (fUI.type == UI::TYPE_NULL)
  5193. {
  5194. pData->uiLibClose();
  5195. fUI.descriptor = nullptr;
  5196. fUI.rdfDescriptor = nullptr;
  5197. return;
  5198. }
  5199. // ---------------------------------------------------------------
  5200. // initialize ui data
  5201. CarlaString guiTitle(pData->name);
  5202. guiTitle += " (GUI)";
  5203. fLv2Options.windowTitle = guiTitle.dup();
  5204. fLv2Options.opts[CarlaPluginLV2Options::WindowTitle].size = (uint32_t)std::strlen(fLv2Options.windowTitle);
  5205. fLv2Options.opts[CarlaPluginLV2Options::WindowTitle].value = fLv2Options.windowTitle;
  5206. // ---------------------------------------------------------------
  5207. // initialize ui features (part 1)
  5208. LV2_Extension_Data_Feature* const uiDataFt = new LV2_Extension_Data_Feature;
  5209. uiDataFt->data_access = fDescriptor->extension_data;
  5210. LV2UI_Port_Map* const uiPortMapFt = new LV2UI_Port_Map;
  5211. uiPortMapFt->handle = this;
  5212. uiPortMapFt->port_index = carla_lv2_ui_port_map;
  5213. LV2UI_Resize* const uiResizeFt = new LV2UI_Resize;
  5214. uiResizeFt->handle = this;
  5215. uiResizeFt->ui_resize = carla_lv2_ui_resize;
  5216. LV2UI_Touch* const uiTouchFt = new LV2UI_Touch;
  5217. uiTouchFt->handle = this;
  5218. uiTouchFt->touch = carla_lv2_ui_touch;
  5219. LV2_External_UI_Host* const uiExternalHostFt = new LV2_External_UI_Host;
  5220. uiExternalHostFt->ui_closed = carla_lv2_external_ui_closed;
  5221. uiExternalHostFt->plugin_human_id = fLv2Options.windowTitle;
  5222. // ---------------------------------------------------------------
  5223. // initialize ui features (part 2)
  5224. for (uint32_t j=kFeatureCountPlugin; j < kFeatureCountAll; ++j)
  5225. fFeatures[j] = new LV2_Feature;
  5226. fFeatures[kFeatureIdUiDataAccess]->URI = LV2_DATA_ACCESS_URI;
  5227. fFeatures[kFeatureIdUiDataAccess]->data = uiDataFt;
  5228. fFeatures[kFeatureIdUiInstanceAccess]->URI = LV2_INSTANCE_ACCESS_URI;
  5229. fFeatures[kFeatureIdUiInstanceAccess]->data = fHandle;
  5230. fFeatures[kFeatureIdUiIdleInterface]->URI = LV2_UI__idleInterface;
  5231. fFeatures[kFeatureIdUiIdleInterface]->data = nullptr;
  5232. fFeatures[kFeatureIdUiFixedSize]->URI = LV2_UI__fixedSize;
  5233. fFeatures[kFeatureIdUiFixedSize]->data = nullptr;
  5234. fFeatures[kFeatureIdUiMakeResident]->URI = LV2_UI__makeResident;
  5235. fFeatures[kFeatureIdUiMakeResident]->data = nullptr;
  5236. fFeatures[kFeatureIdUiMakeResident2]->URI = LV2_UI__makeSONameResident;
  5237. fFeatures[kFeatureIdUiMakeResident2]->data = nullptr;
  5238. fFeatures[kFeatureIdUiNoUserResize]->URI = LV2_UI__noUserResize;
  5239. fFeatures[kFeatureIdUiNoUserResize]->data = nullptr;
  5240. fFeatures[kFeatureIdUiParent]->URI = LV2_UI__parent;
  5241. fFeatures[kFeatureIdUiParent]->data = nullptr;
  5242. fFeatures[kFeatureIdUiPortMap]->URI = LV2_UI__portMap;
  5243. fFeatures[kFeatureIdUiPortMap]->data = uiPortMapFt;
  5244. fFeatures[kFeatureIdUiPortSubscribe]->URI = LV2_UI__portSubscribe;
  5245. fFeatures[kFeatureIdUiPortSubscribe]->data = nullptr;
  5246. fFeatures[kFeatureIdUiResize]->URI = LV2_UI__resize;
  5247. fFeatures[kFeatureIdUiResize]->data = uiResizeFt;
  5248. fFeatures[kFeatureIdUiTouch]->URI = LV2_UI__touch;
  5249. fFeatures[kFeatureIdUiTouch]->data = uiTouchFt;
  5250. fFeatures[kFeatureIdExternalUi]->URI = LV2_EXTERNAL_UI__Host;
  5251. fFeatures[kFeatureIdExternalUi]->data = uiExternalHostFt;
  5252. fFeatures[kFeatureIdExternalUiOld]->URI = LV2_EXTERNAL_UI_DEPRECATED_URI;
  5253. fFeatures[kFeatureIdExternalUiOld]->data = uiExternalHostFt;
  5254. // ---------------------------------------------------------------
  5255. // initialize ui extensions
  5256. if (fUI.descriptor->extension_data == nullptr)
  5257. return;
  5258. fExt.uiidle = (const LV2UI_Idle_Interface*)fUI.descriptor->extension_data(LV2_UI__idleInterface);
  5259. fExt.uishow = (const LV2UI_Show_Interface*)fUI.descriptor->extension_data(LV2_UI__showInterface);
  5260. fExt.uiresize = (const LV2UI_Resize*)fUI.descriptor->extension_data(LV2_UI__resize);
  5261. fExt.uiprograms = (const LV2_Programs_UI_Interface*)fUI.descriptor->extension_data(LV2_PROGRAMS__UIInterface);
  5262. // check if invalid
  5263. if (fExt.uiidle != nullptr && fExt.uiidle->idle == nullptr)
  5264. fExt.uiidle = nullptr;
  5265. if (fExt.uishow != nullptr && (fExt.uishow->show == nullptr || fExt.uishow->hide == nullptr))
  5266. fExt.uishow = nullptr;
  5267. if (fExt.uiresize != nullptr && fExt.uiresize->ui_resize == nullptr)
  5268. fExt.uiresize = nullptr;
  5269. if (fExt.uiprograms != nullptr && fExt.uiprograms->select_program == nullptr)
  5270. fExt.uiprograms = nullptr;
  5271. // don't use uiidle if external
  5272. if (fUI.type == UI::TYPE_EXTERNAL)
  5273. fExt.uiidle = nullptr;
  5274. }
  5275. // -------------------------------------------------------------------
  5276. void handleTransferAtom(const uint32_t portIndex, const LV2_Atom* const atom)
  5277. {
  5278. CARLA_SAFE_ASSERT_RETURN(atom != nullptr,);
  5279. carla_debug("CarlaPluginLV2::handleTransferAtom(%i, %p)", portIndex, atom);
  5280. fAtomBufferEvIn.put(atom, portIndex);
  5281. }
  5282. void handleUridMap(const LV2_URID urid, const char* const uri)
  5283. {
  5284. CARLA_SAFE_ASSERT_RETURN(urid != kUridNull,);
  5285. CARLA_SAFE_ASSERT_RETURN(uri != nullptr && uri[0] != '\0',);
  5286. carla_debug("CarlaPluginLV2::handleUridMap(%i v " P_SIZE ", \"%s\")", urid, fCustomURIDs.size()-1, uri);
  5287. const std::size_t uriCount(fCustomURIDs.size());
  5288. if (urid < uriCount)
  5289. {
  5290. const char* const ourURI(carla_lv2_urid_unmap(this, urid));
  5291. CARLA_SAFE_ASSERT_RETURN(ourURI != nullptr && ourURI != kUnmapFallback,);
  5292. if (std::strcmp(ourURI, uri) != 0)
  5293. {
  5294. carla_stderr2("PLUGIN :: wrong URI '%s' vs '%s'", ourURI, uri);
  5295. }
  5296. }
  5297. else
  5298. {
  5299. CARLA_SAFE_ASSERT_RETURN(urid == uriCount,);
  5300. fCustomURIDs.push_back(uri);
  5301. }
  5302. }
  5303. // -------------------------------------------------------------------
  5304. private:
  5305. LV2_Handle fHandle;
  5306. LV2_Handle fHandle2;
  5307. LV2_Feature* fFeatures[kFeatureCountAll+1];
  5308. const LV2_Descriptor* fDescriptor;
  5309. const LV2_RDF_Descriptor* fRdfDescriptor;
  5310. float** fAudioInBuffers;
  5311. float** fAudioOutBuffers;
  5312. float** fCvInBuffers;
  5313. float** fCvOutBuffers;
  5314. float* fParamBuffers;
  5315. bool fNeedsFixedBuffers;
  5316. bool fNeedsUiClose;
  5317. bool fInlineDisplayNeedsRedraw;
  5318. int64_t fInlineDisplayLastRedrawTime;
  5319. int32_t fLatencyIndex; // -1 if invalid
  5320. int fStrictBounds; // -1 unsupported, 0 optional, 1 required
  5321. Lv2AtomRingBuffer fAtomBufferEvIn;
  5322. Lv2AtomRingBuffer fAtomBufferUiOut;
  5323. Lv2AtomRingBuffer fAtomBufferWorkerIn;
  5324. Lv2AtomRingBuffer fAtomBufferWorkerResp;
  5325. LV2_Atom_Forge fAtomForge;
  5326. uint8_t* fAtomBufferUiOutTmpData;
  5327. uint8_t* fAtomBufferWorkerInTmpData;
  5328. CarlaPluginLV2EventData fEventsIn;
  5329. CarlaPluginLV2EventData fEventsOut;
  5330. CarlaPluginLV2Options fLv2Options;
  5331. CarlaPipeServerLV2 fPipeServer;
  5332. std::vector<std::string> fCustomURIDs;
  5333. bool fFirstActive; // first process() call after activate()
  5334. void* fLastStateChunk;
  5335. EngineTimeInfo fLastTimeInfo;
  5336. // if plugin provides path parameter, use it as fake "gui"
  5337. CarlaString fFilePathURI;
  5338. struct Extensions {
  5339. const LV2_Options_Interface* options;
  5340. const LV2_State_Interface* state;
  5341. const LV2_Worker_Interface* worker;
  5342. const LV2_Inline_Display_Interface* inlineDisplay;
  5343. const LV2_Midnam_Interface* midnam;
  5344. const LV2_Programs_Interface* programs;
  5345. const LV2UI_Idle_Interface* uiidle;
  5346. const LV2UI_Show_Interface* uishow;
  5347. const LV2UI_Resize* uiresize;
  5348. const LV2_Programs_UI_Interface* uiprograms;
  5349. Extensions()
  5350. : options(nullptr),
  5351. state(nullptr),
  5352. worker(nullptr),
  5353. inlineDisplay(nullptr),
  5354. midnam(nullptr),
  5355. programs(nullptr),
  5356. uiidle(nullptr),
  5357. uishow(nullptr),
  5358. uiresize(nullptr),
  5359. uiprograms(nullptr) {}
  5360. CARLA_DECLARE_NON_COPY_STRUCT(Extensions);
  5361. } fExt;
  5362. struct UI {
  5363. enum Type {
  5364. TYPE_NULL = 0,
  5365. TYPE_BRIDGE,
  5366. TYPE_EMBED,
  5367. TYPE_EXTERNAL
  5368. };
  5369. Type type;
  5370. LV2UI_Handle handle;
  5371. LV2UI_Widget widget;
  5372. const LV2UI_Descriptor* descriptor;
  5373. const LV2_RDF_UI* rdfDescriptor;
  5374. CarlaPluginUI* window;
  5375. UI()
  5376. : type(TYPE_NULL),
  5377. handle(nullptr),
  5378. widget(nullptr),
  5379. descriptor(nullptr),
  5380. rdfDescriptor(nullptr),
  5381. window(nullptr) {}
  5382. ~UI()
  5383. {
  5384. CARLA_SAFE_ASSERT(handle == nullptr);
  5385. CARLA_SAFE_ASSERT(widget == nullptr);
  5386. CARLA_SAFE_ASSERT(descriptor == nullptr);
  5387. CARLA_SAFE_ASSERT(rdfDescriptor == nullptr);
  5388. CARLA_SAFE_ASSERT(window == nullptr);
  5389. }
  5390. CARLA_DECLARE_NON_COPY_STRUCT(UI);
  5391. } fUI;
  5392. // -------------------------------------------------------------------
  5393. // Event Feature
  5394. static uint32_t carla_lv2_event_ref(LV2_Event_Callback_Data callback_data, LV2_Event* event)
  5395. {
  5396. CARLA_SAFE_ASSERT_RETURN(callback_data != nullptr, 0);
  5397. CARLA_SAFE_ASSERT_RETURN(event != nullptr, 0);
  5398. carla_debug("carla_lv2_event_ref(%p, %p)", callback_data, event);
  5399. return 0;
  5400. }
  5401. static uint32_t carla_lv2_event_unref(LV2_Event_Callback_Data callback_data, LV2_Event* event)
  5402. {
  5403. CARLA_SAFE_ASSERT_RETURN(callback_data != nullptr, 0);
  5404. CARLA_SAFE_ASSERT_RETURN(event != nullptr, 0);
  5405. carla_debug("carla_lv2_event_unref(%p, %p)", callback_data, event);
  5406. return 0;
  5407. }
  5408. // -------------------------------------------------------------------
  5409. // Logs Feature
  5410. static int carla_lv2_log_printf(LV2_Log_Handle handle, LV2_URID type, const char* fmt, ...)
  5411. {
  5412. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, 0);
  5413. CARLA_SAFE_ASSERT_RETURN(type != kUridNull, 0);
  5414. CARLA_SAFE_ASSERT_RETURN(fmt != nullptr, 0);
  5415. #ifndef DEBUG
  5416. if (type == kUridLogTrace)
  5417. return 0;
  5418. #endif
  5419. va_list args;
  5420. va_start(args, fmt);
  5421. const int ret(carla_lv2_log_vprintf(handle, type, fmt, args));
  5422. va_end(args);
  5423. return ret;
  5424. }
  5425. static int carla_lv2_log_vprintf(LV2_Log_Handle handle, LV2_URID type, const char* fmt, va_list ap)
  5426. {
  5427. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, 0);
  5428. CARLA_SAFE_ASSERT_RETURN(type != kUridNull, 0);
  5429. CARLA_SAFE_ASSERT_RETURN(fmt != nullptr, 0);
  5430. int ret = 0;
  5431. switch (type)
  5432. {
  5433. case kUridLogError:
  5434. std::fprintf(stderr, "\x1b[31m");
  5435. ret = std::vfprintf(stderr, fmt, ap);
  5436. std::fprintf(stderr, "\x1b[0m");
  5437. break;
  5438. case kUridLogNote:
  5439. ret = std::vfprintf(stdout, fmt, ap);
  5440. break;
  5441. case kUridLogTrace:
  5442. #ifdef DEBUG
  5443. std::fprintf(stdout, "\x1b[30;1m");
  5444. ret = std::vfprintf(stdout, fmt, ap);
  5445. std::fprintf(stdout, "\x1b[0m");
  5446. #endif
  5447. break;
  5448. case kUridLogWarning:
  5449. ret = std::vfprintf(stderr, fmt, ap);
  5450. break;
  5451. default:
  5452. break;
  5453. }
  5454. return ret;
  5455. }
  5456. // -------------------------------------------------------------------
  5457. // Programs Feature
  5458. static void carla_lv2_program_changed(LV2_Programs_Handle handle, int32_t index)
  5459. {
  5460. CARLA_SAFE_ASSERT_RETURN(handle != nullptr,);
  5461. carla_debug("carla_lv2_program_changed(%p, %i)", handle, index);
  5462. ((CarlaPluginLV2*)handle)->handleProgramChanged(index);
  5463. }
  5464. // -------------------------------------------------------------------
  5465. // Resize Port Feature
  5466. static LV2_Resize_Port_Status carla_lv2_resize_port(LV2_Resize_Port_Feature_Data data, uint32_t index, size_t size)
  5467. {
  5468. CARLA_SAFE_ASSERT_RETURN(data != nullptr, LV2_RESIZE_PORT_ERR_UNKNOWN);
  5469. carla_debug("carla_lv2_program_changed(%p, %i, " P_SIZE ")", data, index, size);
  5470. return ((CarlaPluginLV2*)data)->handleResizePort(index, size);
  5471. }
  5472. // -------------------------------------------------------------------
  5473. // State Feature
  5474. static char* carla_lv2_state_make_path(LV2_State_Make_Path_Handle handle, const char* path)
  5475. {
  5476. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, nullptr);
  5477. CARLA_SAFE_ASSERT_RETURN(path != nullptr && path[0] != '\0', nullptr);
  5478. carla_debug("carla_lv2_state_make_path(%p, \"%s\")", handle, path);
  5479. File file;
  5480. if (File::isAbsolutePath(path))
  5481. file = File(path);
  5482. else
  5483. file = File::getCurrentWorkingDirectory().getChildFile(path);
  5484. file.getParentDirectory().createDirectory();
  5485. return strdup(file.getFullPathName().toRawUTF8());
  5486. }
  5487. static char* carla_lv2_state_map_abstract_path(LV2_State_Map_Path_Handle handle, const char* absolute_path)
  5488. {
  5489. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, strdup(""));
  5490. CARLA_SAFE_ASSERT_RETURN(absolute_path != nullptr && absolute_path[0] != '\0', strdup(""));
  5491. carla_debug("carla_lv2_state_map_abstract_path(%p, \"%s\")", handle, absolute_path);
  5492. // may already be an abstract path
  5493. if (! File::isAbsolutePath(absolute_path))
  5494. return strdup(absolute_path);
  5495. return strdup(File(absolute_path).getRelativePathFrom(File::getCurrentWorkingDirectory()).toRawUTF8());
  5496. }
  5497. static char* carla_lv2_state_map_absolute_path(LV2_State_Map_Path_Handle handle, const char* abstract_path)
  5498. {
  5499. const char* const cwd(File::getCurrentWorkingDirectory().getFullPathName().toRawUTF8());
  5500. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, strdup(cwd));
  5501. CARLA_SAFE_ASSERT_RETURN(abstract_path != nullptr && abstract_path[0] != '\0', strdup(cwd));
  5502. carla_debug("carla_lv2_state_map_absolute_path(%p, \"%s\")", handle, abstract_path);
  5503. // may already be an absolute path
  5504. if (File::isAbsolutePath(abstract_path))
  5505. return strdup(abstract_path);
  5506. return strdup(File::getCurrentWorkingDirectory().getChildFile(abstract_path).getFullPathName().toRawUTF8());
  5507. }
  5508. static LV2_State_Status carla_lv2_state_store(LV2_State_Handle handle, uint32_t key, const void* value, size_t size, uint32_t type, uint32_t flags)
  5509. {
  5510. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, LV2_STATE_ERR_UNKNOWN);
  5511. carla_debug("carla_lv2_state_store(%p, %i, %p, " P_SIZE ", %i, %i)", handle, key, value, size, type, flags);
  5512. return ((CarlaPluginLV2*)handle)->handleStateStore(key, value, size, type, flags);
  5513. }
  5514. static const void* carla_lv2_state_retrieve(LV2_State_Handle handle, uint32_t key, size_t* size, uint32_t* type, uint32_t* flags)
  5515. {
  5516. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, nullptr);
  5517. carla_debug("carla_lv2_state_retrieve(%p, %i, %p, %p, %p)", handle, key, size, type, flags);
  5518. return ((CarlaPluginLV2*)handle)->handleStateRetrieve(key, size, type, flags);
  5519. }
  5520. // -------------------------------------------------------------------
  5521. // URI-Map Feature
  5522. static uint32_t carla_lv2_uri_to_id(LV2_URI_Map_Callback_Data data, const char* map, const char* uri)
  5523. {
  5524. carla_debug("carla_lv2_uri_to_id(%p, \"%s\", \"%s\")", data, map, uri);
  5525. return carla_lv2_urid_map((LV2_URID_Map_Handle*)data, uri);
  5526. // unused
  5527. (void)map;
  5528. }
  5529. // -------------------------------------------------------------------
  5530. // URID Feature
  5531. static LV2_URID carla_lv2_urid_map(LV2_URID_Map_Handle handle, const char* uri)
  5532. {
  5533. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, kUridNull);
  5534. CARLA_SAFE_ASSERT_RETURN(uri != nullptr && uri[0] != '\0', kUridNull);
  5535. carla_debug("carla_lv2_urid_map(%p, \"%s\")", handle, uri);
  5536. // Atom types
  5537. if (std::strcmp(uri, LV2_ATOM__Blank) == 0)
  5538. return kUridAtomBlank;
  5539. if (std::strcmp(uri, LV2_ATOM__Bool) == 0)
  5540. return kUridAtomBool;
  5541. if (std::strcmp(uri, LV2_ATOM__Chunk) == 0)
  5542. return kUridAtomChunk;
  5543. if (std::strcmp(uri, LV2_ATOM__Double) == 0)
  5544. return kUridAtomDouble;
  5545. if (std::strcmp(uri, LV2_ATOM__Event) == 0)
  5546. return kUridAtomEvent;
  5547. if (std::strcmp(uri, LV2_ATOM__Float) == 0)
  5548. return kUridAtomFloat;
  5549. if (std::strcmp(uri, LV2_ATOM__Int) == 0)
  5550. return kUridAtomInt;
  5551. if (std::strcmp(uri, LV2_ATOM__Literal) == 0)
  5552. return kUridAtomLiteral;
  5553. if (std::strcmp(uri, LV2_ATOM__Long) == 0)
  5554. return kUridAtomLong;
  5555. if (std::strcmp(uri, LV2_ATOM__Number) == 0)
  5556. return kUridAtomNumber;
  5557. if (std::strcmp(uri, LV2_ATOM__Object) == 0)
  5558. return kUridAtomObject;
  5559. if (std::strcmp(uri, LV2_ATOM__Path) == 0)
  5560. return kUridAtomPath;
  5561. if (std::strcmp(uri, LV2_ATOM__Property) == 0)
  5562. return kUridAtomProperty;
  5563. if (std::strcmp(uri, LV2_ATOM__Resource) == 0)
  5564. return kUridAtomResource;
  5565. if (std::strcmp(uri, LV2_ATOM__Sequence) == 0)
  5566. return kUridAtomSequence;
  5567. if (std::strcmp(uri, LV2_ATOM__Sound) == 0)
  5568. return kUridAtomSound;
  5569. if (std::strcmp(uri, LV2_ATOM__String) == 0)
  5570. return kUridAtomString;
  5571. if (std::strcmp(uri, LV2_ATOM__Tuple) == 0)
  5572. return kUridAtomTuple;
  5573. if (std::strcmp(uri, LV2_ATOM__URI) == 0)
  5574. return kUridAtomURI;
  5575. if (std::strcmp(uri, LV2_ATOM__URID) == 0)
  5576. return kUridAtomURID;
  5577. if (std::strcmp(uri, LV2_ATOM__Vector) == 0)
  5578. return kUridAtomVector;
  5579. if (std::strcmp(uri, LV2_ATOM__atomTransfer) == 0)
  5580. return kUridAtomTransferAtom;
  5581. if (std::strcmp(uri, LV2_ATOM__eventTransfer) == 0)
  5582. return kUridAtomTransferEvent;
  5583. // BufSize types
  5584. if (std::strcmp(uri, LV2_BUF_SIZE__maxBlockLength) == 0)
  5585. return kUridBufMaxLength;
  5586. if (std::strcmp(uri, LV2_BUF_SIZE__minBlockLength) == 0)
  5587. return kUridBufMinLength;
  5588. if (std::strcmp(uri, LV2_BUF_SIZE__nominalBlockLength) == 0)
  5589. return kUridBufNominalLength;
  5590. if (std::strcmp(uri, LV2_BUF_SIZE__sequenceSize) == 0)
  5591. return kUridBufSequenceSize;
  5592. // Log types
  5593. if (std::strcmp(uri, LV2_LOG__Error) == 0)
  5594. return kUridLogError;
  5595. if (std::strcmp(uri, LV2_LOG__Note) == 0)
  5596. return kUridLogNote;
  5597. if (std::strcmp(uri, LV2_LOG__Trace) == 0)
  5598. return kUridLogTrace;
  5599. if (std::strcmp(uri, LV2_LOG__Warning) == 0)
  5600. return kUridLogWarning;
  5601. // Patch types
  5602. if (std::strcmp(uri, LV2_PATCH__Set) == 0)
  5603. return kUridPatchSet;
  5604. if (std::strcmp(uri, LV2_PATCH__property) == 0)
  5605. return kUridPatchPoperty;
  5606. if (std::strcmp(uri, LV2_PATCH__value) == 0)
  5607. return kUridPatchValue;
  5608. // Time types
  5609. if (std::strcmp(uri, LV2_TIME__Position) == 0)
  5610. return kUridTimePosition;
  5611. if (std::strcmp(uri, LV2_TIME__bar) == 0)
  5612. return kUridTimeBar;
  5613. if (std::strcmp(uri, LV2_TIME__barBeat) == 0)
  5614. return kUridTimeBarBeat;
  5615. if (std::strcmp(uri, LV2_TIME__beat) == 0)
  5616. return kUridTimeBeat;
  5617. if (std::strcmp(uri, LV2_TIME__beatUnit) == 0)
  5618. return kUridTimeBeatUnit;
  5619. if (std::strcmp(uri, LV2_TIME__beatsPerBar) == 0)
  5620. return kUridTimeBeatsPerBar;
  5621. if (std::strcmp(uri, LV2_TIME__beatsPerMinute) == 0)
  5622. return kUridTimeBeatsPerMinute;
  5623. if (std::strcmp(uri, LV2_TIME__frame) == 0)
  5624. return kUridTimeFrame;
  5625. if (std::strcmp(uri, LV2_TIME__framesPerSecond) == 0)
  5626. return kUridTimeFramesPerSecond;
  5627. if (std::strcmp(uri, LV2_TIME__speed) == 0)
  5628. return kUridTimeSpeed;
  5629. if (std::strcmp(uri, LV2_KXSTUDIO_PROPERTIES__TimePositionTicksPerBeat) == 0)
  5630. return kUridTimeTicksPerBeat;
  5631. // Others
  5632. if (std::strcmp(uri, LV2_MIDI__MidiEvent) == 0)
  5633. return kUridMidiEvent;
  5634. if (std::strcmp(uri, LV2_PARAMETERS__sampleRate) == 0)
  5635. return kUridParamSampleRate;
  5636. if (std::strcmp(uri, LV2_UI__backgroundColor) == 0)
  5637. return kUridBackgroundColor;
  5638. if (std::strcmp(uri, LV2_UI__foregroundColor) == 0)
  5639. return kUridForegroundColor;
  5640. if (std::strcmp(uri, LV2_UI__scaleFactor) == 0)
  5641. return kUridScaleFactor;
  5642. if (std::strcmp(uri, LV2_UI__windowTitle) == 0)
  5643. return kUridWindowTitle;
  5644. // Custom Carla types
  5645. if (std::strcmp(uri, URI_CARLA_ATOM_WORKER_IN) == 0)
  5646. return kUridCarlaAtomWorkerIn;
  5647. if (std::strcmp(uri, URI_CARLA_ATOM_WORKER_RESP) == 0)
  5648. return kUridCarlaAtomWorkerResp;
  5649. if (std::strcmp(uri, LV2_KXSTUDIO_PROPERTIES__TransientWindowId) == 0)
  5650. return kUridCarlaTransientWindowId;
  5651. // Custom plugin types
  5652. return ((CarlaPluginLV2*)handle)->getCustomURID(uri);
  5653. }
  5654. static const char* carla_lv2_urid_unmap(LV2_URID_Map_Handle handle, LV2_URID urid)
  5655. {
  5656. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, nullptr);
  5657. CARLA_SAFE_ASSERT_RETURN(urid != kUridNull, nullptr);
  5658. carla_debug("carla_lv2_urid_unmap(%p, %i)", handle, urid);
  5659. switch (urid)
  5660. {
  5661. // Atom types
  5662. case kUridAtomBlank:
  5663. return LV2_ATOM__Blank;
  5664. case kUridAtomBool:
  5665. return LV2_ATOM__Bool;
  5666. case kUridAtomChunk:
  5667. return LV2_ATOM__Chunk;
  5668. case kUridAtomDouble:
  5669. return LV2_ATOM__Double;
  5670. case kUridAtomEvent:
  5671. return LV2_ATOM__Event;
  5672. case kUridAtomFloat:
  5673. return LV2_ATOM__Float;
  5674. case kUridAtomInt:
  5675. return LV2_ATOM__Int;
  5676. case kUridAtomLiteral:
  5677. return LV2_ATOM__Literal;
  5678. case kUridAtomLong:
  5679. return LV2_ATOM__Long;
  5680. case kUridAtomNumber:
  5681. return LV2_ATOM__Number;
  5682. case kUridAtomObject:
  5683. return LV2_ATOM__Object;
  5684. case kUridAtomPath:
  5685. return LV2_ATOM__Path;
  5686. case kUridAtomProperty:
  5687. return LV2_ATOM__Property;
  5688. case kUridAtomResource:
  5689. return LV2_ATOM__Resource;
  5690. case kUridAtomSequence:
  5691. return LV2_ATOM__Sequence;
  5692. case kUridAtomSound:
  5693. return LV2_ATOM__Sound;
  5694. case kUridAtomString:
  5695. return LV2_ATOM__String;
  5696. case kUridAtomTuple:
  5697. return LV2_ATOM__Tuple;
  5698. case kUridAtomURI:
  5699. return LV2_ATOM__URI;
  5700. case kUridAtomURID:
  5701. return LV2_ATOM__URID;
  5702. case kUridAtomVector:
  5703. return LV2_ATOM__Vector;
  5704. case kUridAtomTransferAtom:
  5705. return LV2_ATOM__atomTransfer;
  5706. case kUridAtomTransferEvent:
  5707. return LV2_ATOM__eventTransfer;
  5708. // BufSize types
  5709. case kUridBufMaxLength:
  5710. return LV2_BUF_SIZE__maxBlockLength;
  5711. case kUridBufMinLength:
  5712. return LV2_BUF_SIZE__minBlockLength;
  5713. case kUridBufNominalLength:
  5714. return LV2_BUF_SIZE__nominalBlockLength;
  5715. case kUridBufSequenceSize:
  5716. return LV2_BUF_SIZE__sequenceSize;
  5717. // Log types
  5718. case kUridLogError:
  5719. return LV2_LOG__Error;
  5720. case kUridLogNote:
  5721. return LV2_LOG__Note;
  5722. case kUridLogTrace:
  5723. return LV2_LOG__Trace;
  5724. case kUridLogWarning:
  5725. return LV2_LOG__Warning;
  5726. // Patch types
  5727. case kUridPatchSet:
  5728. return LV2_PATCH__Set;
  5729. case kUridPatchPoperty:
  5730. return LV2_PATCH__property;
  5731. case kUridPatchValue:
  5732. return LV2_PATCH__value;
  5733. // Time types
  5734. case kUridTimePosition:
  5735. return LV2_TIME__Position;
  5736. case kUridTimeBar:
  5737. return LV2_TIME__bar;
  5738. case kUridTimeBarBeat:
  5739. return LV2_TIME__barBeat;
  5740. case kUridTimeBeat:
  5741. return LV2_TIME__beat;
  5742. case kUridTimeBeatUnit:
  5743. return LV2_TIME__beatUnit;
  5744. case kUridTimeBeatsPerBar:
  5745. return LV2_TIME__beatsPerBar;
  5746. case kUridTimeBeatsPerMinute:
  5747. return LV2_TIME__beatsPerMinute;
  5748. case kUridTimeFrame:
  5749. return LV2_TIME__frame;
  5750. case kUridTimeFramesPerSecond:
  5751. return LV2_TIME__framesPerSecond;
  5752. case kUridTimeSpeed:
  5753. return LV2_TIME__speed;
  5754. case kUridTimeTicksPerBeat:
  5755. return LV2_KXSTUDIO_PROPERTIES__TimePositionTicksPerBeat;
  5756. // Others
  5757. case kUridMidiEvent:
  5758. return LV2_MIDI__MidiEvent;
  5759. case kUridParamSampleRate:
  5760. return LV2_PARAMETERS__sampleRate;
  5761. case kUridBackgroundColor:
  5762. return LV2_UI__backgroundColor;
  5763. case kUridForegroundColor:
  5764. return LV2_UI__foregroundColor;
  5765. case kUridScaleFactor:
  5766. return LV2_UI__scaleFactor;
  5767. case kUridWindowTitle:
  5768. return LV2_UI__windowTitle;
  5769. // Custom Carla types
  5770. case kUridCarlaAtomWorkerIn:
  5771. return URI_CARLA_ATOM_WORKER_IN;
  5772. case kUridCarlaAtomWorkerResp:
  5773. return URI_CARLA_ATOM_WORKER_RESP;
  5774. case kUridCarlaTransientWindowId:
  5775. return LV2_KXSTUDIO_PROPERTIES__TransientWindowId;
  5776. }
  5777. // Custom plugin types
  5778. return ((CarlaPluginLV2*)handle)->getCustomURIDString(urid);
  5779. }
  5780. // -------------------------------------------------------------------
  5781. // Worker Feature
  5782. static LV2_Worker_Status carla_lv2_worker_schedule(LV2_Worker_Schedule_Handle handle, uint32_t size, const void* data)
  5783. {
  5784. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, LV2_WORKER_ERR_UNKNOWN);
  5785. carla_debug("carla_lv2_worker_schedule(%p, %i, %p)", handle, size, data);
  5786. return ((CarlaPluginLV2*)handle)->handleWorkerSchedule(size, data);
  5787. }
  5788. static LV2_Worker_Status carla_lv2_worker_respond(LV2_Worker_Respond_Handle handle, uint32_t size, const void* data)
  5789. {
  5790. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, LV2_WORKER_ERR_UNKNOWN);
  5791. carla_debug("carla_lv2_worker_respond(%p, %i, %p)", handle, size, data);
  5792. return ((CarlaPluginLV2*)handle)->handleWorkerRespond(size, data);
  5793. }
  5794. // -------------------------------------------------------------------
  5795. // Inline Display Feature
  5796. static void carla_lv2_inline_display_queue_draw(LV2_Inline_Display_Handle handle)
  5797. {
  5798. CARLA_SAFE_ASSERT_RETURN(handle != nullptr,);
  5799. // carla_debug("carla_lv2_inline_display_queue_draw(%p)", handle);
  5800. ((CarlaPluginLV2*)handle)->handleInlineDisplayQueueRedraw();
  5801. }
  5802. // -------------------------------------------------------------------
  5803. // Midnam Feature
  5804. static void carla_lv2_midnam_update(LV2_Midnam_Handle handle)
  5805. {
  5806. CARLA_SAFE_ASSERT_RETURN(handle != nullptr,);
  5807. carla_stdout("carla_lv2_midnam_update(%p)", handle);
  5808. ((CarlaPluginLV2*)handle)->handleMidnamUpdate();
  5809. }
  5810. // -------------------------------------------------------------------
  5811. // External UI Feature
  5812. static void carla_lv2_external_ui_closed(LV2UI_Controller controller)
  5813. {
  5814. CARLA_SAFE_ASSERT_RETURN(controller != nullptr,);
  5815. carla_debug("carla_lv2_external_ui_closed(%p)", controller);
  5816. ((CarlaPluginLV2*)controller)->handleExternalUIClosed();
  5817. }
  5818. // -------------------------------------------------------------------
  5819. // UI Port-Map Feature
  5820. static uint32_t carla_lv2_ui_port_map(LV2UI_Feature_Handle handle, const char* symbol)
  5821. {
  5822. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, LV2UI_INVALID_PORT_INDEX);
  5823. carla_debug("carla_lv2_ui_port_map(%p, \"%s\")", handle, symbol);
  5824. return ((CarlaPluginLV2*)handle)->handleUIPortMap(symbol);
  5825. }
  5826. // -------------------------------------------------------------------
  5827. // UI Resize Feature
  5828. static int carla_lv2_ui_resize(LV2UI_Feature_Handle handle, int width, int height)
  5829. {
  5830. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, 1);
  5831. carla_debug("carla_lv2_ui_resize(%p, %i, %i)", handle, width, height);
  5832. return ((CarlaPluginLV2*)handle)->handleUIResize(width, height);
  5833. }
  5834. // -------------------------------------------------------------------
  5835. // UI Touch Feature
  5836. static void carla_lv2_ui_touch(LV2UI_Feature_Handle handle, uint32_t port_index, bool touch)
  5837. {
  5838. CARLA_SAFE_ASSERT_RETURN(handle != nullptr,);
  5839. carla_debug("carla_lv2_ui_touch(%p, %u, %s)", handle, port_index, bool2str(touch));
  5840. ((CarlaPluginLV2*)handle)->handleUITouch(port_index, touch);
  5841. }
  5842. // -------------------------------------------------------------------
  5843. // UI Extension
  5844. static void carla_lv2_ui_write_function(LV2UI_Controller controller, uint32_t port_index, uint32_t buffer_size, uint32_t format, const void* buffer)
  5845. {
  5846. CARLA_SAFE_ASSERT_RETURN(controller != nullptr,);
  5847. carla_debug("carla_lv2_ui_write_function(%p, %i, %i, %i, %p)", controller, port_index, buffer_size, format, buffer);
  5848. ((CarlaPluginLV2*)controller)->handleUIWrite(port_index, buffer_size, format, buffer);
  5849. }
  5850. // -------------------------------------------------------------------
  5851. // Lilv State
  5852. static void carla_lilv_set_port_value(const char* port_symbol, void* user_data, const void* value, uint32_t size, uint32_t type)
  5853. {
  5854. CARLA_SAFE_ASSERT_RETURN(user_data != nullptr,);
  5855. carla_debug("carla_lilv_set_port_value(\"%s\", %p, %p, %i, %i", port_symbol, user_data, value, size, type);
  5856. ((CarlaPluginLV2*)user_data)->handleLilvSetPortValue(port_symbol, value, size, type);
  5857. }
  5858. // -------------------------------------------------------------------
  5859. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginLV2)
  5860. };
  5861. // -------------------------------------------------------------------------------------------------------------------
  5862. bool CarlaPipeServerLV2::msgReceived(const char* const msg) noexcept
  5863. {
  5864. if (std::strcmp(msg, "exiting") == 0)
  5865. {
  5866. closePipeServer();
  5867. fUiState = UiHide;
  5868. return true;
  5869. }
  5870. if (std::strcmp(msg, "control") == 0)
  5871. {
  5872. uint32_t index;
  5873. float value;
  5874. CARLA_SAFE_ASSERT_RETURN(readNextLineAsUInt(index), true);
  5875. CARLA_SAFE_ASSERT_RETURN(readNextLineAsFloat(value), true);
  5876. try {
  5877. kPlugin->handleUIWrite(index, sizeof(float), kUridNull, &value);
  5878. } CARLA_SAFE_EXCEPTION("magReceived control");
  5879. return true;
  5880. }
  5881. if (std::strcmp(msg, "atom") == 0)
  5882. {
  5883. uint32_t index, size;
  5884. const char* base64atom;
  5885. CARLA_SAFE_ASSERT_RETURN(readNextLineAsUInt(index), true);
  5886. CARLA_SAFE_ASSERT_RETURN(readNextLineAsUInt(size), true);
  5887. CARLA_SAFE_ASSERT_RETURN(readNextLineAsString(base64atom), true);
  5888. std::vector<uint8_t> chunk(carla_getChunkFromBase64String(base64atom));
  5889. delete[] base64atom;
  5890. CARLA_SAFE_ASSERT_RETURN(chunk.size() >= sizeof(LV2_Atom), true);
  5891. #ifdef CARLA_PROPER_CPP11_SUPPORT
  5892. const LV2_Atom* const atom((const LV2_Atom*)chunk.data());
  5893. #else
  5894. const LV2_Atom* const atom((const LV2_Atom*)&chunk.front());
  5895. #endif
  5896. CARLA_SAFE_ASSERT_RETURN(lv2_atom_total_size(atom) == chunk.size(), true);
  5897. try {
  5898. kPlugin->handleUIWrite(index, lv2_atom_total_size(atom), kUridAtomTransferEvent, atom);
  5899. } CARLA_SAFE_EXCEPTION("magReceived atom");
  5900. return true;
  5901. }
  5902. if (std::strcmp(msg, "program") == 0)
  5903. {
  5904. uint32_t index;
  5905. CARLA_SAFE_ASSERT_RETURN(readNextLineAsUInt(index), true);
  5906. try {
  5907. kPlugin->setMidiProgram(static_cast<int32_t>(index), false, true, true, false);
  5908. } CARLA_SAFE_EXCEPTION("msgReceived program");
  5909. return true;
  5910. }
  5911. if (std::strcmp(msg, "urid") == 0)
  5912. {
  5913. uint32_t urid;
  5914. const char* uri;
  5915. CARLA_SAFE_ASSERT_RETURN(readNextLineAsUInt(urid), true);
  5916. CARLA_SAFE_ASSERT_RETURN(readNextLineAsString(uri), true);
  5917. if (urid != 0)
  5918. {
  5919. try {
  5920. kPlugin->handleUridMap(urid, uri);
  5921. } CARLA_SAFE_EXCEPTION("msgReceived urid");
  5922. }
  5923. delete[] uri;
  5924. return true;
  5925. }
  5926. if (std::strcmp(msg, "reloadprograms") == 0)
  5927. {
  5928. int32_t index;
  5929. CARLA_SAFE_ASSERT_RETURN(readNextLineAsInt(index), true);
  5930. try {
  5931. kPlugin->handleProgramChanged(index);
  5932. } CARLA_SAFE_EXCEPTION("handleProgramChanged");
  5933. return true;
  5934. }
  5935. return false;
  5936. }
  5937. // -------------------------------------------------------------------------------------------------------------------
  5938. CarlaPlugin* CarlaPlugin::newLV2(const Initializer& init)
  5939. {
  5940. carla_debug("CarlaPlugin::newLV2({%p, \"%s\", \"%s\", " P_INT64 "})", init.engine, init.name, init.label, init.uniqueId);
  5941. CarlaPluginLV2* const plugin(new CarlaPluginLV2(init.engine, init.id));
  5942. if (! plugin->init(init.name, init.label, init.options))
  5943. {
  5944. delete plugin;
  5945. return nullptr;
  5946. }
  5947. return plugin;
  5948. }
  5949. // used in CarlaStandalone.cpp
  5950. const void* carla_render_inline_display_lv2(CarlaPlugin* plugin, uint32_t width, uint32_t height);
  5951. const void* carla_render_inline_display_lv2(CarlaPlugin* plugin, uint32_t width, uint32_t height)
  5952. {
  5953. CarlaPluginLV2* const lv2Plugin = (CarlaPluginLV2*)plugin;
  5954. return lv2Plugin->renderInlineDisplay(width, height);
  5955. }
  5956. // -------------------------------------------------------------------------------------------------------------------
  5957. CARLA_BACKEND_END_NAMESPACE