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.

7229 lines
265KB

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