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.

7215 lines
264KB

  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. if (LV2_IS_PORT_INPUT(portTypes))
  1848. {
  1849. const uint32_t j = iCvIn++;
  1850. pData->cvIn.ports[j].port = (CarlaEngineCVPort*)pData->client->addPort(kEnginePortTypeCV, portName, true, j);
  1851. pData->cvIn.ports[j].rindex = i;
  1852. }
  1853. else if (LV2_IS_PORT_OUTPUT(portTypes))
  1854. {
  1855. const uint32_t j = iCvOut++;
  1856. pData->cvOut.ports[j].port = (CarlaEngineCVPort*)pData->client->addPort(kEnginePortTypeCV, portName, false, j);
  1857. pData->cvOut.ports[j].rindex = i;
  1858. }
  1859. else
  1860. carla_stderr("WARNING - Got a broken Port (CV, but not input or output)");
  1861. }
  1862. else if (LV2_IS_PORT_ATOM_SEQUENCE(portTypes))
  1863. {
  1864. if (LV2_IS_PORT_INPUT(portTypes))
  1865. {
  1866. const uint32_t j = iEvIn++;
  1867. fDescriptor->connect_port(fHandle, i, &fEventsIn.data[j].atom->atoms);
  1868. if (fHandle2 != nullptr)
  1869. fDescriptor->connect_port(fHandle2, i, &fEventsIn.data[j].atom->atoms);
  1870. fEventsIn.data[j].rindex = i;
  1871. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  1872. fEventsIn.data[j].type |= CARLA_EVENT_TYPE_MIDI;
  1873. if (portTypes & LV2_PORT_DATA_PATCH_MESSAGE)
  1874. fEventsIn.data[j].type |= CARLA_EVENT_TYPE_MESSAGE;
  1875. if (portTypes & LV2_PORT_DATA_TIME_POSITION)
  1876. fEventsIn.data[j].type |= CARLA_EVENT_TYPE_TIME;
  1877. if (evIns.count() == 1)
  1878. {
  1879. fEventsIn.ctrl = &fEventsIn.data[j];
  1880. fEventsIn.ctrlIndex = j;
  1881. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  1882. needsCtrlIn = true;
  1883. }
  1884. else
  1885. {
  1886. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  1887. fEventsIn.data[j].port = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, j);
  1888. if (LV2_IS_PORT_DESIGNATION_CONTROL(fRdfDescriptor->Ports[i].Designation))
  1889. {
  1890. fEventsIn.ctrl = &fEventsIn.data[j];
  1891. fEventsIn.ctrlIndex = j;
  1892. }
  1893. }
  1894. }
  1895. else if (LV2_IS_PORT_OUTPUT(portTypes))
  1896. {
  1897. const uint32_t j = iEvOut++;
  1898. fDescriptor->connect_port(fHandle, i, &fEventsOut.data[j].atom->atoms);
  1899. if (fHandle2 != nullptr)
  1900. fDescriptor->connect_port(fHandle2, i, &fEventsOut.data[j].atom->atoms);
  1901. fEventsOut.data[j].rindex = i;
  1902. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  1903. fEventsOut.data[j].type |= CARLA_EVENT_TYPE_MIDI;
  1904. if (portTypes & LV2_PORT_DATA_PATCH_MESSAGE)
  1905. fEventsOut.data[j].type |= CARLA_EVENT_TYPE_MESSAGE;
  1906. if (portTypes & LV2_PORT_DATA_TIME_POSITION)
  1907. fEventsOut.data[j].type |= CARLA_EVENT_TYPE_TIME;
  1908. if (evOuts.count() == 1)
  1909. {
  1910. fEventsOut.ctrl = &fEventsOut.data[j];
  1911. fEventsOut.ctrlIndex = j;
  1912. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  1913. needsCtrlOut = true;
  1914. }
  1915. else
  1916. {
  1917. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  1918. fEventsOut.data[j].port = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, j);
  1919. if (LV2_IS_PORT_DESIGNATION_CONTROL(fRdfDescriptor->Ports[i].Designation))
  1920. {
  1921. fEventsOut.ctrl = &fEventsOut.data[j];
  1922. fEventsOut.ctrlIndex = j;
  1923. }
  1924. }
  1925. }
  1926. else
  1927. carla_stderr2("WARNING - Got a broken Port (Atom-Sequence, but not input or output)");
  1928. }
  1929. else if (LV2_IS_PORT_EVENT(portTypes))
  1930. {
  1931. if (LV2_IS_PORT_INPUT(portTypes))
  1932. {
  1933. const uint32_t j = iEvIn++;
  1934. fDescriptor->connect_port(fHandle, i, fEventsIn.data[j].event);
  1935. if (fHandle2 != nullptr)
  1936. fDescriptor->connect_port(fHandle2, i, fEventsIn.data[j].event);
  1937. fEventsIn.data[j].rindex = i;
  1938. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  1939. fEventsIn.data[j].type |= CARLA_EVENT_TYPE_MIDI;
  1940. if (portTypes & LV2_PORT_DATA_PATCH_MESSAGE)
  1941. fEventsIn.data[j].type |= CARLA_EVENT_TYPE_MESSAGE;
  1942. if (portTypes & LV2_PORT_DATA_TIME_POSITION)
  1943. fEventsIn.data[j].type |= CARLA_EVENT_TYPE_TIME;
  1944. if (evIns.count() == 1)
  1945. {
  1946. fEventsIn.ctrl = &fEventsIn.data[j];
  1947. fEventsIn.ctrlIndex = j;
  1948. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  1949. needsCtrlIn = true;
  1950. }
  1951. else
  1952. {
  1953. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  1954. fEventsIn.data[j].port = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, j);
  1955. if (LV2_IS_PORT_DESIGNATION_CONTROL(fRdfDescriptor->Ports[i].Designation))
  1956. {
  1957. fEventsIn.ctrl = &fEventsIn.data[j];
  1958. fEventsIn.ctrlIndex = j;
  1959. }
  1960. }
  1961. }
  1962. else if (LV2_IS_PORT_OUTPUT(portTypes))
  1963. {
  1964. const uint32_t j = iEvOut++;
  1965. fDescriptor->connect_port(fHandle, i, fEventsOut.data[j].event);
  1966. if (fHandle2 != nullptr)
  1967. fDescriptor->connect_port(fHandle2, i, fEventsOut.data[j].event);
  1968. fEventsOut.data[j].rindex = i;
  1969. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  1970. fEventsOut.data[j].type |= CARLA_EVENT_TYPE_MIDI;
  1971. if (portTypes & LV2_PORT_DATA_PATCH_MESSAGE)
  1972. fEventsOut.data[j].type |= CARLA_EVENT_TYPE_MESSAGE;
  1973. if (portTypes & LV2_PORT_DATA_TIME_POSITION)
  1974. fEventsOut.data[j].type |= CARLA_EVENT_TYPE_TIME;
  1975. if (evOuts.count() == 1)
  1976. {
  1977. fEventsOut.ctrl = &fEventsOut.data[j];
  1978. fEventsOut.ctrlIndex = j;
  1979. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  1980. needsCtrlOut = true;
  1981. }
  1982. else
  1983. {
  1984. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  1985. fEventsOut.data[j].port = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, j);
  1986. if (LV2_IS_PORT_DESIGNATION_CONTROL(fRdfDescriptor->Ports[i].Designation))
  1987. {
  1988. fEventsOut.ctrl = &fEventsOut.data[j];
  1989. fEventsOut.ctrlIndex = j;
  1990. }
  1991. }
  1992. }
  1993. else
  1994. carla_stderr2("WARNING - Got a broken Port (Event, but not input or output)");
  1995. }
  1996. else if (LV2_IS_PORT_MIDI_LL(portTypes))
  1997. {
  1998. if (LV2_IS_PORT_INPUT(portTypes))
  1999. {
  2000. const uint32_t j = iEvIn++;
  2001. fDescriptor->connect_port(fHandle, i, &fEventsIn.data[j].midi);
  2002. if (fHandle2 != nullptr)
  2003. fDescriptor->connect_port(fHandle2, i, &fEventsIn.data[j].midi);
  2004. fEventsIn.data[j].type |= CARLA_EVENT_TYPE_MIDI;
  2005. fEventsIn.data[j].rindex = i;
  2006. if (evIns.count() == 1)
  2007. {
  2008. needsCtrlIn = true;
  2009. fEventsIn.ctrl = &fEventsIn.data[j];
  2010. fEventsIn.ctrlIndex = j;
  2011. }
  2012. else
  2013. {
  2014. fEventsIn.data[j].port = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, j);
  2015. if (LV2_IS_PORT_DESIGNATION_CONTROL(fRdfDescriptor->Ports[i].Designation))
  2016. {
  2017. fEventsIn.ctrl = &fEventsIn.data[j];
  2018. fEventsIn.ctrlIndex = j;
  2019. }
  2020. }
  2021. }
  2022. else if (LV2_IS_PORT_OUTPUT(portTypes))
  2023. {
  2024. const uint32_t j = iEvOut++;
  2025. fDescriptor->connect_port(fHandle, i, &fEventsOut.data[j].midi);
  2026. if (fHandle2 != nullptr)
  2027. fDescriptor->connect_port(fHandle2, i, &fEventsOut.data[j].midi);
  2028. fEventsOut.data[j].type |= CARLA_EVENT_TYPE_MIDI;
  2029. fEventsOut.data[j].rindex = i;
  2030. if (evOuts.count() == 1)
  2031. {
  2032. needsCtrlOut = true;
  2033. fEventsOut.ctrl = &fEventsOut.data[j];
  2034. fEventsOut.ctrlIndex = j;
  2035. }
  2036. else
  2037. {
  2038. fEventsOut.data[j].port = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, j);
  2039. if (LV2_IS_PORT_DESIGNATION_CONTROL(fRdfDescriptor->Ports[i].Designation))
  2040. {
  2041. fEventsOut.ctrl = &fEventsOut.data[j];
  2042. fEventsOut.ctrlIndex = j;
  2043. }
  2044. }
  2045. }
  2046. else
  2047. carla_stderr2("WARNING - Got a broken Port (MIDI, but not input or output)");
  2048. }
  2049. else if (LV2_IS_PORT_CONTROL(portTypes))
  2050. {
  2051. const LV2_Property portProps(fRdfDescriptor->Ports[i].Properties);
  2052. const LV2_Property portDesignation(fRdfDescriptor->Ports[i].Designation);
  2053. const LV2_RDF_PortPoints portPoints(fRdfDescriptor->Ports[i].Points);
  2054. const uint32_t j = iCtrl++;
  2055. pData->param.data[j].index = static_cast<int32_t>(j);
  2056. pData->param.data[j].rindex = static_cast<int32_t>(i);
  2057. float min, max, def, step, stepSmall, stepLarge;
  2058. // min value
  2059. if (LV2_HAVE_MINIMUM_PORT_POINT(portPoints.Hints))
  2060. min = portPoints.Minimum;
  2061. else
  2062. min = 0.0f;
  2063. // max value
  2064. if (LV2_HAVE_MAXIMUM_PORT_POINT(portPoints.Hints))
  2065. max = portPoints.Maximum;
  2066. else
  2067. max = 1.0f;
  2068. if (LV2_IS_PORT_SAMPLE_RATE(portProps))
  2069. {
  2070. min *= sampleRate;
  2071. max *= sampleRate;
  2072. pData->param.data[j].hints |= PARAMETER_USES_SAMPLERATE;
  2073. }
  2074. // stupid hack for ir.lv2 (broken plugin)
  2075. if (std::strcmp(fRdfDescriptor->URI, "http://factorial.hu/plugins/lv2/ir") == 0 && std::strncmp(fRdfDescriptor->Ports[i].Name, "FileHash", 8) == 0)
  2076. {
  2077. min = 0.0f;
  2078. max = (float)0xffffff;
  2079. }
  2080. if (min >= max)
  2081. {
  2082. carla_stderr2("WARNING - Broken plugin parameter '%s': min >= max", fRdfDescriptor->Ports[i].Name);
  2083. max = min + 0.1f;
  2084. }
  2085. // default value
  2086. if (LV2_HAVE_DEFAULT_PORT_POINT(portPoints.Hints))
  2087. {
  2088. def = portPoints.Default;
  2089. }
  2090. else
  2091. {
  2092. // no default value
  2093. if (min < 0.0f && max > 0.0f)
  2094. def = 0.0f;
  2095. else
  2096. def = min;
  2097. }
  2098. if (def < min)
  2099. def = min;
  2100. else if (def > max)
  2101. def = max;
  2102. if (LV2_IS_PORT_TOGGLED(portProps))
  2103. {
  2104. step = max - min;
  2105. stepSmall = step;
  2106. stepLarge = step;
  2107. pData->param.data[j].hints |= PARAMETER_IS_BOOLEAN;
  2108. }
  2109. else if (LV2_IS_PORT_INTEGER(portProps))
  2110. {
  2111. step = 1.0f;
  2112. stepSmall = 1.0f;
  2113. stepLarge = 10.0f;
  2114. pData->param.data[j].hints |= PARAMETER_IS_INTEGER;
  2115. }
  2116. else
  2117. {
  2118. float range = max - min;
  2119. step = range/100.0f;
  2120. stepSmall = range/1000.0f;
  2121. stepLarge = range/10.0f;
  2122. }
  2123. if (LV2_IS_PORT_INPUT(portTypes))
  2124. {
  2125. pData->param.data[j].type = PARAMETER_INPUT;
  2126. if (LV2_IS_PORT_DESIGNATION_LATENCY(portDesignation))
  2127. {
  2128. carla_stderr("Plugin has latency input port, this should not happen!");
  2129. }
  2130. else if (LV2_IS_PORT_DESIGNATION_SAMPLE_RATE(portDesignation))
  2131. {
  2132. def = sampleRate;
  2133. step = 1.0f;
  2134. stepSmall = 1.0f;
  2135. stepLarge = 1.0f;
  2136. pData->param.special[j] = PARAMETER_SPECIAL_SAMPLE_RATE;
  2137. }
  2138. else if (LV2_IS_PORT_DESIGNATION_FREEWHEELING(portDesignation))
  2139. {
  2140. pData->param.special[j] = PARAMETER_SPECIAL_FREEWHEEL;
  2141. }
  2142. else if (LV2_IS_PORT_DESIGNATION_TIME(portDesignation))
  2143. {
  2144. pData->param.special[j] = PARAMETER_SPECIAL_TIME;
  2145. }
  2146. else
  2147. {
  2148. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  2149. pData->param.data[j].hints |= PARAMETER_IS_AUTOMABLE;
  2150. pData->param.data[j].hints |= PARAMETER_CAN_BE_CV_CONTROLLED;
  2151. needsCtrlIn = true;
  2152. }
  2153. // MIDI CC value
  2154. const LV2_RDF_PortMidiMap& portMidiMap(fRdfDescriptor->Ports[i].MidiMap);
  2155. if (LV2_IS_PORT_MIDI_MAP_CC(portMidiMap.Type))
  2156. {
  2157. if (portMidiMap.Number < MAX_MIDI_CONTROL && ! MIDI_IS_CONTROL_BANK_SELECT(portMidiMap.Number))
  2158. pData->param.data[j].midiCC = static_cast<int16_t>(portMidiMap.Number);
  2159. }
  2160. }
  2161. else if (LV2_IS_PORT_OUTPUT(portTypes))
  2162. {
  2163. pData->param.data[j].type = PARAMETER_OUTPUT;
  2164. if (LV2_IS_PORT_DESIGNATION_LATENCY(portDesignation))
  2165. {
  2166. min = 0.0f;
  2167. max = sampleRate;
  2168. def = 0.0f;
  2169. step = 1.0f;
  2170. stepSmall = 1.0f;
  2171. stepLarge = 1.0f;
  2172. pData->param.special[j] = PARAMETER_SPECIAL_LATENCY;
  2173. CARLA_SAFE_ASSERT_INT2(fLatencyIndex == static_cast<int32_t>(j), fLatencyIndex, j);
  2174. }
  2175. else if (LV2_IS_PORT_DESIGNATION_SAMPLE_RATE(portDesignation))
  2176. {
  2177. def = sampleRate;
  2178. step = 1.0f;
  2179. stepSmall = 1.0f;
  2180. stepLarge = 1.0f;
  2181. pData->param.special[j] = PARAMETER_SPECIAL_SAMPLE_RATE;
  2182. }
  2183. else if (LV2_IS_PORT_DESIGNATION_FREEWHEELING(portDesignation))
  2184. {
  2185. carla_stderr("Plugin has freewheeling output port, this should not happen!");
  2186. }
  2187. else if (LV2_IS_PORT_DESIGNATION_TIME(portDesignation))
  2188. {
  2189. pData->param.special[j] = PARAMETER_SPECIAL_TIME;
  2190. }
  2191. else
  2192. {
  2193. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  2194. pData->param.data[j].hints |= PARAMETER_IS_AUTOMABLE;
  2195. needsCtrlOut = true;
  2196. }
  2197. }
  2198. else
  2199. {
  2200. pData->param.data[j].type = PARAMETER_UNKNOWN;
  2201. carla_stderr2("WARNING - Got a broken Port (Control, but not input or output)");
  2202. }
  2203. // extra parameter hints
  2204. if (LV2_IS_PORT_LOGARITHMIC(portProps))
  2205. pData->param.data[j].hints |= PARAMETER_IS_LOGARITHMIC;
  2206. if (LV2_IS_PORT_TRIGGER(portProps))
  2207. pData->param.data[j].hints |= PARAMETER_IS_TRIGGER;
  2208. if (LV2_IS_PORT_STRICT_BOUNDS(portProps))
  2209. pData->param.data[j].hints |= PARAMETER_IS_STRICT_BOUNDS;
  2210. if (LV2_IS_PORT_ENUMERATION(portProps))
  2211. pData->param.data[j].hints |= PARAMETER_USES_SCALEPOINTS;
  2212. // check if parameter is not enabled or automable
  2213. if (LV2_IS_PORT_NOT_ON_GUI(portProps))
  2214. pData->param.data[j].hints &= ~(PARAMETER_IS_ENABLED|PARAMETER_IS_AUTOMABLE);
  2215. else if (LV2_IS_PORT_CAUSES_ARTIFACTS(portProps) || LV2_IS_PORT_EXPENSIVE(portProps))
  2216. pData->param.data[j].hints &= ~PARAMETER_IS_AUTOMABLE;
  2217. else if (LV2_IS_PORT_NOT_AUTOMATIC(portProps) || LV2_IS_PORT_NON_AUTOMABLE(portProps))
  2218. pData->param.data[j].hints &= ~PARAMETER_IS_AUTOMABLE;
  2219. pData->param.ranges[j].min = min;
  2220. pData->param.ranges[j].max = max;
  2221. pData->param.ranges[j].def = def;
  2222. pData->param.ranges[j].step = step;
  2223. pData->param.ranges[j].stepSmall = stepSmall;
  2224. pData->param.ranges[j].stepLarge = stepLarge;
  2225. // Start parameters in their default values (except freewheel, which is off by default)
  2226. if (pData->param.data[j].type == PARAMETER_INPUT && pData->param.special[j] == PARAMETER_SPECIAL_FREEWHEEL)
  2227. fParamBuffers[j] = min;
  2228. else
  2229. fParamBuffers[j] = def;
  2230. fDescriptor->connect_port(fHandle, i, &fParamBuffers[j]);
  2231. if (fHandle2 != nullptr)
  2232. fDescriptor->connect_port(fHandle2, i, &fParamBuffers[j]);
  2233. }
  2234. else
  2235. {
  2236. // Port Type not supported, but it's optional anyway
  2237. fDescriptor->connect_port(fHandle, i, nullptr);
  2238. if (fHandle2 != nullptr)
  2239. fDescriptor->connect_port(fHandle2, i, nullptr);
  2240. }
  2241. }
  2242. for (uint32_t i=0; i < fRdfDescriptor->ParameterCount; ++i)
  2243. {
  2244. const LV2_RDF_Parameter& rdfParam(fRdfDescriptor->Parameters[i]);
  2245. switch (rdfParam.Type)
  2246. {
  2247. case LV2_PARAMETER_BOOL:
  2248. case LV2_PARAMETER_INT:
  2249. // case LV2_PARAMETER_LONG:
  2250. case LV2_PARAMETER_FLOAT:
  2251. case LV2_PARAMETER_DOUBLE:
  2252. break;
  2253. default:
  2254. continue;
  2255. }
  2256. const LV2_RDF_PortPoints& portPoints(rdfParam.Points);
  2257. const uint32_t j = iCtrl++;
  2258. pData->param.data[j].index = static_cast<int32_t>(j);
  2259. pData->param.data[j].rindex = static_cast<int32_t>(fRdfDescriptor->PortCount + i);
  2260. float min, max, def, step, stepSmall, stepLarge;
  2261. // min value
  2262. if (LV2_HAVE_MINIMUM_PORT_POINT(portPoints.Hints))
  2263. min = portPoints.Minimum;
  2264. else
  2265. min = 0.0f;
  2266. // max value
  2267. if (LV2_HAVE_MAXIMUM_PORT_POINT(portPoints.Hints))
  2268. max = portPoints.Maximum;
  2269. else
  2270. max = 1.0f;
  2271. if (min >= max)
  2272. {
  2273. carla_stderr2("WARNING - Broken plugin parameter '%s': min >= max", rdfParam.Label);
  2274. max = min + 0.1f;
  2275. }
  2276. // default value
  2277. if (LV2_HAVE_DEFAULT_PORT_POINT(portPoints.Hints))
  2278. {
  2279. def = portPoints.Default;
  2280. }
  2281. else
  2282. {
  2283. // no default value
  2284. if (min < 0.0f && max > 0.0f)
  2285. def = 0.0f;
  2286. else
  2287. def = min;
  2288. }
  2289. if (def < min)
  2290. def = min;
  2291. else if (def > max)
  2292. def = max;
  2293. switch (rdfParam.Type)
  2294. {
  2295. case LV2_PARAMETER_BOOL:
  2296. step = max - min;
  2297. stepSmall = step;
  2298. stepLarge = step;
  2299. pData->param.data[j].hints |= PARAMETER_IS_BOOLEAN;
  2300. break;
  2301. case LV2_PARAMETER_INT:
  2302. case LV2_PARAMETER_LONG:
  2303. step = 1.0f;
  2304. stepSmall = 1.0f;
  2305. stepLarge = 10.0f;
  2306. pData->param.data[j].hints |= PARAMETER_IS_INTEGER;
  2307. break;
  2308. default:
  2309. const float range = max - min;
  2310. step = range/100.0f;
  2311. stepSmall = range/1000.0f;
  2312. stepLarge = range/10.0f;
  2313. break;
  2314. }
  2315. if (rdfParam.Input)
  2316. {
  2317. pData->param.data[j].type = PARAMETER_INPUT;
  2318. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  2319. pData->param.data[j].hints |= PARAMETER_IS_AUTOMABLE;
  2320. needsCtrlIn = true;
  2321. }
  2322. else
  2323. {
  2324. pData->param.data[j].type = PARAMETER_OUTPUT;
  2325. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  2326. pData->param.data[j].hints |= PARAMETER_IS_AUTOMABLE;
  2327. needsCtrlOut = true;
  2328. }
  2329. pData->param.ranges[j].min = min;
  2330. pData->param.ranges[j].max = max;
  2331. pData->param.ranges[j].def = def;
  2332. pData->param.ranges[j].step = step;
  2333. pData->param.ranges[j].stepSmall = stepSmall;
  2334. pData->param.ranges[j].stepLarge = stepLarge;
  2335. fParamBuffers[j] = def;
  2336. }
  2337. if (needsCtrlIn)
  2338. {
  2339. portName.clear();
  2340. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  2341. {
  2342. portName = pData->name;
  2343. portName += ":";
  2344. }
  2345. portName += "events-in";
  2346. portName.truncate(portNameSize);
  2347. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, 0);
  2348. }
  2349. if (needsCtrlOut)
  2350. {
  2351. portName.clear();
  2352. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  2353. {
  2354. portName = pData->name;
  2355. portName += ":";
  2356. }
  2357. portName += "events-out";
  2358. portName.truncate(portNameSize);
  2359. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, 0);
  2360. }
  2361. if (fExt.worker != nullptr && fEventsIn.ctrl != nullptr)
  2362. {
  2363. fAtomBufferWorkerIn.createBuffer(eventBufferSize);
  2364. fAtomBufferWorkerResp.createBuffer(eventBufferSize);
  2365. fAtomBufferWorkerInTmpData = new uint8_t[fAtomBufferWorkerIn.getSize()];
  2366. }
  2367. if (fRdfDescriptor->ParameterCount > 0 ||
  2368. (fUI.type != UI::TYPE_NULL && fEventsIn.count > 0 && (fEventsIn.data[0].type & CARLA_EVENT_DATA_ATOM) != 0))
  2369. fAtomBufferEvIn.createBuffer(eventBufferSize);
  2370. if (fUI.type != UI::TYPE_NULL && fEventsOut.count > 0 && (fEventsOut.data[0].type & CARLA_EVENT_DATA_ATOM) != 0)
  2371. {
  2372. fAtomBufferUiOut.createBuffer(std::min(eventBufferSize*32, 1638400U));
  2373. fAtomBufferUiOutTmpData = new uint8_t[fAtomBufferUiOut.getSize()];
  2374. }
  2375. if (fEventsIn.ctrl != nullptr && fEventsIn.ctrl->port == nullptr)
  2376. fEventsIn.ctrl->port = pData->event.portIn;
  2377. if (fEventsOut.ctrl != nullptr && fEventsOut.ctrl->port == nullptr)
  2378. fEventsOut.ctrl->port = pData->event.portOut;
  2379. if (fEventsIn.ctrl != nullptr && fExt.midnam != nullptr)
  2380. {
  2381. if (char* const midnam = fExt.midnam->midnam(fHandle))
  2382. {
  2383. fEventsIn.ctrl->port->setMetaData("http://www.midi.org/dtds/MIDINameDocument10.dtd",
  2384. midnam, "text/xml");
  2385. if (fExt.midnam->free != nullptr)
  2386. fExt.midnam->free(midnam);
  2387. }
  2388. }
  2389. if (forcedStereoIn || forcedStereoOut)
  2390. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  2391. else
  2392. pData->options &= ~PLUGIN_OPTION_FORCE_STEREO;
  2393. // plugin hints
  2394. pData->hints = (pData->hints & PLUGIN_HAS_INLINE_DISPLAY) ? PLUGIN_HAS_INLINE_DISPLAY : 0;
  2395. if (isRealtimeSafe())
  2396. pData->hints |= PLUGIN_IS_RTSAFE;
  2397. if (fUI.type != UI::TYPE_NULL || fFilePathURI.isNotEmpty())
  2398. {
  2399. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  2400. if (fUI.type == UI::TYPE_EMBED || fUI.type == UI::TYPE_EXTERNAL)
  2401. pData->hints |= PLUGIN_NEEDS_UI_MAIN_THREAD;
  2402. }
  2403. if (LV2_IS_GENERATOR(fRdfDescriptor->Type[0], fRdfDescriptor->Type[1]))
  2404. pData->hints |= PLUGIN_IS_SYNTH;
  2405. if (aOuts > 0 && (aIns == aOuts || aIns == 1))
  2406. pData->hints |= PLUGIN_CAN_DRYWET;
  2407. if (aOuts > 0)
  2408. pData->hints |= PLUGIN_CAN_VOLUME;
  2409. if (aOuts >= 2 && aOuts % 2 == 0)
  2410. pData->hints |= PLUGIN_CAN_BALANCE;
  2411. // extra plugin hints
  2412. pData->extraHints = 0x0;
  2413. // check initial latency
  2414. findInitialLatencyValue(aIns, aOuts);
  2415. bufferSizeChanged(pData->engine->getBufferSize());
  2416. reloadPrograms(true);
  2417. evIns.clear();
  2418. evOuts.clear();
  2419. if (pData->active)
  2420. activate();
  2421. carla_debug("CarlaPluginLV2::reload() - end");
  2422. }
  2423. void findInitialLatencyValue(const uint32_t aIns, const uint32_t aOuts) const
  2424. {
  2425. if (fLatencyIndex < 0)
  2426. return;
  2427. // we need to pre-run the plugin so it can update its latency control-port
  2428. const uint32_t bufferSize = static_cast<uint32_t>(fLv2Options.nominalBufferSize);
  2429. float tmpIn [(aIns > 0) ? aIns : 1][bufferSize];
  2430. float tmpOut[(aOuts > 0) ? aOuts : 1][bufferSize];
  2431. for (uint32_t j=0; j < aIns; ++j)
  2432. {
  2433. carla_zeroFloats(tmpIn[j], bufferSize);
  2434. try {
  2435. fDescriptor->connect_port(fHandle, pData->audioIn.ports[j].rindex, tmpIn[j]);
  2436. } CARLA_SAFE_EXCEPTION("LV2 connect_port latency input");
  2437. }
  2438. for (uint32_t j=0; j < aOuts; ++j)
  2439. {
  2440. carla_zeroFloats(tmpOut[j], bufferSize);
  2441. try {
  2442. fDescriptor->connect_port(fHandle, pData->audioOut.ports[j].rindex, tmpOut[j]);
  2443. } CARLA_SAFE_EXCEPTION("LV2 connect_port latency output");
  2444. }
  2445. if (fDescriptor->activate != nullptr)
  2446. {
  2447. try {
  2448. fDescriptor->activate(fHandle);
  2449. } CARLA_SAFE_EXCEPTION("LV2 latency activate");
  2450. }
  2451. try {
  2452. fDescriptor->run(fHandle, bufferSize);
  2453. } CARLA_SAFE_EXCEPTION("LV2 latency run");
  2454. if (fDescriptor->deactivate != nullptr)
  2455. {
  2456. try {
  2457. fDescriptor->deactivate(fHandle);
  2458. } CARLA_SAFE_EXCEPTION("LV2 latency deactivate");
  2459. }
  2460. // done, let's get the value
  2461. if (const uint32_t latency = getLatencyInFrames())
  2462. {
  2463. pData->client->setLatency(latency);
  2464. #ifndef BUILD_BRIDGE
  2465. pData->latency.recreateBuffers(std::max(aIns, aOuts), latency);
  2466. #endif
  2467. }
  2468. }
  2469. void reloadPrograms(const bool doInit) override
  2470. {
  2471. carla_debug("CarlaPluginLV2::reloadPrograms(%s)", bool2str(doInit));
  2472. const uint32_t oldCount = pData->midiprog.count;
  2473. const int32_t current = pData->midiprog.current;
  2474. // special LV2 programs handling
  2475. if (doInit)
  2476. {
  2477. pData->prog.clear();
  2478. const uint32_t presetCount(fRdfDescriptor->PresetCount);
  2479. if (presetCount > 0)
  2480. {
  2481. pData->prog.createNew(presetCount);
  2482. for (uint32_t i=0; i < presetCount; ++i)
  2483. pData->prog.names[i] = carla_strdup(fRdfDescriptor->Presets[i].Label);
  2484. }
  2485. }
  2486. // Delete old programs
  2487. pData->midiprog.clear();
  2488. // Query new programs
  2489. uint32_t newCount = 0;
  2490. if (fExt.programs != nullptr && fExt.programs->get_program != nullptr && fExt.programs->select_program != nullptr)
  2491. {
  2492. for (; fExt.programs->get_program(fHandle, newCount);)
  2493. ++newCount;
  2494. }
  2495. if (newCount > 0)
  2496. {
  2497. pData->midiprog.createNew(newCount);
  2498. // Update data
  2499. for (uint32_t i=0; i < newCount; ++i)
  2500. {
  2501. const LV2_Program_Descriptor* const pdesc(fExt.programs->get_program(fHandle, i));
  2502. CARLA_SAFE_ASSERT_CONTINUE(pdesc != nullptr);
  2503. CARLA_SAFE_ASSERT(pdesc->name != nullptr);
  2504. pData->midiprog.data[i].bank = pdesc->bank;
  2505. pData->midiprog.data[i].program = pdesc->program;
  2506. pData->midiprog.data[i].name = carla_strdup(pdesc->name);
  2507. }
  2508. }
  2509. if (doInit)
  2510. {
  2511. if (newCount > 0)
  2512. {
  2513. setMidiProgram(0, false, false, false, true);
  2514. }
  2515. else
  2516. {
  2517. // load default state
  2518. if (LilvState* const state = Lv2WorldClass::getInstance().getStateFromURI(fDescriptor->URI, (const LV2_URID_Map*)fFeatures[kFeatureIdUridMap]->data))
  2519. {
  2520. lilv_state_restore(state, fExt.state, fHandle, carla_lilv_set_port_value, this, 0, fFeatures);
  2521. if (fHandle2 != nullptr)
  2522. lilv_state_restore(state, fExt.state, fHandle2, carla_lilv_set_port_value, this, 0, fFeatures);
  2523. lilv_state_free(state);
  2524. }
  2525. }
  2526. }
  2527. else
  2528. {
  2529. // Check if current program is invalid
  2530. bool programChanged = false;
  2531. if (newCount == oldCount+1)
  2532. {
  2533. // one midi program added, probably created by user
  2534. pData->midiprog.current = static_cast<int32_t>(oldCount);
  2535. programChanged = true;
  2536. }
  2537. else if (current < 0 && newCount > 0)
  2538. {
  2539. // programs exist now, but not before
  2540. pData->midiprog.current = 0;
  2541. programChanged = true;
  2542. }
  2543. else if (current >= 0 && newCount == 0)
  2544. {
  2545. // programs existed before, but not anymore
  2546. pData->midiprog.current = -1;
  2547. programChanged = true;
  2548. }
  2549. else if (current >= static_cast<int32_t>(newCount))
  2550. {
  2551. // current midi program > count
  2552. pData->midiprog.current = 0;
  2553. programChanged = true;
  2554. }
  2555. else
  2556. {
  2557. // no change
  2558. pData->midiprog.current = current;
  2559. }
  2560. if (programChanged)
  2561. setMidiProgram(pData->midiprog.current, true, true, true, false);
  2562. pData->engine->callback(true, true, ENGINE_CALLBACK_RELOAD_PROGRAMS, pData->id, 0, 0, 0, 0.0f, nullptr);
  2563. }
  2564. }
  2565. // -------------------------------------------------------------------
  2566. // Plugin processing
  2567. void activate() noexcept override
  2568. {
  2569. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr,);
  2570. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr,);
  2571. if (fDescriptor->activate != nullptr)
  2572. {
  2573. try {
  2574. fDescriptor->activate(fHandle);
  2575. } CARLA_SAFE_EXCEPTION("LV2 activate");
  2576. if (fHandle2 != nullptr)
  2577. {
  2578. try {
  2579. fDescriptor->activate(fHandle2);
  2580. } CARLA_SAFE_EXCEPTION("LV2 activate #2");
  2581. }
  2582. }
  2583. fFirstActive = true;
  2584. }
  2585. void deactivate() noexcept override
  2586. {
  2587. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr,);
  2588. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr,);
  2589. if (fDescriptor->deactivate != nullptr)
  2590. {
  2591. try {
  2592. fDescriptor->deactivate(fHandle);
  2593. } CARLA_SAFE_EXCEPTION("LV2 deactivate");
  2594. if (fHandle2 != nullptr)
  2595. {
  2596. try {
  2597. fDescriptor->deactivate(fHandle2);
  2598. } CARLA_SAFE_EXCEPTION("LV2 deactivate #2");
  2599. }
  2600. }
  2601. }
  2602. void process(const float** const audioIn, float** const audioOut, const float** const cvIn, float** const cvOut, const uint32_t frames) override
  2603. {
  2604. // --------------------------------------------------------------------------------------------------------
  2605. // Check if active
  2606. if (! pData->active)
  2607. {
  2608. // disable any output sound
  2609. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  2610. carla_zeroFloats(audioOut[i], frames);
  2611. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  2612. carla_zeroFloats(cvOut[i], frames);
  2613. return;
  2614. }
  2615. // --------------------------------------------------------------------------------------------------------
  2616. // Event itenerators from different APIs (input)
  2617. LV2_Atom_Buffer_Iterator evInAtomIters[fEventsIn.count];
  2618. LV2_Event_Iterator evInEventIters[fEventsIn.count];
  2619. LV2_MIDIState evInMidiStates[fEventsIn.count];
  2620. for (uint32_t i=0; i < fEventsIn.count; ++i)
  2621. {
  2622. if (fEventsIn.data[i].type & CARLA_EVENT_DATA_ATOM)
  2623. {
  2624. lv2_atom_buffer_reset(fEventsIn.data[i].atom, true);
  2625. lv2_atom_buffer_begin(&evInAtomIters[i], fEventsIn.data[i].atom);
  2626. }
  2627. else if (fEventsIn.data[i].type & CARLA_EVENT_DATA_EVENT)
  2628. {
  2629. lv2_event_buffer_reset(fEventsIn.data[i].event, LV2_EVENT_AUDIO_STAMP, fEventsIn.data[i].event->data);
  2630. lv2_event_begin(&evInEventIters[i], fEventsIn.data[i].event);
  2631. }
  2632. else if (fEventsIn.data[i].type & CARLA_EVENT_DATA_MIDI_LL)
  2633. {
  2634. fEventsIn.data[i].midi.event_count = 0;
  2635. fEventsIn.data[i].midi.size = 0;
  2636. evInMidiStates[i].midi = &fEventsIn.data[i].midi;
  2637. evInMidiStates[i].frame_count = frames;
  2638. evInMidiStates[i].position = 0;
  2639. }
  2640. }
  2641. for (uint32_t i=0; i < fEventsOut.count; ++i)
  2642. {
  2643. if (fEventsOut.data[i].type & CARLA_EVENT_DATA_ATOM)
  2644. {
  2645. lv2_atom_buffer_reset(fEventsOut.data[i].atom, false);
  2646. }
  2647. else if (fEventsOut.data[i].type & CARLA_EVENT_DATA_EVENT)
  2648. {
  2649. lv2_event_buffer_reset(fEventsOut.data[i].event, LV2_EVENT_AUDIO_STAMP, fEventsOut.data[i].event->data);
  2650. }
  2651. else if (fEventsOut.data[i].type & CARLA_EVENT_DATA_MIDI_LL)
  2652. {
  2653. // not needed
  2654. }
  2655. }
  2656. // --------------------------------------------------------------------------------------------------------
  2657. // Check if needs reset
  2658. if (pData->needsReset)
  2659. {
  2660. if (fEventsIn.ctrl != nullptr && (fEventsIn.ctrl->type & CARLA_EVENT_TYPE_MIDI) != 0)
  2661. {
  2662. const uint32_t j = fEventsIn.ctrlIndex;
  2663. CARLA_ASSERT(j < fEventsIn.count);
  2664. uint8_t midiData[3] = { 0, 0, 0 };
  2665. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  2666. {
  2667. for (uint8_t i=0; i < MAX_MIDI_CHANNELS; ++i)
  2668. {
  2669. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (i & MIDI_CHANNEL_BIT));
  2670. midiData[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  2671. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  2672. lv2_atom_buffer_write(&evInAtomIters[j], 0, 0, kUridMidiEvent, 3, midiData);
  2673. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  2674. lv2_event_write(&evInEventIters[j], 0, 0, kUridMidiEvent, 3, midiData);
  2675. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  2676. lv2midi_put_event(&evInMidiStates[j], 0.0, 3, midiData);
  2677. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (i & MIDI_CHANNEL_BIT));
  2678. midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  2679. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  2680. lv2_atom_buffer_write(&evInAtomIters[j], 0, 0, kUridMidiEvent, 3, midiData);
  2681. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  2682. lv2_event_write(&evInEventIters[j], 0, 0, kUridMidiEvent, 3, midiData);
  2683. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  2684. lv2midi_put_event(&evInMidiStates[j], 0.0, 3, midiData);
  2685. }
  2686. }
  2687. else if (pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  2688. {
  2689. for (uint8_t k=0; k < MAX_MIDI_NOTE; ++k)
  2690. {
  2691. midiData[0] = uint8_t(MIDI_STATUS_NOTE_OFF | (pData->ctrlChannel & MIDI_CHANNEL_BIT));
  2692. midiData[1] = k;
  2693. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  2694. lv2_atom_buffer_write(&evInAtomIters[j], 0, 0, kUridMidiEvent, 3, midiData);
  2695. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  2696. lv2_event_write(&evInEventIters[j], 0, 0, kUridMidiEvent, 3, midiData);
  2697. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  2698. lv2midi_put_event(&evInMidiStates[j], 0.0, 3, midiData);
  2699. }
  2700. }
  2701. }
  2702. pData->needsReset = false;
  2703. }
  2704. // --------------------------------------------------------------------------------------------------------
  2705. // TimeInfo
  2706. const EngineTimeInfo timeInfo(pData->engine->getTimeInfo());
  2707. if (fFirstActive || fLastTimeInfo != timeInfo)
  2708. {
  2709. bool doPostRt;
  2710. int32_t rindex;
  2711. const double barBeat = static_cast<double>(timeInfo.bbt.beat - 1)
  2712. + (timeInfo.bbt.tick / timeInfo.bbt.ticksPerBeat);
  2713. // update input ports
  2714. for (uint32_t k=0; k < pData->param.count; ++k)
  2715. {
  2716. if (pData->param.data[k].type != PARAMETER_INPUT)
  2717. continue;
  2718. if (pData->param.special[k] != PARAMETER_SPECIAL_TIME)
  2719. continue;
  2720. doPostRt = false;
  2721. rindex = pData->param.data[k].rindex;
  2722. CARLA_SAFE_ASSERT_CONTINUE(rindex >= 0 && rindex < static_cast<int32_t>(fRdfDescriptor->PortCount));
  2723. switch (fRdfDescriptor->Ports[rindex].Designation)
  2724. {
  2725. // Non-BBT
  2726. case LV2_PORT_DESIGNATION_TIME_SPEED:
  2727. if (fLastTimeInfo.playing != timeInfo.playing)
  2728. {
  2729. fParamBuffers[k] = timeInfo.playing ? 1.0f : 0.0f;
  2730. doPostRt = true;
  2731. }
  2732. break;
  2733. case LV2_PORT_DESIGNATION_TIME_FRAME:
  2734. if (fLastTimeInfo.frame != timeInfo.frame)
  2735. {
  2736. fParamBuffers[k] = static_cast<float>(timeInfo.frame);
  2737. doPostRt = true;
  2738. }
  2739. break;
  2740. case LV2_PORT_DESIGNATION_TIME_FRAMES_PER_SECOND:
  2741. break;
  2742. // BBT
  2743. case LV2_PORT_DESIGNATION_TIME_BAR:
  2744. if (timeInfo.bbt.valid && fLastTimeInfo.bbt.bar != timeInfo.bbt.bar)
  2745. {
  2746. fParamBuffers[k] = static_cast<float>(timeInfo.bbt.bar - 1);
  2747. doPostRt = true;
  2748. }
  2749. break;
  2750. case LV2_PORT_DESIGNATION_TIME_BAR_BEAT:
  2751. if (timeInfo.bbt.valid && (carla_isNotEqual(fLastTimeInfo.bbt.tick, timeInfo.bbt.tick) ||
  2752. fLastTimeInfo.bbt.beat != timeInfo.bbt.beat))
  2753. {
  2754. fParamBuffers[k] = static_cast<float>(barBeat);
  2755. doPostRt = true;
  2756. }
  2757. break;
  2758. case LV2_PORT_DESIGNATION_TIME_BEAT:
  2759. if (timeInfo.bbt.valid && fLastTimeInfo.bbt.beat != timeInfo.bbt.beat)
  2760. {
  2761. fParamBuffers[k] = static_cast<float>(timeInfo.bbt.beat - 1);
  2762. doPostRt = true;
  2763. }
  2764. break;
  2765. case LV2_PORT_DESIGNATION_TIME_BEAT_UNIT:
  2766. if (timeInfo.bbt.valid && carla_isNotEqual(fLastTimeInfo.bbt.beatType, timeInfo.bbt.beatType))
  2767. {
  2768. fParamBuffers[k] = timeInfo.bbt.beatType;
  2769. doPostRt = true;
  2770. }
  2771. break;
  2772. case LV2_PORT_DESIGNATION_TIME_BEATS_PER_BAR:
  2773. if (timeInfo.bbt.valid && carla_isNotEqual(fLastTimeInfo.bbt.beatsPerBar, timeInfo.bbt.beatsPerBar))
  2774. {
  2775. fParamBuffers[k] = timeInfo.bbt.beatsPerBar;
  2776. doPostRt = true;
  2777. }
  2778. break;
  2779. case LV2_PORT_DESIGNATION_TIME_BEATS_PER_MINUTE:
  2780. if (timeInfo.bbt.valid && carla_isNotEqual(fLastTimeInfo.bbt.beatsPerMinute, timeInfo.bbt.beatsPerMinute))
  2781. {
  2782. fParamBuffers[k] = static_cast<float>(timeInfo.bbt.beatsPerMinute);
  2783. doPostRt = true;
  2784. }
  2785. break;
  2786. case LV2_PORT_DESIGNATION_TIME_TICKS_PER_BEAT:
  2787. if (timeInfo.bbt.valid && carla_isNotEqual(fLastTimeInfo.bbt.ticksPerBeat, timeInfo.bbt.ticksPerBeat))
  2788. {
  2789. fParamBuffers[k] = static_cast<float>(timeInfo.bbt.ticksPerBeat);
  2790. doPostRt = true;
  2791. }
  2792. break;
  2793. }
  2794. if (doPostRt)
  2795. pData->postponeRtEvent(kPluginPostRtEventParameterChange,
  2796. true,
  2797. static_cast<int32_t>(k),
  2798. 0,
  2799. 0,
  2800. fParamBuffers[k]);
  2801. }
  2802. for (uint32_t i=0; i < fEventsIn.count; ++i)
  2803. {
  2804. if ((fEventsIn.data[i].type & CARLA_EVENT_DATA_ATOM) == 0 || (fEventsIn.data[i].type & CARLA_EVENT_TYPE_TIME) == 0)
  2805. continue;
  2806. uint8_t timeInfoBuf[256];
  2807. lv2_atom_forge_set_buffer(&fAtomForge, timeInfoBuf, sizeof(timeInfoBuf));
  2808. LV2_Atom_Forge_Frame forgeFrame;
  2809. lv2_atom_forge_object(&fAtomForge, &forgeFrame, kUridNull, kUridTimePosition);
  2810. lv2_atom_forge_key(&fAtomForge, kUridTimeSpeed);
  2811. lv2_atom_forge_float(&fAtomForge, timeInfo.playing ? 1.0f : 0.0f);
  2812. lv2_atom_forge_key(&fAtomForge, kUridTimeFrame);
  2813. lv2_atom_forge_long(&fAtomForge, static_cast<int64_t>(timeInfo.frame));
  2814. if (timeInfo.bbt.valid)
  2815. {
  2816. lv2_atom_forge_key(&fAtomForge, kUridTimeBar);
  2817. lv2_atom_forge_long(&fAtomForge, timeInfo.bbt.bar - 1);
  2818. lv2_atom_forge_key(&fAtomForge, kUridTimeBarBeat);
  2819. lv2_atom_forge_float(&fAtomForge, static_cast<float>(barBeat));
  2820. lv2_atom_forge_key(&fAtomForge, kUridTimeBeat);
  2821. lv2_atom_forge_double(&fAtomForge, timeInfo.bbt.beat - 1);
  2822. lv2_atom_forge_key(&fAtomForge, kUridTimeBeatUnit);
  2823. lv2_atom_forge_int(&fAtomForge, static_cast<int32_t>(timeInfo.bbt.beatType));
  2824. lv2_atom_forge_key(&fAtomForge, kUridTimeBeatsPerBar);
  2825. lv2_atom_forge_float(&fAtomForge, timeInfo.bbt.beatsPerBar);
  2826. lv2_atom_forge_key(&fAtomForge, kUridTimeBeatsPerMinute);
  2827. lv2_atom_forge_float(&fAtomForge, static_cast<float>(timeInfo.bbt.beatsPerMinute));
  2828. lv2_atom_forge_key(&fAtomForge, kUridTimeTicksPerBeat);
  2829. lv2_atom_forge_double(&fAtomForge, timeInfo.bbt.ticksPerBeat);
  2830. }
  2831. lv2_atom_forge_pop(&fAtomForge, &forgeFrame);
  2832. LV2_Atom* const atom((LV2_Atom*)timeInfoBuf);
  2833. CARLA_SAFE_ASSERT_BREAK(atom->size < 256);
  2834. // send only deprecated blank object for now
  2835. lv2_atom_buffer_write(&evInAtomIters[i], 0, 0, kUridAtomBlank, atom->size, LV2_ATOM_BODY_CONST(atom));
  2836. // for atom:object
  2837. //lv2_atom_buffer_write(&evInAtomIters[i], 0, 0, atom->type, atom->size, LV2_ATOM_BODY_CONST(atom));
  2838. }
  2839. pData->postRtEvents.trySplice();
  2840. fLastTimeInfo = timeInfo;
  2841. }
  2842. // --------------------------------------------------------------------------------------------------------
  2843. // Event Input and Processing
  2844. if (fEventsIn.ctrl != nullptr)
  2845. {
  2846. // ----------------------------------------------------------------------------------------------------
  2847. // Message Input
  2848. if (fAtomBufferEvIn.tryLock())
  2849. {
  2850. if (fAtomBufferEvIn.isDataAvailableForReading())
  2851. {
  2852. const LV2_Atom* atom;
  2853. uint32_t j, portIndex;
  2854. for (; fAtomBufferEvIn.get(atom, portIndex);)
  2855. {
  2856. j = (portIndex < fEventsIn.count) ? portIndex : fEventsIn.ctrlIndex;
  2857. if (! lv2_atom_buffer_write(&evInAtomIters[j], 0, 0, atom->type, atom->size, LV2_ATOM_BODY_CONST(atom)))
  2858. {
  2859. carla_stderr2("Event input buffer full, at least 1 message lost");
  2860. continue;
  2861. }
  2862. }
  2863. }
  2864. fAtomBufferEvIn.unlock();
  2865. }
  2866. if (fExt.worker != nullptr && fAtomBufferWorkerIn.tryLock())
  2867. {
  2868. if (fAtomBufferWorkerIn.isDataAvailableForReading())
  2869. {
  2870. const LV2_Atom* atom;
  2871. uint32_t portIndex;
  2872. for (; fAtomBufferWorkerIn.get(atom, portIndex);)
  2873. {
  2874. CARLA_SAFE_ASSERT_CONTINUE(atom->type == kUridCarlaAtomWorkerIn);
  2875. fExt.worker->work(fHandle, carla_lv2_worker_respond, this, atom->size, LV2_ATOM_BODY_CONST(atom));
  2876. }
  2877. }
  2878. fAtomBufferWorkerIn.unlock();
  2879. }
  2880. // ----------------------------------------------------------------------------------------------------
  2881. // MIDI Input (External)
  2882. if (pData->extNotes.mutex.tryLock())
  2883. {
  2884. if ((fEventsIn.ctrl->type & CARLA_EVENT_TYPE_MIDI) == 0)
  2885. {
  2886. // does not handle MIDI
  2887. pData->extNotes.data.clear();
  2888. }
  2889. else
  2890. {
  2891. const uint32_t j = fEventsIn.ctrlIndex;
  2892. for (RtLinkedList<ExternalMidiNote>::Itenerator it = pData->extNotes.data.begin2(); it.valid(); it.next())
  2893. {
  2894. const ExternalMidiNote& note(it.getValue(kExternalMidiNoteFallback));
  2895. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  2896. uint8_t midiEvent[3];
  2897. midiEvent[0] = uint8_t((note.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT));
  2898. midiEvent[1] = note.note;
  2899. midiEvent[2] = note.velo;
  2900. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  2901. lv2_atom_buffer_write(&evInAtomIters[j], 0, 0, kUridMidiEvent, 3, midiEvent);
  2902. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  2903. lv2_event_write(&evInEventIters[j], 0, 0, kUridMidiEvent, 3, midiEvent);
  2904. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  2905. lv2midi_put_event(&evInMidiStates[j], 0.0, 3, midiEvent);
  2906. }
  2907. pData->extNotes.data.clear();
  2908. }
  2909. pData->extNotes.mutex.unlock();
  2910. } // End of MIDI Input (External)
  2911. // ----------------------------------------------------------------------------------------------------
  2912. // CV Control Input
  2913. for (uint32_t i=0, j=0; i < pData->param.count && i < 32; ++i)
  2914. {
  2915. if (pData->param.data[i].type != PARAMETER_INPUT)
  2916. continue;
  2917. if ((pData->param.data[i].hints & PARAMETER_IS_CV_CONTROLLED) == 0x0)
  2918. continue;
  2919. const uint32_t cvIndex = j++;
  2920. pData->event.portIn->mixWithCvBuffer(cvIn[pData->cvIn.count + cvIndex], frames, i);
  2921. }
  2922. // ----------------------------------------------------------------------------------------------------
  2923. // Event Input (System)
  2924. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2925. bool allNotesOffSent = false;
  2926. #endif
  2927. bool isSampleAccurate = (pData->options & PLUGIN_OPTION_FIXED_BUFFERS) == 0;
  2928. uint32_t startTime = 0;
  2929. uint32_t timeOffset = 0;
  2930. uint32_t nextBankId;
  2931. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0)
  2932. nextBankId = pData->midiprog.data[pData->midiprog.current].bank;
  2933. else
  2934. nextBankId = 0;
  2935. const uint32_t numEvents = (fEventsIn.ctrl->port != nullptr) ? fEventsIn.ctrl->port->getEventCount() : 0;
  2936. for (uint32_t i=0; i < numEvents; ++i)
  2937. {
  2938. const EngineEvent& event(fEventsIn.ctrl->port->getEvent(i));
  2939. uint32_t eventTime = event.time;
  2940. CARLA_SAFE_ASSERT_UINT2_CONTINUE(eventTime < frames, eventTime, frames);
  2941. if (eventTime < timeOffset)
  2942. {
  2943. carla_stderr2("Timing error, eventTime:%u < timeOffset:%u for '%s'",
  2944. eventTime, timeOffset, pData->name);
  2945. eventTime = timeOffset;
  2946. }
  2947. if (isSampleAccurate && eventTime > timeOffset)
  2948. {
  2949. if (processSingle(audioIn, audioOut, cvIn, cvOut, eventTime - timeOffset, timeOffset))
  2950. {
  2951. startTime = 0;
  2952. timeOffset = eventTime;
  2953. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0)
  2954. nextBankId = pData->midiprog.data[pData->midiprog.current].bank;
  2955. else
  2956. nextBankId = 0;
  2957. for (uint32_t j=0; j < fEventsIn.count; ++j)
  2958. {
  2959. if (fEventsIn.data[j].type & CARLA_EVENT_DATA_ATOM)
  2960. {
  2961. lv2_atom_buffer_reset(fEventsIn.data[j].atom, true);
  2962. lv2_atom_buffer_begin(&evInAtomIters[j], fEventsIn.data[j].atom);
  2963. }
  2964. else if (fEventsIn.data[j].type & CARLA_EVENT_DATA_EVENT)
  2965. {
  2966. lv2_event_buffer_reset(fEventsIn.data[j].event, LV2_EVENT_AUDIO_STAMP, fEventsIn.data[j].event->data);
  2967. lv2_event_begin(&evInEventIters[j], fEventsIn.data[j].event);
  2968. }
  2969. else if (fEventsIn.data[j].type & CARLA_EVENT_DATA_MIDI_LL)
  2970. {
  2971. fEventsIn.data[j].midi.event_count = 0;
  2972. fEventsIn.data[j].midi.size = 0;
  2973. evInMidiStates[j].position = eventTime;
  2974. }
  2975. }
  2976. for (uint32_t j=0; j < fEventsOut.count; ++j)
  2977. {
  2978. if (fEventsOut.data[j].type & CARLA_EVENT_DATA_ATOM)
  2979. {
  2980. lv2_atom_buffer_reset(fEventsOut.data[j].atom, false);
  2981. }
  2982. else if (fEventsOut.data[j].type & CARLA_EVENT_DATA_EVENT)
  2983. {
  2984. lv2_event_buffer_reset(fEventsOut.data[j].event, LV2_EVENT_AUDIO_STAMP, fEventsOut.data[j].event->data);
  2985. }
  2986. else if (fEventsOut.data[j].type & CARLA_EVENT_DATA_MIDI_LL)
  2987. {
  2988. // not needed
  2989. }
  2990. }
  2991. }
  2992. else
  2993. {
  2994. startTime += timeOffset;
  2995. }
  2996. }
  2997. switch (event.type)
  2998. {
  2999. case kEngineEventTypeNull:
  3000. break;
  3001. case kEngineEventTypeControl: {
  3002. const EngineControlEvent& ctrlEvent(event.ctrl);
  3003. switch (ctrlEvent.type)
  3004. {
  3005. case kEngineControlEventTypeNull:
  3006. break;
  3007. case kEngineControlEventTypeParameter: {
  3008. float value;
  3009. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  3010. // non-midi
  3011. if (event.channel == kEngineEventNonMidiChannel)
  3012. {
  3013. const uint32_t k = ctrlEvent.param;
  3014. CARLA_SAFE_ASSERT_CONTINUE(k < pData->param.count);
  3015. if (pData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  3016. {
  3017. value = (ctrlEvent.value < 0.5f) ? pData->param.ranges[k].min : pData->param.ranges[k].max;
  3018. }
  3019. else
  3020. {
  3021. if (pData->param.data[k].hints & PARAMETER_IS_LOGARITHMIC)
  3022. value = pData->param.ranges[k].getUnnormalizedLogValue(ctrlEvent.value);
  3023. else
  3024. value = pData->param.ranges[k].getUnnormalizedValue(ctrlEvent.value);
  3025. if (pData->param.data[k].hints & PARAMETER_IS_INTEGER)
  3026. value = std::rint(value);
  3027. }
  3028. setParameterValueRT(k, value, true);
  3029. continue;
  3030. }
  3031. // Control backend stuff
  3032. if (event.channel == pData->ctrlChannel)
  3033. {
  3034. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  3035. {
  3036. value = ctrlEvent.value;
  3037. setDryWetRT(value, true);
  3038. }
  3039. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  3040. {
  3041. value = ctrlEvent.value*127.0f/100.0f;
  3042. setVolumeRT(value, true);
  3043. }
  3044. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  3045. {
  3046. float left, right;
  3047. value = ctrlEvent.value/0.5f - 1.0f;
  3048. if (value < 0.0f)
  3049. {
  3050. left = -1.0f;
  3051. right = (value*2.0f)+1.0f;
  3052. }
  3053. else if (value > 0.0f)
  3054. {
  3055. left = (value*2.0f)-1.0f;
  3056. right = 1.0f;
  3057. }
  3058. else
  3059. {
  3060. left = -1.0f;
  3061. right = 1.0f;
  3062. }
  3063. setBalanceLeftRT(left, true);
  3064. setBalanceRightRT(right, true);
  3065. }
  3066. }
  3067. #endif
  3068. // Control plugin parameters
  3069. uint32_t k;
  3070. for (k=0; k < pData->param.count; ++k)
  3071. {
  3072. if (pData->param.data[k].midiChannel != event.channel)
  3073. continue;
  3074. if (pData->param.data[k].midiCC != ctrlEvent.param)
  3075. continue;
  3076. if (pData->param.data[k].type != PARAMETER_INPUT)
  3077. continue;
  3078. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  3079. continue;
  3080. if (pData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  3081. {
  3082. value = (ctrlEvent.value < 0.5f) ? pData->param.ranges[k].min : pData->param.ranges[k].max;
  3083. }
  3084. else
  3085. {
  3086. if (pData->param.data[k].hints & PARAMETER_IS_LOGARITHMIC)
  3087. value = pData->param.ranges[k].getUnnormalizedLogValue(ctrlEvent.value);
  3088. else
  3089. value = pData->param.ranges[k].getUnnormalizedValue(ctrlEvent.value);
  3090. if (pData->param.data[k].hints & PARAMETER_IS_INTEGER)
  3091. value = std::rint(value);
  3092. }
  3093. setParameterValueRT(k, value, true);
  3094. }
  3095. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param < MAX_MIDI_CONTROL)
  3096. {
  3097. uint8_t midiData[3];
  3098. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  3099. midiData[1] = uint8_t(ctrlEvent.param);
  3100. midiData[2] = uint8_t(ctrlEvent.value*127.0f);
  3101. const uint32_t mtime(isSampleAccurate ? startTime : eventTime);
  3102. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  3103. lv2_atom_buffer_write(&evInAtomIters[fEventsIn.ctrlIndex], mtime, 0, kUridMidiEvent, 3, midiData);
  3104. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  3105. lv2_event_write(&evInEventIters[fEventsIn.ctrlIndex], mtime, 0, kUridMidiEvent, 3, midiData);
  3106. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  3107. lv2midi_put_event(&evInMidiStates[fEventsIn.ctrlIndex], mtime, 3, midiData);
  3108. }
  3109. break;
  3110. } // case kEngineControlEventTypeParameter
  3111. case kEngineControlEventTypeMidiBank:
  3112. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  3113. {
  3114. if (event.channel == pData->ctrlChannel)
  3115. nextBankId = ctrlEvent.param;
  3116. }
  3117. else if (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES)
  3118. {
  3119. uint8_t midiData[3];
  3120. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  3121. midiData[1] = MIDI_CONTROL_BANK_SELECT;
  3122. midiData[2] = uint8_t(ctrlEvent.param);
  3123. const uint32_t mtime(isSampleAccurate ? startTime : eventTime);
  3124. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  3125. lv2_atom_buffer_write(&evInAtomIters[fEventsIn.ctrlIndex], mtime, 0, kUridMidiEvent, 3, midiData);
  3126. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  3127. lv2_event_write(&evInEventIters[fEventsIn.ctrlIndex], mtime, 0, kUridMidiEvent, 3, midiData);
  3128. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  3129. lv2midi_put_event(&evInMidiStates[fEventsIn.ctrlIndex], mtime, 3, midiData);
  3130. }
  3131. break;
  3132. case kEngineControlEventTypeMidiProgram:
  3133. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  3134. {
  3135. if (event.channel == pData->ctrlChannel)
  3136. {
  3137. const uint32_t nextProgramId(ctrlEvent.param);
  3138. for (uint32_t k=0; k < pData->midiprog.count; ++k)
  3139. {
  3140. if (pData->midiprog.data[k].bank == nextBankId && pData->midiprog.data[k].program == nextProgramId)
  3141. {
  3142. setMidiProgramRT(k, true);
  3143. break;
  3144. }
  3145. }
  3146. }
  3147. }
  3148. else if (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES)
  3149. {
  3150. uint8_t midiData[2];
  3151. midiData[0] = uint8_t(MIDI_STATUS_PROGRAM_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  3152. midiData[1] = uint8_t(ctrlEvent.param);
  3153. const uint32_t mtime(isSampleAccurate ? startTime : eventTime);
  3154. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  3155. lv2_atom_buffer_write(&evInAtomIters[fEventsIn.ctrlIndex], mtime, 0, kUridMidiEvent, 2, midiData);
  3156. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  3157. lv2_event_write(&evInEventIters[fEventsIn.ctrlIndex], mtime, 0, kUridMidiEvent, 2, midiData);
  3158. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  3159. lv2midi_put_event(&evInMidiStates[fEventsIn.ctrlIndex], mtime, 2, midiData);
  3160. }
  3161. break;
  3162. case kEngineControlEventTypeAllSoundOff:
  3163. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  3164. {
  3165. const uint32_t mtime(isSampleAccurate ? startTime : eventTime);
  3166. uint8_t midiData[3];
  3167. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  3168. midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  3169. midiData[2] = 0;
  3170. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  3171. lv2_atom_buffer_write(&evInAtomIters[fEventsIn.ctrlIndex], mtime, 0, kUridMidiEvent, 3, midiData);
  3172. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  3173. lv2_event_write(&evInEventIters[fEventsIn.ctrlIndex], mtime, 0, kUridMidiEvent, 3, midiData);
  3174. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  3175. lv2midi_put_event(&evInMidiStates[fEventsIn.ctrlIndex], mtime, 3, midiData);
  3176. }
  3177. break;
  3178. case kEngineControlEventTypeAllNotesOff:
  3179. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  3180. {
  3181. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  3182. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  3183. {
  3184. allNotesOffSent = true;
  3185. postponeRtAllNotesOff();
  3186. }
  3187. #endif
  3188. const uint32_t mtime(isSampleAccurate ? startTime : eventTime);
  3189. uint8_t midiData[3];
  3190. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  3191. midiData[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  3192. midiData[2] = 0;
  3193. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  3194. lv2_atom_buffer_write(&evInAtomIters[fEventsIn.ctrlIndex], mtime, 0, kUridMidiEvent, 3, midiData);
  3195. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  3196. lv2_event_write(&evInEventIters[fEventsIn.ctrlIndex], mtime, 0, kUridMidiEvent, 3, midiData);
  3197. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  3198. lv2midi_put_event(&evInMidiStates[fEventsIn.ctrlIndex], mtime, 3, midiData);
  3199. }
  3200. break;
  3201. } // switch (ctrlEvent.type)
  3202. break;
  3203. } // case kEngineEventTypeControl
  3204. case kEngineEventTypeMidi: {
  3205. const EngineMidiEvent& midiEvent(event.midi);
  3206. const uint8_t* const midiData(midiEvent.size > EngineMidiEvent::kDataSize ? midiEvent.dataExt : midiEvent.data);
  3207. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiData));
  3208. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  3209. continue;
  3210. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  3211. continue;
  3212. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  3213. continue;
  3214. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  3215. continue;
  3216. // Fix bad note-off (per LV2 spec)
  3217. if (status == MIDI_STATUS_NOTE_ON && midiData[2] == 0)
  3218. status = MIDI_STATUS_NOTE_OFF;
  3219. const uint32_t j = fEventsIn.ctrlIndex;
  3220. const uint32_t mtime = isSampleAccurate ? startTime : eventTime;
  3221. // put back channel in data
  3222. uint8_t midiData2[midiEvent.size];
  3223. midiData2[0] = uint8_t(status | (event.channel & MIDI_CHANNEL_BIT));
  3224. std::memcpy(midiData2+1, midiData+1, static_cast<std::size_t>(midiEvent.size-1));
  3225. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  3226. lv2_atom_buffer_write(&evInAtomIters[j], mtime, 0, kUridMidiEvent, midiEvent.size, midiData2);
  3227. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  3228. lv2_event_write(&evInEventIters[j], mtime, 0, kUridMidiEvent, midiEvent.size, midiData2);
  3229. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  3230. lv2midi_put_event(&evInMidiStates[j], mtime, midiEvent.size, midiData2);
  3231. if (status == MIDI_STATUS_NOTE_ON)
  3232. {
  3233. pData->postponeRtEvent(kPluginPostRtEventNoteOn,
  3234. true,
  3235. event.channel,
  3236. midiData[1],
  3237. midiData[2],
  3238. 0.0f);
  3239. }
  3240. else if (status == MIDI_STATUS_NOTE_OFF)
  3241. {
  3242. pData->postponeRtEvent(kPluginPostRtEventNoteOff,
  3243. true,
  3244. event.channel,
  3245. midiData[1],
  3246. 0, 0.0f);
  3247. }
  3248. } break;
  3249. } // switch (event.type)
  3250. }
  3251. pData->postRtEvents.trySplice();
  3252. if (frames > timeOffset)
  3253. processSingle(audioIn, audioOut, cvIn, cvOut, frames - timeOffset, timeOffset);
  3254. } // End of Event Input and Processing
  3255. // --------------------------------------------------------------------------------------------------------
  3256. // Plugin processing (no events)
  3257. else
  3258. {
  3259. processSingle(audioIn, audioOut, cvIn, cvOut, frames, 0);
  3260. } // End of Plugin processing (no events)
  3261. // --------------------------------------------------------------------------------------------------------
  3262. // Events/MIDI Output
  3263. for (uint32_t i=0; i < fEventsOut.count; ++i)
  3264. {
  3265. uint32_t lastFrame = 0;
  3266. Lv2EventData& evData(fEventsOut.data[i]);
  3267. if (evData.type & CARLA_EVENT_DATA_ATOM)
  3268. {
  3269. const LV2_Atom_Event* ev;
  3270. LV2_Atom_Buffer_Iterator iter;
  3271. uint8_t* data;
  3272. lv2_atom_buffer_begin(&iter, evData.atom);
  3273. for (;;)
  3274. {
  3275. data = nullptr;
  3276. ev = lv2_atom_buffer_get(&iter, &data);
  3277. if (ev == nullptr || ev->body.size == 0 || data == nullptr)
  3278. break;
  3279. if (ev->body.type == kUridMidiEvent)
  3280. {
  3281. if (evData.port != nullptr)
  3282. {
  3283. CARLA_SAFE_ASSERT_CONTINUE(ev->time.frames >= 0);
  3284. CARLA_SAFE_ASSERT_CONTINUE(ev->body.size < 0xFF);
  3285. uint32_t currentFrame = static_cast<uint32_t>(ev->time.frames);
  3286. if (currentFrame < lastFrame)
  3287. currentFrame = lastFrame;
  3288. else if (currentFrame >= frames)
  3289. currentFrame = frames - 1;
  3290. evData.port->writeMidiEvent(currentFrame, static_cast<uint8_t>(ev->body.size), data);
  3291. }
  3292. }
  3293. else if (fAtomBufferUiOutTmpData != nullptr)
  3294. {
  3295. fAtomBufferUiOut.put(&ev->body, evData.rindex);
  3296. }
  3297. lv2_atom_buffer_increment(&iter);
  3298. }
  3299. }
  3300. else if ((evData.type & CARLA_EVENT_DATA_EVENT) != 0 && evData.port != nullptr)
  3301. {
  3302. const LV2_Event* ev;
  3303. LV2_Event_Iterator iter;
  3304. uint8_t* data;
  3305. lv2_event_begin(&iter, evData.event);
  3306. for (;;)
  3307. {
  3308. data = nullptr;
  3309. ev = lv2_event_get(&iter, &data);
  3310. if (ev == nullptr || data == nullptr)
  3311. break;
  3312. uint32_t currentFrame = ev->frames;
  3313. if (currentFrame < lastFrame)
  3314. currentFrame = lastFrame;
  3315. else if (currentFrame >= frames)
  3316. currentFrame = frames - 1;
  3317. if (ev->type == kUridMidiEvent)
  3318. {
  3319. CARLA_SAFE_ASSERT_CONTINUE(ev->size < 0xFF);
  3320. evData.port->writeMidiEvent(currentFrame, static_cast<uint8_t>(ev->size), data);
  3321. }
  3322. lv2_event_increment(&iter);
  3323. }
  3324. }
  3325. else if ((evData.type & CARLA_EVENT_DATA_MIDI_LL) != 0 && evData.port != nullptr)
  3326. {
  3327. LV2_MIDIState state = { &evData.midi, frames, 0 };
  3328. uint32_t eventSize;
  3329. double eventTime;
  3330. uchar* eventData;
  3331. for (;;)
  3332. {
  3333. eventSize = 0;
  3334. eventTime = 0.0;
  3335. eventData = nullptr;
  3336. lv2midi_get_event(&state, &eventTime, &eventSize, &eventData);
  3337. if (eventData == nullptr || eventSize == 0)
  3338. break;
  3339. CARLA_SAFE_ASSERT_CONTINUE(eventSize < 0xFF);
  3340. CARLA_SAFE_ASSERT_CONTINUE(eventTime >= 0.0);
  3341. evData.port->writeMidiEvent(static_cast<uint32_t>(eventTime), static_cast<uint8_t>(eventSize), eventData);
  3342. lv2midi_step(&state);
  3343. }
  3344. }
  3345. }
  3346. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  3347. // --------------------------------------------------------------------------------------------------------
  3348. // Control Output
  3349. if (pData->event.portOut != nullptr)
  3350. {
  3351. uint8_t channel;
  3352. uint16_t param;
  3353. float value;
  3354. for (uint32_t k=0; k < pData->param.count; ++k)
  3355. {
  3356. if (pData->param.data[k].type != PARAMETER_OUTPUT)
  3357. continue;
  3358. if (fStrictBounds >= 0 && (pData->param.data[k].hints & PARAMETER_IS_STRICT_BOUNDS) != 0)
  3359. // plugin is responsible to ensure correct bounds
  3360. pData->param.ranges[k].fixValue(fParamBuffers[k]);
  3361. if (pData->param.data[k].midiCC > 0)
  3362. {
  3363. channel = pData->param.data[k].midiChannel;
  3364. param = static_cast<uint16_t>(pData->param.data[k].midiCC);
  3365. value = pData->param.ranges[k].getNormalizedValue(fParamBuffers[k]);
  3366. pData->event.portOut->writeControlEvent(0, channel, kEngineControlEventTypeParameter, param, value);
  3367. }
  3368. }
  3369. } // End of Control Output
  3370. #endif
  3371. // --------------------------------------------------------------------------------------------------------
  3372. // Final work
  3373. if (fEventsIn.ctrl != nullptr && fExt.worker != nullptr && fAtomBufferWorkerResp.tryLock())
  3374. {
  3375. if (fAtomBufferWorkerResp.isDataAvailableForReading())
  3376. {
  3377. const LV2_Atom* atom;
  3378. uint32_t portIndex;
  3379. for (; fAtomBufferWorkerResp.get(atom, portIndex);)
  3380. {
  3381. CARLA_SAFE_ASSERT_CONTINUE(atom->type == kUridCarlaAtomWorkerResp);
  3382. fExt.worker->work_response(fHandle, atom->size, LV2_ATOM_BODY_CONST(atom));
  3383. }
  3384. }
  3385. fAtomBufferWorkerResp.unlock();
  3386. }
  3387. if (fExt.worker != nullptr && fExt.worker->end_run != nullptr)
  3388. {
  3389. fExt.worker->end_run(fHandle);
  3390. if (fHandle2 != nullptr)
  3391. fExt.worker->end_run(fHandle2);
  3392. }
  3393. fFirstActive = false;
  3394. // --------------------------------------------------------------------------------------------------------
  3395. }
  3396. bool processSingle(const float** const audioIn, float** const audioOut, const float** const cvIn, float** const cvOut, const uint32_t frames, const uint32_t timeOffset)
  3397. {
  3398. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  3399. if (pData->audioIn.count > 0)
  3400. {
  3401. CARLA_SAFE_ASSERT_RETURN(audioIn != nullptr, false);
  3402. CARLA_SAFE_ASSERT_RETURN(fAudioInBuffers != nullptr, false);
  3403. }
  3404. if (pData->audioOut.count > 0)
  3405. {
  3406. CARLA_SAFE_ASSERT_RETURN(audioOut != nullptr, false);
  3407. CARLA_SAFE_ASSERT_RETURN(fAudioOutBuffers != nullptr, false);
  3408. }
  3409. if (pData->cvIn.count > 0)
  3410. {
  3411. CARLA_SAFE_ASSERT_RETURN(cvIn != nullptr, false);
  3412. }
  3413. if (pData->cvOut.count > 0)
  3414. {
  3415. CARLA_SAFE_ASSERT_RETURN(cvOut != nullptr, false);
  3416. }
  3417. // --------------------------------------------------------------------------------------------------------
  3418. // Try lock, silence otherwise
  3419. #ifndef STOAT_TEST_BUILD
  3420. if (pData->engine->isOffline())
  3421. {
  3422. pData->singleMutex.lock();
  3423. }
  3424. else
  3425. #endif
  3426. if (! pData->singleMutex.tryLock())
  3427. {
  3428. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  3429. {
  3430. for (uint32_t k=0; k < frames; ++k)
  3431. audioOut[i][k+timeOffset] = 0.0f;
  3432. }
  3433. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  3434. {
  3435. for (uint32_t k=0; k < frames; ++k)
  3436. cvOut[i][k+timeOffset] = 0.0f;
  3437. }
  3438. return false;
  3439. }
  3440. // --------------------------------------------------------------------------------------------------------
  3441. // Set audio buffers
  3442. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  3443. carla_copyFloats(fAudioInBuffers[i], audioIn[i]+timeOffset, frames);
  3444. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  3445. carla_zeroFloats(fAudioOutBuffers[i], frames);
  3446. // --------------------------------------------------------------------------------------------------------
  3447. // Set CV buffers
  3448. for (uint32_t i=0; i < pData->cvIn.count; ++i)
  3449. carla_copyFloats(fCvInBuffers[i], cvIn[i]+timeOffset, frames);
  3450. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  3451. carla_zeroFloats(fCvOutBuffers[i], frames);
  3452. // --------------------------------------------------------------------------------------------------------
  3453. // Run plugin
  3454. fDescriptor->run(fHandle, frames);
  3455. if (fHandle2 != nullptr)
  3456. fDescriptor->run(fHandle2, frames);
  3457. // --------------------------------------------------------------------------------------------------------
  3458. // Handle trigger parameters
  3459. for (uint32_t k=0; k < pData->param.count; ++k)
  3460. {
  3461. if (pData->param.data[k].type != PARAMETER_INPUT)
  3462. continue;
  3463. if (pData->param.data[k].hints & PARAMETER_IS_TRIGGER)
  3464. {
  3465. if (carla_isNotEqual(fParamBuffers[k], pData->param.ranges[k].def))
  3466. {
  3467. fParamBuffers[k] = pData->param.ranges[k].def;
  3468. pData->postponeRtEvent(kPluginPostRtEventParameterChange,
  3469. true,
  3470. static_cast<int32_t>(k),
  3471. 1, 0,
  3472. fParamBuffers[k]);
  3473. }
  3474. }
  3475. }
  3476. pData->postRtEvents.trySplice();
  3477. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  3478. // --------------------------------------------------------------------------------------------------------
  3479. // Post-processing (dry/wet, volume and balance)
  3480. {
  3481. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  3482. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  3483. const bool isMono = (pData->audioIn.count == 1);
  3484. bool isPair;
  3485. float bufValue, oldBufLeft[doBalance ? frames : 1];
  3486. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  3487. {
  3488. // Dry/Wet
  3489. if (doDryWet)
  3490. {
  3491. const uint32_t c = isMono ? 0 : i;
  3492. for (uint32_t k=0; k < frames; ++k)
  3493. {
  3494. # ifndef BUILD_BRIDGE
  3495. if (k < pData->latency.frames && pData->latency.buffers != nullptr)
  3496. bufValue = pData->latency.buffers[c][k];
  3497. else if (pData->latency.frames < frames)
  3498. bufValue = fAudioInBuffers[c][k-pData->latency.frames];
  3499. else
  3500. # endif
  3501. bufValue = fAudioInBuffers[c][k];
  3502. fAudioOutBuffers[i][k] = (fAudioOutBuffers[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  3503. }
  3504. }
  3505. // Balance
  3506. if (doBalance)
  3507. {
  3508. isPair = (i % 2 == 0);
  3509. if (isPair)
  3510. {
  3511. CARLA_ASSERT(i+1 < pData->audioOut.count);
  3512. carla_copyFloats(oldBufLeft, fAudioOutBuffers[i], frames);
  3513. }
  3514. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  3515. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  3516. for (uint32_t k=0; k < frames; ++k)
  3517. {
  3518. if (isPair)
  3519. {
  3520. // left
  3521. fAudioOutBuffers[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  3522. fAudioOutBuffers[i][k] += fAudioOutBuffers[i+1][k] * (1.0f - balRangeR);
  3523. }
  3524. else
  3525. {
  3526. // right
  3527. fAudioOutBuffers[i][k] = fAudioOutBuffers[i][k] * balRangeR;
  3528. fAudioOutBuffers[i][k] += oldBufLeft[k] * balRangeL;
  3529. }
  3530. }
  3531. }
  3532. // Volume (and buffer copy)
  3533. {
  3534. for (uint32_t k=0; k < frames; ++k)
  3535. audioOut[i][k+timeOffset] = fAudioOutBuffers[i][k] * pData->postProc.volume;
  3536. }
  3537. }
  3538. } // End of Post-processing
  3539. # ifndef BUILD_BRIDGE
  3540. // --------------------------------------------------------------------------------------------------------
  3541. // Save latency values for next callback
  3542. if (pData->latency.frames != 0 && pData->latency.buffers != nullptr)
  3543. {
  3544. CARLA_SAFE_ASSERT(timeOffset == 0);
  3545. const uint32_t latframes = pData->latency.frames;
  3546. if (latframes <= frames)
  3547. {
  3548. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  3549. carla_copyFloats(pData->latency.buffers[i], audioIn[i]+(frames-latframes), latframes);
  3550. }
  3551. else
  3552. {
  3553. const uint32_t diff = latframes - frames;
  3554. for (uint32_t i=0, k; i<pData->audioIn.count; ++i)
  3555. {
  3556. // push back buffer by 'frames'
  3557. for (k=0; k < diff; ++k)
  3558. pData->latency.buffers[i][k] = pData->latency.buffers[i][k+frames];
  3559. // put current input at the end
  3560. for (uint32_t j=0; k < latframes; ++j, ++k)
  3561. pData->latency.buffers[i][k] = audioIn[i][j];
  3562. }
  3563. }
  3564. }
  3565. # endif
  3566. #else // BUILD_BRIDGE_ALTERNATIVE_ARCH
  3567. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  3568. {
  3569. for (uint32_t k=0; k < frames; ++k)
  3570. audioOut[i][k+timeOffset] = fAudioOutBuffers[i][k];
  3571. }
  3572. #endif
  3573. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  3574. {
  3575. for (uint32_t k=0; k < frames; ++k)
  3576. cvOut[i][k+timeOffset] = fCvOutBuffers[i][k];
  3577. }
  3578. // --------------------------------------------------------------------------------------------------------
  3579. pData->singleMutex.unlock();
  3580. return true;
  3581. }
  3582. void bufferSizeChanged(const uint32_t newBufferSize) override
  3583. {
  3584. CARLA_ASSERT_INT(newBufferSize > 0, newBufferSize);
  3585. carla_debug("CarlaPluginLV2::bufferSizeChanged(%i) - start", newBufferSize);
  3586. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  3587. {
  3588. if (fAudioInBuffers[i] != nullptr)
  3589. delete[] fAudioInBuffers[i];
  3590. fAudioInBuffers[i] = new float[newBufferSize];
  3591. }
  3592. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  3593. {
  3594. if (fAudioOutBuffers[i] != nullptr)
  3595. delete[] fAudioOutBuffers[i];
  3596. fAudioOutBuffers[i] = new float[newBufferSize];
  3597. }
  3598. if (fHandle2 == nullptr)
  3599. {
  3600. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  3601. {
  3602. CARLA_ASSERT(fAudioInBuffers[i] != nullptr);
  3603. fDescriptor->connect_port(fHandle, pData->audioIn.ports[i].rindex, fAudioInBuffers[i]);
  3604. }
  3605. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  3606. {
  3607. CARLA_ASSERT(fAudioOutBuffers[i] != nullptr);
  3608. fDescriptor->connect_port(fHandle, pData->audioOut.ports[i].rindex, fAudioOutBuffers[i]);
  3609. }
  3610. }
  3611. else
  3612. {
  3613. if (pData->audioIn.count > 0)
  3614. {
  3615. CARLA_ASSERT(pData->audioIn.count == 2);
  3616. CARLA_ASSERT(fAudioInBuffers[0] != nullptr);
  3617. CARLA_ASSERT(fAudioInBuffers[1] != nullptr);
  3618. fDescriptor->connect_port(fHandle, pData->audioIn.ports[0].rindex, fAudioInBuffers[0]);
  3619. fDescriptor->connect_port(fHandle2, pData->audioIn.ports[1].rindex, fAudioInBuffers[1]);
  3620. }
  3621. if (pData->audioOut.count > 0)
  3622. {
  3623. CARLA_ASSERT(pData->audioOut.count == 2);
  3624. CARLA_ASSERT(fAudioOutBuffers[0] != nullptr);
  3625. CARLA_ASSERT(fAudioOutBuffers[1] != nullptr);
  3626. fDescriptor->connect_port(fHandle, pData->audioOut.ports[0].rindex, fAudioOutBuffers[0]);
  3627. fDescriptor->connect_port(fHandle2, pData->audioOut.ports[1].rindex, fAudioOutBuffers[1]);
  3628. }
  3629. }
  3630. for (uint32_t i=0; i < pData->cvIn.count; ++i)
  3631. {
  3632. if (fCvInBuffers[i] != nullptr)
  3633. delete[] fCvInBuffers[i];
  3634. fCvInBuffers[i] = new float[newBufferSize];
  3635. fDescriptor->connect_port(fHandle, pData->cvIn.ports[i].rindex, fCvInBuffers[i]);
  3636. if (fHandle2 != nullptr)
  3637. fDescriptor->connect_port(fHandle2, pData->cvIn.ports[i].rindex, fCvInBuffers[i]);
  3638. }
  3639. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  3640. {
  3641. if (fCvOutBuffers[i] != nullptr)
  3642. delete[] fCvOutBuffers[i];
  3643. fCvOutBuffers[i] = new float[newBufferSize];
  3644. fDescriptor->connect_port(fHandle, pData->cvOut.ports[i].rindex, fCvOutBuffers[i]);
  3645. if (fHandle2 != nullptr)
  3646. fDescriptor->connect_port(fHandle2, pData->cvOut.ports[i].rindex, fCvOutBuffers[i]);
  3647. }
  3648. const int newBufferSizeInt(static_cast<int>(newBufferSize));
  3649. if (fLv2Options.maxBufferSize != newBufferSizeInt || (fLv2Options.minBufferSize != 1 && fLv2Options.minBufferSize != newBufferSizeInt))
  3650. {
  3651. fLv2Options.maxBufferSize = fLv2Options.nominalBufferSize = newBufferSizeInt;
  3652. if (fLv2Options.minBufferSize != 1)
  3653. fLv2Options.minBufferSize = newBufferSizeInt;
  3654. if (fExt.options != nullptr && fExt.options->set != nullptr)
  3655. {
  3656. fExt.options->set(fHandle, &fLv2Options.opts[CarlaPluginLV2Options::MaxBlockLenth]);
  3657. fExt.options->set(fHandle, &fLv2Options.opts[CarlaPluginLV2Options::NominalBlockLenth]);
  3658. if (fLv2Options.minBufferSize != 1)
  3659. fExt.options->set(fHandle, &fLv2Options.opts[CarlaPluginLV2Options::MinBlockLenth]);
  3660. }
  3661. }
  3662. carla_debug("CarlaPluginLV2::bufferSizeChanged(%i) - end", newBufferSize);
  3663. }
  3664. void sampleRateChanged(const double newSampleRate) override
  3665. {
  3666. CARLA_ASSERT_INT(newSampleRate > 0.0, newSampleRate);
  3667. carla_debug("CarlaPluginLV2::sampleRateChanged(%g) - start", newSampleRate);
  3668. const float sampleRatef = static_cast<float>(newSampleRate);
  3669. if (carla_isNotEqual(fLv2Options.sampleRate, sampleRatef))
  3670. {
  3671. fLv2Options.sampleRate = sampleRatef;
  3672. if (fExt.options != nullptr && fExt.options->set != nullptr)
  3673. {
  3674. LV2_Options_Option options[2];
  3675. carla_zeroStructs(options, 2);
  3676. LV2_Options_Option& optSampleRate(options[0]);
  3677. optSampleRate.context = LV2_OPTIONS_INSTANCE;
  3678. optSampleRate.subject = 0;
  3679. optSampleRate.key = kUridParamSampleRate;
  3680. optSampleRate.size = sizeof(float);
  3681. optSampleRate.type = kUridAtomFloat;
  3682. optSampleRate.value = &fLv2Options.sampleRate;
  3683. fExt.options->set(fHandle, options);
  3684. }
  3685. }
  3686. for (uint32_t k=0; k < pData->param.count; ++k)
  3687. {
  3688. if (pData->param.data[k].type != PARAMETER_INPUT)
  3689. continue;
  3690. if (pData->param.special[k] != PARAMETER_SPECIAL_SAMPLE_RATE)
  3691. continue;
  3692. fParamBuffers[k] = sampleRatef;
  3693. pData->postponeRtEvent(kPluginPostRtEventParameterChange,
  3694. true,
  3695. static_cast<int32_t>(k),
  3696. 0,
  3697. 0,
  3698. fParamBuffers[k]);
  3699. break;
  3700. }
  3701. carla_debug("CarlaPluginLV2::sampleRateChanged(%g) - end", newSampleRate);
  3702. }
  3703. void offlineModeChanged(const bool isOffline) override
  3704. {
  3705. for (uint32_t k=0; k < pData->param.count; ++k)
  3706. {
  3707. if (pData->param.data[k].type == PARAMETER_INPUT && pData->param.special[k] == PARAMETER_SPECIAL_FREEWHEEL)
  3708. {
  3709. fParamBuffers[k] = isOffline ? pData->param.ranges[k].max : pData->param.ranges[k].min;
  3710. pData->postponeRtEvent(kPluginPostRtEventParameterChange,
  3711. true,
  3712. static_cast<int32_t>(k),
  3713. 0,
  3714. 0,
  3715. fParamBuffers[k]);
  3716. break;
  3717. }
  3718. }
  3719. }
  3720. // -------------------------------------------------------------------
  3721. // Plugin buffers
  3722. void initBuffers() const noexcept override
  3723. {
  3724. fEventsIn.initBuffers();
  3725. fEventsOut.initBuffers();
  3726. CarlaPlugin::initBuffers();
  3727. }
  3728. void clearBuffers() noexcept override
  3729. {
  3730. carla_debug("CarlaPluginLV2::clearBuffers() - start");
  3731. if (fAudioInBuffers != nullptr)
  3732. {
  3733. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  3734. {
  3735. if (fAudioInBuffers[i] != nullptr)
  3736. {
  3737. delete[] fAudioInBuffers[i];
  3738. fAudioInBuffers[i] = nullptr;
  3739. }
  3740. }
  3741. delete[] fAudioInBuffers;
  3742. fAudioInBuffers = nullptr;
  3743. }
  3744. if (fAudioOutBuffers != nullptr)
  3745. {
  3746. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  3747. {
  3748. if (fAudioOutBuffers[i] != nullptr)
  3749. {
  3750. delete[] fAudioOutBuffers[i];
  3751. fAudioOutBuffers[i] = nullptr;
  3752. }
  3753. }
  3754. delete[] fAudioOutBuffers;
  3755. fAudioOutBuffers = nullptr;
  3756. }
  3757. if (fCvInBuffers != nullptr)
  3758. {
  3759. for (uint32_t i=0; i < pData->cvIn.count; ++i)
  3760. {
  3761. if (fCvInBuffers[i] != nullptr)
  3762. {
  3763. delete[] fCvInBuffers[i];
  3764. fCvInBuffers[i] = nullptr;
  3765. }
  3766. }
  3767. delete[] fCvInBuffers;
  3768. fCvInBuffers = nullptr;
  3769. }
  3770. if (fCvOutBuffers != nullptr)
  3771. {
  3772. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  3773. {
  3774. if (fCvOutBuffers[i] != nullptr)
  3775. {
  3776. delete[] fCvOutBuffers[i];
  3777. fCvOutBuffers[i] = nullptr;
  3778. }
  3779. }
  3780. delete[] fCvOutBuffers;
  3781. fCvOutBuffers = nullptr;
  3782. }
  3783. if (fParamBuffers != nullptr)
  3784. {
  3785. delete[] fParamBuffers;
  3786. fParamBuffers = nullptr;
  3787. }
  3788. fEventsIn.clear();
  3789. fEventsOut.clear();
  3790. CarlaPlugin::clearBuffers();
  3791. carla_debug("CarlaPluginLV2::clearBuffers() - end");
  3792. }
  3793. // -------------------------------------------------------------------
  3794. // Post-poned UI Stuff
  3795. void uiParameterChange(const uint32_t index, const float value) noexcept override
  3796. {
  3797. CARLA_SAFE_ASSERT_RETURN(fUI.type != UI::TYPE_NULL || fFilePathURI.isNotEmpty(),);
  3798. CARLA_SAFE_ASSERT_RETURN(index < pData->param.count,);
  3799. if (fUI.type == UI::TYPE_BRIDGE)
  3800. {
  3801. if (fPipeServer.isPipeRunning())
  3802. fPipeServer.writeControlMessage(static_cast<uint32_t>(pData->param.data[index].rindex), value);
  3803. }
  3804. else
  3805. {
  3806. if (fUI.handle != nullptr && fUI.descriptor != nullptr && fUI.descriptor->port_event != nullptr && ! fNeedsUiClose)
  3807. {
  3808. CARLA_SAFE_ASSERT_RETURN(pData->param.data[index].rindex >= 0,);
  3809. fUI.descriptor->port_event(fUI.handle, static_cast<uint32_t>(pData->param.data[index].rindex), sizeof(float), kUridNull, &value);
  3810. }
  3811. }
  3812. }
  3813. void uiMidiProgramChange(const uint32_t index) noexcept override
  3814. {
  3815. CARLA_SAFE_ASSERT_RETURN(fUI.type != UI::TYPE_NULL || fFilePathURI.isNotEmpty(),);
  3816. CARLA_SAFE_ASSERT_RETURN(index < pData->midiprog.count,);
  3817. if (fUI.type == UI::TYPE_BRIDGE)
  3818. {
  3819. if (fPipeServer.isPipeRunning())
  3820. fPipeServer.writeMidiProgramMessage(pData->midiprog.data[index].bank, pData->midiprog.data[index].program);
  3821. }
  3822. else
  3823. {
  3824. if (fExt.uiprograms != nullptr && fExt.uiprograms->select_program != nullptr && ! fNeedsUiClose)
  3825. fExt.uiprograms->select_program(fUI.handle, pData->midiprog.data[index].bank, pData->midiprog.data[index].program);
  3826. }
  3827. }
  3828. void uiNoteOn(const uint8_t channel, const uint8_t note, const uint8_t velo) noexcept override
  3829. {
  3830. CARLA_SAFE_ASSERT_RETURN(fUI.type != UI::TYPE_NULL || fFilePathURI.isNotEmpty(),);
  3831. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  3832. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  3833. CARLA_SAFE_ASSERT_RETURN(velo > 0 && velo < MAX_MIDI_VALUE,);
  3834. #if 0
  3835. if (fUI.type == UI::TYPE_BRIDGE)
  3836. {
  3837. if (fPipeServer.isPipeRunning())
  3838. fPipeServer.writeMidiNoteMessage(false, channel, note, velo);
  3839. }
  3840. else
  3841. {
  3842. if (fUI.handle != nullptr && fUI.descriptor != nullptr && fUI.descriptor->port_event != nullptr && fEventsIn.ctrl != nullptr && ! fNeedsUiClose)
  3843. {
  3844. LV2_Atom_MidiEvent midiEv;
  3845. midiEv.atom.type = kUridMidiEvent;
  3846. midiEv.atom.size = 3;
  3847. midiEv.data[0] = uint8_t(MIDI_STATUS_NOTE_ON | (channel & MIDI_CHANNEL_BIT));
  3848. midiEv.data[1] = note;
  3849. midiEv.data[2] = velo;
  3850. fUI.descriptor->port_event(fUI.handle, fEventsIn.ctrl->rindex, lv2_atom_total_size(midiEv), kUridAtomTransferEvent, &midiEv);
  3851. }
  3852. }
  3853. #endif
  3854. }
  3855. void uiNoteOff(const uint8_t channel, const uint8_t note) noexcept override
  3856. {
  3857. CARLA_SAFE_ASSERT_RETURN(fUI.type != UI::TYPE_NULL || fFilePathURI.isNotEmpty(),);
  3858. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  3859. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  3860. #if 0
  3861. if (fUI.type == UI::TYPE_BRIDGE)
  3862. {
  3863. if (fPipeServer.isPipeRunning())
  3864. fPipeServer.writeMidiNoteMessage(false, channel, note, 0);
  3865. }
  3866. else
  3867. {
  3868. if (fUI.handle != nullptr && fUI.descriptor != nullptr && fUI.descriptor->port_event != nullptr && fEventsIn.ctrl != nullptr && ! fNeedsUiClose)
  3869. {
  3870. LV2_Atom_MidiEvent midiEv;
  3871. midiEv.atom.type = kUridMidiEvent;
  3872. midiEv.atom.size = 3;
  3873. midiEv.data[0] = uint8_t(MIDI_STATUS_NOTE_OFF | (channel & MIDI_CHANNEL_BIT));
  3874. midiEv.data[1] = note;
  3875. midiEv.data[2] = 0;
  3876. fUI.descriptor->port_event(fUI.handle, fEventsIn.ctrl->rindex, lv2_atom_total_size(midiEv), kUridAtomTransferEvent, &midiEv);
  3877. }
  3878. }
  3879. #endif
  3880. }
  3881. // -------------------------------------------------------------------
  3882. // Internal helper functions
  3883. void restoreLV2State() noexcept override
  3884. {
  3885. if (fExt.state == nullptr)
  3886. return;
  3887. LV2_State_Status status = LV2_STATE_ERR_UNKNOWN;
  3888. {
  3889. const ScopedSingleProcessLocker spl(this, true);
  3890. try {
  3891. status = fExt.state->restore(fHandle, carla_lv2_state_retrieve, this, 0, fFeatures);
  3892. } catch(...) {}
  3893. if (fHandle2 != nullptr)
  3894. {
  3895. try {
  3896. fExt.state->restore(fHandle, carla_lv2_state_retrieve, this, 0, fFeatures);
  3897. } catch(...) {}
  3898. }
  3899. }
  3900. switch (status)
  3901. {
  3902. case LV2_STATE_SUCCESS:
  3903. carla_debug("CarlaPluginLV2::updateLV2State() - success");
  3904. break;
  3905. case LV2_STATE_ERR_UNKNOWN:
  3906. carla_stderr("CarlaPluginLV2::updateLV2State() - unknown error");
  3907. break;
  3908. case LV2_STATE_ERR_BAD_TYPE:
  3909. carla_stderr("CarlaPluginLV2::updateLV2State() - error, bad type");
  3910. break;
  3911. case LV2_STATE_ERR_BAD_FLAGS:
  3912. carla_stderr("CarlaPluginLV2::updateLV2State() - error, bad flags");
  3913. break;
  3914. case LV2_STATE_ERR_NO_FEATURE:
  3915. carla_stderr("CarlaPluginLV2::updateLV2State() - error, missing feature");
  3916. break;
  3917. case LV2_STATE_ERR_NO_PROPERTY:
  3918. carla_stderr("CarlaPluginLV2::updateLV2State() - error, missing property");
  3919. break;
  3920. case LV2_STATE_ERR_NO_SPACE:
  3921. carla_stderr("CarlaPluginLV2::updateLV2State() - error, insufficient space");
  3922. break;
  3923. }
  3924. }
  3925. // -------------------------------------------------------------------
  3926. bool isRealtimeSafe() const noexcept
  3927. {
  3928. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr, false);
  3929. for (uint32_t i=0; i < fRdfDescriptor->FeatureCount; ++i)
  3930. {
  3931. if (std::strcmp(fRdfDescriptor->Features[i].URI, LV2_CORE__hardRTCapable) == 0)
  3932. return true;
  3933. }
  3934. return false;
  3935. }
  3936. // -------------------------------------------------------------------
  3937. bool isUiBridgeable(const uint32_t uiId) const noexcept
  3938. {
  3939. CARLA_SAFE_ASSERT_RETURN(uiId < fRdfDescriptor->UICount, false);
  3940. #ifndef LV2_UIS_ONLY_INPROCESS
  3941. const LV2_RDF_UI* const rdfUI(&fRdfDescriptor->UIs[uiId]);
  3942. for (uint32_t i=0; i < rdfUI->FeatureCount; ++i)
  3943. {
  3944. const LV2_RDF_Feature& feat(rdfUI->Features[i]);
  3945. if (! feat.Required)
  3946. continue;
  3947. if (std::strcmp(feat.URI, LV2_INSTANCE_ACCESS_URI) == 0)
  3948. return false;
  3949. if (std::strcmp(feat.URI, LV2_DATA_ACCESS_URI) == 0)
  3950. return false;
  3951. }
  3952. // Calf UIs are mostly useless without their special graphs
  3953. // but they can be crashy under certain conditions, so follow user preferences
  3954. if (std::strstr(rdfUI->URI, "http://calf.sourceforge.net/plugins/gui/") != nullptr)
  3955. return pData->engine->getOptions().preferUiBridges;
  3956. // LSP-Plugins UIs make heavy use of URIDs, for which carla right now is very slow
  3957. // FIXME after some optimization, remove this
  3958. if (std::strstr(rdfUI->URI, "http://lsp-plug.in/ui/lv2/") != nullptr)
  3959. return false;
  3960. return true;
  3961. #else
  3962. return false;
  3963. #endif
  3964. }
  3965. bool isUiResizable() const noexcept
  3966. {
  3967. CARLA_SAFE_ASSERT_RETURN(fUI.rdfDescriptor != nullptr, false);
  3968. for (uint32_t i=0; i < fUI.rdfDescriptor->FeatureCount; ++i)
  3969. {
  3970. if (std::strcmp(fUI.rdfDescriptor->Features[i].URI, LV2_UI__fixedSize) == 0)
  3971. return false;
  3972. if (std::strcmp(fUI.rdfDescriptor->Features[i].URI, LV2_UI__noUserResize) == 0)
  3973. return false;
  3974. }
  3975. return true;
  3976. }
  3977. const char* getUiBridgeBinary(const LV2_Property type) const
  3978. {
  3979. CarlaString bridgeBinary(pData->engine->getOptions().binaryDir);
  3980. if (bridgeBinary.isEmpty())
  3981. return nullptr;
  3982. switch (type)
  3983. {
  3984. case LV2_UI_GTK2:
  3985. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-gtk2";
  3986. break;
  3987. case LV2_UI_GTK3:
  3988. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-gtk3";
  3989. break;
  3990. case LV2_UI_QT4:
  3991. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-qt4";
  3992. break;
  3993. case LV2_UI_QT5:
  3994. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-qt5";
  3995. break;
  3996. case LV2_UI_COCOA:
  3997. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-cocoa";
  3998. break;
  3999. case LV2_UI_WINDOWS:
  4000. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-windows";
  4001. break;
  4002. case LV2_UI_X11:
  4003. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-x11";
  4004. break;
  4005. case LV2_UI_MOD:
  4006. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-modgui";
  4007. break;
  4008. #if 0
  4009. case LV2_UI_EXTERNAL:
  4010. case LV2_UI_OLD_EXTERNAL:
  4011. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-external";
  4012. break;
  4013. #endif
  4014. default:
  4015. return nullptr;
  4016. }
  4017. #ifdef CARLA_OS_WIN
  4018. bridgeBinary += ".exe";
  4019. #endif
  4020. if (! File(bridgeBinary.buffer()).existsAsFile())
  4021. return nullptr;
  4022. return bridgeBinary.dupSafe();
  4023. }
  4024. // -------------------------------------------------------------------
  4025. void recheckExtensions()
  4026. {
  4027. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr,);
  4028. carla_debug("CarlaPluginLV2::recheckExtensions()");
  4029. fExt.options = nullptr;
  4030. fExt.programs = nullptr;
  4031. fExt.state = nullptr;
  4032. fExt.worker = nullptr;
  4033. fExt.inlineDisplay = nullptr;
  4034. for (uint32_t i=0; i < fRdfDescriptor->ExtensionCount; ++i)
  4035. {
  4036. const char* const extension = fRdfDescriptor->Extensions[i];
  4037. CARLA_SAFE_ASSERT_CONTINUE(extension != nullptr);
  4038. /**/ if (std::strcmp(extension, LV2_OPTIONS__interface) == 0)
  4039. pData->hints |= PLUGIN_HAS_EXTENSION_OPTIONS;
  4040. else if (std::strcmp(extension, LV2_PROGRAMS__Interface) == 0)
  4041. pData->hints |= PLUGIN_HAS_EXTENSION_PROGRAMS;
  4042. else if (std::strcmp(extension, LV2_STATE__interface) == 0)
  4043. pData->hints |= PLUGIN_HAS_EXTENSION_STATE;
  4044. else if (std::strcmp(extension, LV2_WORKER__interface) == 0)
  4045. pData->hints |= PLUGIN_HAS_EXTENSION_WORKER;
  4046. else if (std::strcmp(extension, LV2_INLINEDISPLAY__interface) == 0)
  4047. pData->hints |= PLUGIN_HAS_EXTENSION_INLINE_DISPLAY;
  4048. else if (std::strcmp(extension, LV2_MIDNAM__interface) == 0)
  4049. pData->hints |= PLUGIN_HAS_EXTENSION_MIDNAM;
  4050. else
  4051. carla_stdout("Plugin '%s' has non-supported extension: '%s'", fRdfDescriptor->URI, extension);
  4052. }
  4053. // Fix for broken plugins, nasty!
  4054. for (uint32_t i=0; i < fRdfDescriptor->FeatureCount; ++i)
  4055. {
  4056. const LV2_RDF_Feature& feature(fRdfDescriptor->Features[i]);
  4057. if (std::strcmp(feature.URI, LV2_INLINEDISPLAY__queue_draw) == 0)
  4058. {
  4059. if (pData->hints & PLUGIN_HAS_EXTENSION_INLINE_DISPLAY)
  4060. break;
  4061. carla_stdout("Plugin '%s' uses inline-display but does not set extension data, nasty!", fRdfDescriptor->URI);
  4062. pData->hints |= PLUGIN_HAS_EXTENSION_INLINE_DISPLAY;
  4063. }
  4064. else if (std::strcmp(feature.URI, LV2_MIDNAM__update) == 0)
  4065. {
  4066. if (pData->hints & PLUGIN_HAS_EXTENSION_MIDNAM)
  4067. break;
  4068. carla_stdout("Plugin '%s' uses midnam but does not set extension data, nasty!", fRdfDescriptor->URI);
  4069. pData->hints |= PLUGIN_HAS_EXTENSION_MIDNAM;
  4070. }
  4071. }
  4072. if (fDescriptor->extension_data != nullptr)
  4073. {
  4074. if (pData->hints & PLUGIN_HAS_EXTENSION_OPTIONS)
  4075. fExt.options = (const LV2_Options_Interface*)fDescriptor->extension_data(LV2_OPTIONS__interface);
  4076. if (pData->hints & PLUGIN_HAS_EXTENSION_PROGRAMS)
  4077. fExt.programs = (const LV2_Programs_Interface*)fDescriptor->extension_data(LV2_PROGRAMS__Interface);
  4078. if (pData->hints & PLUGIN_HAS_EXTENSION_STATE)
  4079. fExt.state = (const LV2_State_Interface*)fDescriptor->extension_data(LV2_STATE__interface);
  4080. if (pData->hints & PLUGIN_HAS_EXTENSION_WORKER)
  4081. fExt.worker = (const LV2_Worker_Interface*)fDescriptor->extension_data(LV2_WORKER__interface);
  4082. if (pData->hints & PLUGIN_HAS_EXTENSION_INLINE_DISPLAY)
  4083. fExt.inlineDisplay = (const LV2_Inline_Display_Interface*)fDescriptor->extension_data(LV2_INLINEDISPLAY__interface);
  4084. if (pData->hints & PLUGIN_HAS_EXTENSION_MIDNAM)
  4085. fExt.midnam = (const LV2_Midnam_Interface*)fDescriptor->extension_data(LV2_MIDNAM__interface);
  4086. // check if invalid
  4087. if (fExt.options != nullptr && fExt.options->get == nullptr && fExt.options->set == nullptr)
  4088. fExt.options = nullptr;
  4089. if (fExt.programs != nullptr && (fExt.programs->get_program == nullptr || fExt.programs->select_program == nullptr))
  4090. fExt.programs = nullptr;
  4091. if (fExt.state != nullptr && (fExt.state->save == nullptr || fExt.state->restore == nullptr))
  4092. fExt.state = nullptr;
  4093. if (fExt.worker != nullptr && fExt.worker->work == nullptr)
  4094. fExt.worker = nullptr;
  4095. if (fExt.inlineDisplay != nullptr)
  4096. {
  4097. if (fExt.inlineDisplay->render != nullptr)
  4098. {
  4099. pData->hints |= PLUGIN_HAS_INLINE_DISPLAY;
  4100. pData->setCanDeleteLib(false);
  4101. }
  4102. else
  4103. {
  4104. fExt.inlineDisplay = nullptr;
  4105. }
  4106. }
  4107. if (fExt.midnam != nullptr && fExt.midnam->midnam == nullptr)
  4108. fExt.midnam = nullptr;
  4109. }
  4110. CARLA_SAFE_ASSERT_RETURN(fLatencyIndex == -1,);
  4111. int32_t iCtrl=0;
  4112. for (uint32_t i=0, count=fRdfDescriptor->PortCount; i<count; ++i)
  4113. {
  4114. const LV2_Property portTypes(fRdfDescriptor->Ports[i].Types);
  4115. if (! LV2_IS_PORT_CONTROL(portTypes))
  4116. continue;
  4117. const CarlaScopedValueSetter<int32_t> svs(iCtrl, iCtrl, iCtrl+1);
  4118. if (! LV2_IS_PORT_OUTPUT(portTypes))
  4119. continue;
  4120. const LV2_Property portDesignation(fRdfDescriptor->Ports[i].Designation);
  4121. if (! LV2_IS_PORT_DESIGNATION_LATENCY(portDesignation))
  4122. continue;
  4123. fLatencyIndex = iCtrl;
  4124. break;
  4125. }
  4126. }
  4127. // -------------------------------------------------------------------
  4128. void updateUi()
  4129. {
  4130. CARLA_SAFE_ASSERT_RETURN(fUI.handle != nullptr,);
  4131. CARLA_SAFE_ASSERT_RETURN(fUI.descriptor != nullptr,);
  4132. carla_debug("CarlaPluginLV2::updateUi()");
  4133. // update midi program
  4134. if (fExt.uiprograms != nullptr && pData->midiprog.count > 0 && pData->midiprog.current >= 0)
  4135. {
  4136. const MidiProgramData& curData(pData->midiprog.getCurrent());
  4137. fExt.uiprograms->select_program(fUI.handle, curData.bank, curData.program);
  4138. }
  4139. // update control ports
  4140. if (fUI.descriptor->port_event != nullptr)
  4141. {
  4142. float value;
  4143. for (uint32_t i=0; i < pData->param.count; ++i)
  4144. {
  4145. value = getParameterValue(i);
  4146. fUI.descriptor->port_event(fUI.handle, static_cast<uint32_t>(pData->param.data[i].rindex), sizeof(float), kUridNull, &value);
  4147. }
  4148. }
  4149. }
  4150. // -------------------------------------------------------------------
  4151. LV2_URID getCustomURID(const char* const uri)
  4152. {
  4153. CARLA_SAFE_ASSERT_RETURN(uri != nullptr && uri[0] != '\0', kUridNull);
  4154. carla_debug("CarlaPluginLV2::getCustomURID(\"%s\")", uri);
  4155. const std::string s_uri(uri);
  4156. const std::ptrdiff_t s_pos(std::find(fCustomURIDs.begin(), fCustomURIDs.end(), s_uri) - fCustomURIDs.begin());
  4157. if (s_pos <= 0 || s_pos >= INT32_MAX)
  4158. return kUridNull;
  4159. const LV2_URID urid = static_cast<LV2_URID>(s_pos);
  4160. const LV2_URID uriCount = static_cast<LV2_URID>(fCustomURIDs.size());
  4161. if (urid < uriCount)
  4162. return urid;
  4163. CARLA_SAFE_ASSERT(urid == uriCount);
  4164. fCustomURIDs.push_back(uri);
  4165. if (fUI.type == UI::TYPE_BRIDGE && fPipeServer.isPipeRunning())
  4166. fPipeServer.writeLv2UridMessage(urid, uri);
  4167. return urid;
  4168. }
  4169. const char* getCustomURIDString(const LV2_URID urid) const noexcept
  4170. {
  4171. CARLA_SAFE_ASSERT_RETURN(urid != kUridNull, kUnmapFallback);
  4172. CARLA_SAFE_ASSERT_RETURN(urid < fCustomURIDs.size(), kUnmapFallback);
  4173. carla_debug("CarlaPluginLV2::getCustomURIString(%i)", urid);
  4174. return fCustomURIDs[urid].c_str();
  4175. }
  4176. // -------------------------------------------------------------------
  4177. void handleProgramChanged(const int32_t index)
  4178. {
  4179. CARLA_SAFE_ASSERT_RETURN(index >= -1,);
  4180. carla_debug("CarlaPluginLV2::handleProgramChanged(%i)", index);
  4181. if (index == -1)
  4182. {
  4183. const ScopedSingleProcessLocker spl(this, true);
  4184. return reloadPrograms(false);
  4185. }
  4186. if (index < static_cast<int32_t>(pData->midiprog.count) && fExt.programs != nullptr && fExt.programs->get_program != nullptr)
  4187. {
  4188. if (const LV2_Program_Descriptor* const progDesc = fExt.programs->get_program(fHandle, static_cast<uint32_t>(index)))
  4189. {
  4190. CARLA_SAFE_ASSERT_RETURN(progDesc->name != nullptr,);
  4191. if (pData->midiprog.data[index].name != nullptr)
  4192. delete[] pData->midiprog.data[index].name;
  4193. pData->midiprog.data[index].name = carla_strdup(progDesc->name);
  4194. if (index == pData->midiprog.current)
  4195. pData->engine->callback(true, true, ENGINE_CALLBACK_UPDATE, pData->id, 0, 0, 0, 0.0, nullptr);
  4196. else
  4197. pData->engine->callback(true, true, ENGINE_CALLBACK_RELOAD_PROGRAMS, pData->id, 0, 0, 0, 0.0, nullptr);
  4198. }
  4199. }
  4200. }
  4201. // -------------------------------------------------------------------
  4202. LV2_Resize_Port_Status handleResizePort(const uint32_t index, const size_t size)
  4203. {
  4204. CARLA_SAFE_ASSERT_RETURN(size > 0, LV2_RESIZE_PORT_ERR_UNKNOWN);
  4205. carla_debug("CarlaPluginLV2::handleResizePort(%i, " P_SIZE ")", index, size);
  4206. // TODO
  4207. return LV2_RESIZE_PORT_ERR_NO_SPACE;
  4208. (void)index;
  4209. }
  4210. // -------------------------------------------------------------------
  4211. LV2_State_Status handleStateStore(const uint32_t key, const void* const value, const size_t size, const uint32_t type, const uint32_t flags)
  4212. {
  4213. CARLA_SAFE_ASSERT_RETURN(key != kUridNull, LV2_STATE_ERR_NO_PROPERTY);
  4214. CARLA_SAFE_ASSERT_RETURN(value != nullptr, LV2_STATE_ERR_NO_PROPERTY);
  4215. CARLA_SAFE_ASSERT_RETURN(size > 0, LV2_STATE_ERR_NO_PROPERTY);
  4216. CARLA_SAFE_ASSERT_RETURN(type != kUridNull, LV2_STATE_ERR_BAD_TYPE);
  4217. // FIXME linuxsampler does not set POD flag
  4218. // CARLA_SAFE_ASSERT_RETURN(flags & LV2_STATE_IS_POD, LV2_STATE_ERR_BAD_FLAGS);
  4219. carla_debug("CarlaPluginLV2::handleStateStore(%i:\"%s\", %p, " P_SIZE ", %i:\"%s\", %i)",
  4220. key, carla_lv2_urid_unmap(this, key), value, size, type, carla_lv2_urid_unmap(this, type), flags);
  4221. const char* const skey(carla_lv2_urid_unmap(this, key));
  4222. const char* const stype(carla_lv2_urid_unmap(this, type));
  4223. CARLA_SAFE_ASSERT_RETURN(skey != nullptr && skey != kUnmapFallback, LV2_STATE_ERR_BAD_TYPE);
  4224. CARLA_SAFE_ASSERT_RETURN(stype != nullptr && stype != kUnmapFallback, LV2_STATE_ERR_BAD_TYPE);
  4225. // Check if we already have this key
  4226. for (LinkedList<CustomData>::Itenerator it = pData->custom.begin2(); it.valid(); it.next())
  4227. {
  4228. CustomData& cData(it.getValue(kCustomDataFallbackNC));
  4229. CARLA_SAFE_ASSERT_CONTINUE(cData.isValid());
  4230. if (std::strcmp(cData.key, skey) == 0)
  4231. {
  4232. // found it
  4233. delete[] cData.value;
  4234. if (type == kUridAtomString || type == kUridAtomPath)
  4235. cData.value = carla_strdup((const char*)value);
  4236. else
  4237. cData.value = CarlaString::asBase64(value, size).dup();
  4238. return LV2_STATE_SUCCESS;
  4239. }
  4240. }
  4241. // Otherwise store it
  4242. CustomData newData;
  4243. newData.type = carla_strdup(stype);
  4244. newData.key = carla_strdup(skey);
  4245. if (type == kUridAtomString || type == kUridAtomPath)
  4246. newData.value = carla_strdup((const char*)value);
  4247. else
  4248. newData.value = CarlaString::asBase64(value, size).dup();
  4249. pData->custom.append(newData);
  4250. return LV2_STATE_SUCCESS;
  4251. // unused
  4252. (void)flags;
  4253. }
  4254. const void* handleStateRetrieve(const uint32_t key, size_t* const size, uint32_t* const type, uint32_t* const flags)
  4255. {
  4256. CARLA_SAFE_ASSERT_RETURN(key != kUridNull, nullptr);
  4257. CARLA_SAFE_ASSERT_RETURN(size != nullptr, nullptr);
  4258. CARLA_SAFE_ASSERT_RETURN(type != nullptr, nullptr);
  4259. CARLA_SAFE_ASSERT_RETURN(flags != nullptr, nullptr);
  4260. carla_debug("CarlaPluginLV2::handleStateRetrieve(%i, %p, %p, %p)", key, size, type, flags);
  4261. const char* const skey(carla_lv2_urid_unmap(this, key));
  4262. CARLA_SAFE_ASSERT_RETURN(skey != nullptr && skey != kUnmapFallback, nullptr);
  4263. const char* stype = nullptr;
  4264. const char* stringData = nullptr;
  4265. for (LinkedList<CustomData>::Itenerator it = pData->custom.begin2(); it.valid(); it.next())
  4266. {
  4267. const CustomData& cData(it.getValue(kCustomDataFallback));
  4268. CARLA_SAFE_ASSERT_CONTINUE(cData.isValid());
  4269. if (std::strcmp(cData.key, skey) == 0)
  4270. {
  4271. stype = cData.type;
  4272. stringData = cData.value;
  4273. break;
  4274. }
  4275. }
  4276. if (stype == nullptr || stringData == nullptr)
  4277. {
  4278. carla_stderr("Plugin requested value for '%s' which is not available", skey);
  4279. *size = *type = *flags = 0;
  4280. return nullptr;
  4281. }
  4282. *type = carla_lv2_urid_map(this, stype);
  4283. *flags = LV2_STATE_IS_POD;
  4284. if (*type == kUridAtomString || *type == kUridAtomPath)
  4285. {
  4286. *size = std::strlen(stringData);
  4287. return stringData;
  4288. }
  4289. if (fLastStateChunk != nullptr)
  4290. {
  4291. std::free(fLastStateChunk);
  4292. fLastStateChunk = nullptr;
  4293. }
  4294. std::vector<uint8_t> chunk(carla_getChunkFromBase64String(stringData));
  4295. CARLA_SAFE_ASSERT_RETURN(chunk.size() > 0, nullptr);
  4296. fLastStateChunk = std::malloc(chunk.size());
  4297. CARLA_SAFE_ASSERT_RETURN(fLastStateChunk != nullptr, nullptr);
  4298. #ifdef CARLA_PROPER_CPP11_SUPPORT
  4299. std::memcpy(fLastStateChunk, chunk.data(), chunk.size());
  4300. #else
  4301. std::memcpy(fLastStateChunk, &chunk.front(), chunk.size());
  4302. #endif
  4303. *size = chunk.size();
  4304. return fLastStateChunk;
  4305. }
  4306. // -------------------------------------------------------------------
  4307. LV2_Worker_Status handleWorkerSchedule(const uint32_t size, const void* const data)
  4308. {
  4309. CARLA_SAFE_ASSERT_RETURN(fExt.worker != nullptr && fExt.worker->work != nullptr, LV2_WORKER_ERR_UNKNOWN);
  4310. CARLA_SAFE_ASSERT_RETURN(fEventsIn.ctrl != nullptr, LV2_WORKER_ERR_UNKNOWN);
  4311. carla_debug("CarlaPluginLV2::handleWorkerSchedule(%i, %p)", size, data);
  4312. if (pData->engine->isOffline())
  4313. {
  4314. fExt.worker->work(fHandle, carla_lv2_worker_respond, this, size, data);
  4315. return LV2_WORKER_SUCCESS;
  4316. }
  4317. LV2_Atom atom;
  4318. atom.size = size;
  4319. atom.type = kUridCarlaAtomWorkerIn;
  4320. return fAtomBufferWorkerIn.putChunk(&atom, data, fEventsOut.ctrlIndex) ? LV2_WORKER_SUCCESS : LV2_WORKER_ERR_NO_SPACE;
  4321. }
  4322. LV2_Worker_Status handleWorkerRespond(const uint32_t size, const void* const data)
  4323. {
  4324. CARLA_SAFE_ASSERT_RETURN(fExt.worker != nullptr && fExt.worker->work_response != nullptr, LV2_WORKER_ERR_UNKNOWN);
  4325. carla_debug("CarlaPluginLV2::handleWorkerRespond(%i, %p)", size, data);
  4326. LV2_Atom atom;
  4327. atom.size = size;
  4328. atom.type = kUridCarlaAtomWorkerResp;
  4329. return fAtomBufferWorkerResp.putChunk(&atom, data, fEventsIn.ctrlIndex) ? LV2_WORKER_SUCCESS : LV2_WORKER_ERR_NO_SPACE;
  4330. }
  4331. // -------------------------------------------------------------------
  4332. void handleInlineDisplayQueueRedraw()
  4333. {
  4334. fInlineDisplayNeedsRedraw = true;
  4335. }
  4336. const LV2_Inline_Display_Image_Surface* renderInlineDisplay(const uint32_t width, const uint32_t height)
  4337. {
  4338. CARLA_SAFE_ASSERT_RETURN(fExt.inlineDisplay != nullptr && fExt.inlineDisplay->render != nullptr, nullptr);
  4339. CARLA_SAFE_ASSERT_RETURN(width > 0, nullptr);
  4340. CARLA_SAFE_ASSERT_RETURN(height > 0, nullptr);
  4341. return fExt.inlineDisplay->render(fHandle, width, height);
  4342. }
  4343. // -------------------------------------------------------------------
  4344. void handleMidnamUpdate()
  4345. {
  4346. CARLA_SAFE_ASSERT_RETURN(fExt.midnam != nullptr,);
  4347. if (fEventsIn.ctrl == nullptr)
  4348. return;
  4349. char* const midnam = fExt.midnam->midnam(fHandle);
  4350. CARLA_SAFE_ASSERT_RETURN(midnam != nullptr,);
  4351. fEventsIn.ctrl->port->setMetaData("http://www.midi.org/dtds/MIDINameDocument10.dtd", midnam, "text/xml");
  4352. if (fExt.midnam->free != nullptr)
  4353. fExt.midnam->free(midnam);
  4354. }
  4355. // -------------------------------------------------------------------
  4356. void handleExternalUIClosed()
  4357. {
  4358. CARLA_SAFE_ASSERT_RETURN(fUI.type == UI::TYPE_EXTERNAL,);
  4359. carla_debug("CarlaPluginLV2::handleExternalUIClosed()");
  4360. fNeedsUiClose = true;
  4361. }
  4362. void handlePluginUIClosed() override
  4363. {
  4364. CARLA_SAFE_ASSERT_RETURN(fUI.type == UI::TYPE_EMBED,);
  4365. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  4366. carla_debug("CarlaPluginLV2::handlePluginUIClosed()");
  4367. fNeedsUiClose = true;
  4368. }
  4369. void handlePluginUIResized(const uint width, const uint height) override
  4370. {
  4371. CARLA_SAFE_ASSERT_RETURN(fUI.type == UI::TYPE_EMBED,);
  4372. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  4373. carla_debug("CarlaPluginLV2::handlePluginUIResized(%u, %u)", width, height);
  4374. if (fUI.handle != nullptr && fExt.uiresize != nullptr)
  4375. fExt.uiresize->ui_resize(fUI.handle, static_cast<int>(width), static_cast<int>(height));
  4376. }
  4377. // -------------------------------------------------------------------
  4378. uint32_t handleUIPortMap(const char* const symbol) const noexcept
  4379. {
  4380. CARLA_SAFE_ASSERT_RETURN(symbol != nullptr && symbol[0] != '\0', LV2UI_INVALID_PORT_INDEX);
  4381. carla_debug("CarlaPluginLV2::handleUIPortMap(\"%s\")", symbol);
  4382. for (uint32_t i=0; i < fRdfDescriptor->PortCount; ++i)
  4383. {
  4384. if (std::strcmp(fRdfDescriptor->Ports[i].Symbol, symbol) == 0)
  4385. return i;
  4386. }
  4387. return LV2UI_INVALID_PORT_INDEX;
  4388. }
  4389. int handleUIResize(const int width, const int height)
  4390. {
  4391. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr, 1);
  4392. CARLA_SAFE_ASSERT_RETURN(width > 0, 1);
  4393. CARLA_SAFE_ASSERT_RETURN(height > 0, 1);
  4394. carla_debug("CarlaPluginLV2::handleUIResize(%i, %i)", width, height);
  4395. fUI.window->setSize(static_cast<uint>(width), static_cast<uint>(height), true);
  4396. return 0;
  4397. }
  4398. void handleUITouch(const uint32_t rindex, const bool touch)
  4399. {
  4400. carla_debug("CarlaPluginLV2::handleUITouch(%u, %s)", rindex, bool2str(touch));
  4401. uint32_t index = LV2UI_INVALID_PORT_INDEX;
  4402. for (uint32_t i=0; i < pData->param.count; ++i)
  4403. {
  4404. if (pData->param.data[i].rindex != static_cast<int32_t>(rindex))
  4405. continue;
  4406. index = i;
  4407. break;
  4408. }
  4409. CARLA_SAFE_ASSERT_RETURN(index != LV2UI_INVALID_PORT_INDEX,);
  4410. pData->engine->touchPluginParameter(pData->id, index, touch);
  4411. }
  4412. void handleUIWrite(const uint32_t rindex, const uint32_t bufferSize, const uint32_t format, const void* const buffer)
  4413. {
  4414. CARLA_SAFE_ASSERT_RETURN(buffer != nullptr,);
  4415. CARLA_SAFE_ASSERT_RETURN(bufferSize > 0,);
  4416. carla_debug("CarlaPluginLV2::handleUIWrite(%i, %i, %i, %p)", rindex, bufferSize, format, buffer);
  4417. uint32_t index = LV2UI_INVALID_PORT_INDEX;
  4418. switch (format)
  4419. {
  4420. case kUridNull: {
  4421. CARLA_SAFE_ASSERT_RETURN(rindex < fRdfDescriptor->PortCount,);
  4422. CARLA_SAFE_ASSERT_RETURN(bufferSize == sizeof(float),);
  4423. for (uint32_t i=0; i < pData->param.count; ++i)
  4424. {
  4425. if (pData->param.data[i].rindex != static_cast<int32_t>(rindex))
  4426. continue;
  4427. index = i;
  4428. break;
  4429. }
  4430. CARLA_SAFE_ASSERT_RETURN(index != LV2UI_INVALID_PORT_INDEX,);
  4431. const float value(*(const float*)buffer);
  4432. // check if we should feedback message back to UI
  4433. bool sendGui = false;
  4434. if (const uint32_t notifCount = fUI.rdfDescriptor->PortNotificationCount)
  4435. {
  4436. const char* const portSymbol = fRdfDescriptor->Ports[rindex].Symbol;
  4437. for (uint32_t i=0; i < notifCount; ++i)
  4438. {
  4439. const LV2_RDF_UI_PortNotification& portNotif(fUI.rdfDescriptor->PortNotifications[i]);
  4440. if (portNotif.Protocol != LV2_UI_PORT_PROTOCOL_FLOAT)
  4441. continue;
  4442. if (portNotif.Symbol != nullptr)
  4443. {
  4444. if (std::strcmp(portNotif.Symbol, portSymbol) != 0)
  4445. continue;
  4446. }
  4447. else if (portNotif.Index != rindex)
  4448. {
  4449. continue;
  4450. }
  4451. sendGui = true;
  4452. break;
  4453. }
  4454. }
  4455. setParameterValue(index, value, sendGui, true, true);
  4456. } break;
  4457. case kUridAtomTransferAtom:
  4458. case kUridAtomTransferEvent: {
  4459. CARLA_SAFE_ASSERT_RETURN(bufferSize >= sizeof(LV2_Atom),);
  4460. const LV2_Atom* const atom((const LV2_Atom*)buffer);
  4461. // plugins sometimes fail on this, not good...
  4462. const uint32_t totalSize = lv2_atom_total_size(atom);
  4463. const uint32_t paddedSize = lv2_atom_pad_size(totalSize);
  4464. if (bufferSize != totalSize && bufferSize != paddedSize)
  4465. carla_stderr2("Warning: LV2 UI sending atom with invalid size %u! size: %u, padded-size: %u",
  4466. bufferSize, totalSize, paddedSize);
  4467. for (uint32_t i=0; i < fEventsIn.count; ++i)
  4468. {
  4469. if (fEventsIn.data[i].rindex != rindex)
  4470. continue;
  4471. index = i;
  4472. break;
  4473. }
  4474. // for bad plugins
  4475. if (index == LV2UI_INVALID_PORT_INDEX)
  4476. {
  4477. CARLA_SAFE_ASSERT(index != LV2UI_INVALID_PORT_INDEX); // FIXME
  4478. index = fEventsIn.ctrlIndex;
  4479. }
  4480. fAtomBufferEvIn.put(atom, index);
  4481. } break;
  4482. default:
  4483. carla_stdout("CarlaPluginLV2::handleUIWrite(%i, %i, %i:\"%s\", %p) - unknown format",
  4484. rindex, bufferSize, format, carla_lv2_urid_unmap(this, format), buffer);
  4485. break;
  4486. }
  4487. }
  4488. // -------------------------------------------------------------------
  4489. void handleLilvSetPortValue(const char* const portSymbol, const void* const value, const uint32_t size, const uint32_t type)
  4490. {
  4491. CARLA_SAFE_ASSERT_RETURN(portSymbol != nullptr && portSymbol[0] != '\0',);
  4492. CARLA_SAFE_ASSERT_RETURN(value != nullptr,);
  4493. CARLA_SAFE_ASSERT_RETURN(size > 0,);
  4494. CARLA_SAFE_ASSERT_RETURN(type != kUridNull,);
  4495. carla_debug("CarlaPluginLV2::handleLilvSetPortValue(\"%s\", %p, %i, %i)", portSymbol, value, size, type);
  4496. int32_t rindex = -1;
  4497. for (uint32_t i=0; i < fRdfDescriptor->PortCount; ++i)
  4498. {
  4499. if (std::strcmp(fRdfDescriptor->Ports[i].Symbol, portSymbol) == 0)
  4500. {
  4501. rindex = static_cast<int32_t>(i);
  4502. break;
  4503. }
  4504. }
  4505. CARLA_SAFE_ASSERT_RETURN(rindex >= 0,);
  4506. float paramValue;
  4507. switch (type)
  4508. {
  4509. case kUridAtomBool:
  4510. CARLA_SAFE_ASSERT_RETURN(size == sizeof(bool),);
  4511. paramValue = (*(const bool*)value) ? 1.0f : 0.0f;
  4512. break;
  4513. case kUridAtomDouble:
  4514. CARLA_SAFE_ASSERT_RETURN(size == sizeof(double),);
  4515. paramValue = static_cast<float>((*(const double*)value));
  4516. break;
  4517. case kUridAtomFloat:
  4518. CARLA_SAFE_ASSERT_RETURN(size == sizeof(float),);
  4519. paramValue = (*(const float*)value);
  4520. break;
  4521. case kUridAtomInt:
  4522. CARLA_SAFE_ASSERT_RETURN(size == sizeof(int32_t),);
  4523. paramValue = static_cast<float>((*(const int32_t*)value));
  4524. break;
  4525. case kUridAtomLong:
  4526. CARLA_SAFE_ASSERT_RETURN(size == sizeof(int64_t),);
  4527. paramValue = static_cast<float>((*(const int64_t*)value));
  4528. break;
  4529. default:
  4530. carla_stdout("CarlaPluginLV2::handleLilvSetPortValue(\"%s\", %p, %i, %i:\"%s\") - unknown type",
  4531. portSymbol, value, size, type, carla_lv2_urid_unmap(this, type));
  4532. return;
  4533. }
  4534. for (uint32_t i=0; i < pData->param.count; ++i)
  4535. {
  4536. if (pData->param.data[i].rindex == rindex)
  4537. {
  4538. setParameterValueRT(i, paramValue, true);
  4539. break;
  4540. }
  4541. }
  4542. }
  4543. // -------------------------------------------------------------------
  4544. void* getNativeHandle() const noexcept override
  4545. {
  4546. return fHandle;
  4547. }
  4548. const void* getNativeDescriptor() const noexcept override
  4549. {
  4550. return fDescriptor;
  4551. }
  4552. uintptr_t getUiBridgeProcessId() const noexcept override
  4553. {
  4554. return fPipeServer.isPipeRunning() ? fPipeServer.getPID() : 0;
  4555. }
  4556. // -------------------------------------------------------------------
  4557. public:
  4558. bool init(const char* const name, const char* const uri, const uint options)
  4559. {
  4560. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  4561. // ---------------------------------------------------------------
  4562. // first checks
  4563. if (pData->client != nullptr)
  4564. {
  4565. pData->engine->setLastError("Plugin client is already registered");
  4566. return false;
  4567. }
  4568. if (uri == nullptr || uri[0] == '\0')
  4569. {
  4570. pData->engine->setLastError("null uri");
  4571. return false;
  4572. }
  4573. // ---------------------------------------------------------------
  4574. // Init LV2 World if needed, sets LV2_PATH for lilv
  4575. Lv2WorldClass& lv2World(Lv2WorldClass::getInstance());
  4576. if (pData->engine->getOptions().pathLV2 != nullptr && pData->engine->getOptions().pathLV2[0] != '\0')
  4577. lv2World.initIfNeeded(pData->engine->getOptions().pathLV2);
  4578. else if (const char* const LV2_PATH = std::getenv("LV2_PATH"))
  4579. lv2World.initIfNeeded(LV2_PATH);
  4580. else
  4581. lv2World.initIfNeeded(LILV_DEFAULT_LV2_PATH);
  4582. // ---------------------------------------------------------------
  4583. // get plugin from lv2_rdf (lilv)
  4584. fRdfDescriptor = lv2_rdf_new(uri, true);
  4585. if (fRdfDescriptor == nullptr)
  4586. {
  4587. pData->engine->setLastError("Failed to find the requested plugin");
  4588. return false;
  4589. }
  4590. // ---------------------------------------------------------------
  4591. // open DLL
  4592. if (! pData->libOpen(fRdfDescriptor->Binary))
  4593. {
  4594. pData->engine->setLastError(pData->libError(fRdfDescriptor->Binary));
  4595. return false;
  4596. }
  4597. // ---------------------------------------------------------------
  4598. // try to get DLL main entry via new mode
  4599. if (const LV2_Lib_Descriptor_Function libDescFn = pData->libSymbol<LV2_Lib_Descriptor_Function>("lv2_lib_descriptor"))
  4600. {
  4601. // -----------------------------------------------------------
  4602. // all ok, get lib descriptor
  4603. const LV2_Lib_Descriptor* const libDesc = libDescFn(fRdfDescriptor->Bundle, nullptr);
  4604. if (libDesc == nullptr)
  4605. {
  4606. pData->engine->setLastError("Could not find the LV2 Descriptor");
  4607. return false;
  4608. }
  4609. // -----------------------------------------------------------
  4610. // get descriptor that matches URI (new mode)
  4611. uint32_t i = 0;
  4612. while ((fDescriptor = libDesc->get_plugin(libDesc->handle, i++)))
  4613. {
  4614. if (std::strcmp(fDescriptor->URI, uri) == 0)
  4615. break;
  4616. }
  4617. }
  4618. else
  4619. {
  4620. // -----------------------------------------------------------
  4621. // get DLL main entry (old mode)
  4622. const LV2_Descriptor_Function descFn = pData->libSymbol<LV2_Descriptor_Function>("lv2_descriptor");
  4623. if (descFn == nullptr)
  4624. {
  4625. pData->engine->setLastError("Could not find the LV2 Descriptor in the plugin library");
  4626. return false;
  4627. }
  4628. // -----------------------------------------------------------
  4629. // get descriptor that matches URI (old mode)
  4630. uint32_t i = 0;
  4631. while ((fDescriptor = descFn(i++)))
  4632. {
  4633. if (std::strcmp(fDescriptor->URI, uri) == 0)
  4634. break;
  4635. }
  4636. }
  4637. if (fDescriptor == nullptr)
  4638. {
  4639. pData->engine->setLastError("Could not find the requested plugin URI in the plugin library");
  4640. return false;
  4641. }
  4642. // ---------------------------------------------------------------
  4643. // check supported port-types and features
  4644. bool canContinue = true;
  4645. // Check supported ports
  4646. for (uint32_t j=0; j < fRdfDescriptor->PortCount; ++j)
  4647. {
  4648. const LV2_Property portTypes(fRdfDescriptor->Ports[j].Types);
  4649. if (! is_lv2_port_supported(portTypes))
  4650. {
  4651. if (! LV2_IS_PORT_OPTIONAL(fRdfDescriptor->Ports[j].Properties))
  4652. {
  4653. pData->engine->setLastError("Plugin requires a port type that is not currently supported");
  4654. canContinue = false;
  4655. break;
  4656. }
  4657. }
  4658. }
  4659. // Check supported features
  4660. for (uint32_t j=0; j < fRdfDescriptor->FeatureCount && canContinue; ++j)
  4661. {
  4662. const LV2_RDF_Feature& feature(fRdfDescriptor->Features[j]);
  4663. if (std::strcmp(feature.URI, LV2_DATA_ACCESS_URI) == 0 || std::strcmp(feature.URI, LV2_INSTANCE_ACCESS_URI) == 0)
  4664. {
  4665. carla_stderr("Plugin DSP wants UI feature '%s', ignoring this", feature.URI);
  4666. }
  4667. else if (std::strcmp(feature.URI, LV2_BUF_SIZE__fixedBlockLength) == 0)
  4668. {
  4669. fNeedsFixedBuffers = true;
  4670. }
  4671. else if (std::strcmp(feature.URI, LV2_PORT_PROPS__supportsStrictBounds) == 0)
  4672. {
  4673. fStrictBounds = feature.Required ? 1 : 0;
  4674. }
  4675. else if (feature.Required && ! is_lv2_feature_supported(feature.URI))
  4676. {
  4677. CarlaString msg("Plugin wants a feature that is not supported:\n");
  4678. msg += feature.URI;
  4679. canContinue = false;
  4680. pData->engine->setLastError(msg);
  4681. break;
  4682. }
  4683. }
  4684. if (! canContinue)
  4685. {
  4686. // error already set
  4687. return false;
  4688. }
  4689. if (fNeedsFixedBuffers && ! pData->engine->usesConstantBufferSize())
  4690. {
  4691. pData->engine->setLastError("Cannot use this plugin under the current engine.\n"
  4692. "The plugin requires a fixed block size which is not possible right now.");
  4693. return false;
  4694. }
  4695. // ---------------------------------------------------------------
  4696. // set icon
  4697. if (std::strncmp(fDescriptor->URI, "http://distrho.sf.net/", 22) == 0)
  4698. pData->iconName = carla_strdup_safe("distrho");
  4699. // ---------------------------------------------------------------
  4700. // set info
  4701. if (name != nullptr && name[0] != '\0')
  4702. pData->name = pData->engine->getUniquePluginName(name);
  4703. else
  4704. pData->name = pData->engine->getUniquePluginName(fRdfDescriptor->Name);
  4705. // ---------------------------------------------------------------
  4706. // register client
  4707. pData->client = pData->engine->addClient(this);
  4708. if (pData->client == nullptr || ! pData->client->isOk())
  4709. {
  4710. pData->engine->setLastError("Failed to register plugin client");
  4711. return false;
  4712. }
  4713. // ---------------------------------------------------------------
  4714. // initialize options
  4715. const int bufferSize = static_cast<int>(pData->engine->getBufferSize());
  4716. fLv2Options.minBufferSize = fNeedsFixedBuffers ? bufferSize : 1;
  4717. fLv2Options.maxBufferSize = bufferSize;
  4718. fLv2Options.nominalBufferSize = bufferSize;
  4719. fLv2Options.sampleRate = static_cast<float>(pData->engine->getSampleRate());
  4720. fLv2Options.transientWinId = static_cast<int64_t>(pData->engine->getOptions().frontendWinId);
  4721. uint32_t eventBufferSize = MAX_DEFAULT_BUFFER_SIZE;
  4722. for (uint32_t j=0; j < fRdfDescriptor->PortCount; ++j)
  4723. {
  4724. const LV2_Property portTypes(fRdfDescriptor->Ports[j].Types);
  4725. if (LV2_IS_PORT_ATOM_SEQUENCE(portTypes) || LV2_IS_PORT_EVENT(portTypes) || LV2_IS_PORT_MIDI_LL(portTypes))
  4726. {
  4727. if (fRdfDescriptor->Ports[j].MinimumSize > eventBufferSize)
  4728. eventBufferSize = fRdfDescriptor->Ports[j].MinimumSize;
  4729. }
  4730. }
  4731. fLv2Options.sequenceSize = static_cast<int>(eventBufferSize);
  4732. fLv2Options.uiScale = pData->engine->getOptions().uiScale;
  4733. // ---------------------------------------------------------------
  4734. // initialize features (part 1)
  4735. LV2_Event_Feature* const eventFt = new LV2_Event_Feature;
  4736. eventFt->callback_data = this;
  4737. eventFt->lv2_event_ref = carla_lv2_event_ref;
  4738. eventFt->lv2_event_unref = carla_lv2_event_unref;
  4739. LV2_Log_Log* const logFt = new LV2_Log_Log;
  4740. logFt->handle = this;
  4741. logFt->printf = carla_lv2_log_printf;
  4742. logFt->vprintf = carla_lv2_log_vprintf;
  4743. LV2_State_Make_Path* const stateMakePathFt = new LV2_State_Make_Path;
  4744. stateMakePathFt->handle = this;
  4745. stateMakePathFt->path = carla_lv2_state_make_path;
  4746. LV2_State_Map_Path* const stateMapPathFt = new LV2_State_Map_Path;
  4747. stateMapPathFt->handle = this;
  4748. stateMapPathFt->abstract_path = carla_lv2_state_map_abstract_path;
  4749. stateMapPathFt->absolute_path = carla_lv2_state_map_absolute_path;
  4750. LV2_Programs_Host* const programsFt = new LV2_Programs_Host;
  4751. programsFt->handle = this;
  4752. programsFt->program_changed = carla_lv2_program_changed;
  4753. LV2_Resize_Port_Resize* const rsPortFt = new LV2_Resize_Port_Resize;
  4754. rsPortFt->data = this;
  4755. rsPortFt->resize = carla_lv2_resize_port;
  4756. LV2_RtMemPool_Pool* const rtMemPoolFt = new LV2_RtMemPool_Pool;
  4757. lv2_rtmempool_init(rtMemPoolFt);
  4758. LV2_RtMemPool_Pool_Deprecated* const rtMemPoolOldFt = new LV2_RtMemPool_Pool_Deprecated;
  4759. lv2_rtmempool_init_deprecated(rtMemPoolOldFt);
  4760. LV2_URI_Map_Feature* const uriMapFt = new LV2_URI_Map_Feature;
  4761. uriMapFt->callback_data = this;
  4762. uriMapFt->uri_to_id = carla_lv2_uri_to_id;
  4763. LV2_URID_Map* const uridMapFt = new LV2_URID_Map;
  4764. uridMapFt->handle = this;
  4765. uridMapFt->map = carla_lv2_urid_map;
  4766. LV2_URID_Unmap* const uridUnmapFt = new LV2_URID_Unmap;
  4767. uridUnmapFt->handle = this;
  4768. uridUnmapFt->unmap = carla_lv2_urid_unmap;
  4769. LV2_Worker_Schedule* const workerFt = new LV2_Worker_Schedule;
  4770. workerFt->handle = this;
  4771. workerFt->schedule_work = carla_lv2_worker_schedule;
  4772. LV2_Inline_Display* const inlineDisplay = new LV2_Inline_Display;
  4773. inlineDisplay->handle = this;
  4774. inlineDisplay->queue_draw = carla_lv2_inline_display_queue_draw;
  4775. LV2_Midnam* const midnam = new LV2_Midnam;
  4776. midnam->handle = this;
  4777. midnam->update = carla_lv2_midnam_update;
  4778. // ---------------------------------------------------------------
  4779. // initialize features (part 2)
  4780. for (uint32_t j=0; j < kFeatureCountPlugin; ++j)
  4781. fFeatures[j] = new LV2_Feature;
  4782. fFeatures[kFeatureIdBufSizeBounded]->URI = LV2_BUF_SIZE__boundedBlockLength;
  4783. fFeatures[kFeatureIdBufSizeBounded]->data = nullptr;
  4784. fFeatures[kFeatureIdBufSizeFixed]->URI = fNeedsFixedBuffers
  4785. ? LV2_BUF_SIZE__fixedBlockLength
  4786. : LV2_BUF_SIZE__boundedBlockLength;
  4787. fFeatures[kFeatureIdBufSizeFixed]->data = nullptr;
  4788. fFeatures[kFeatureIdBufSizePowerOf2]->URI = LV2_BUF_SIZE__powerOf2BlockLength;
  4789. fFeatures[kFeatureIdBufSizePowerOf2]->data = nullptr;
  4790. fFeatures[kFeatureIdEvent]->URI = LV2_EVENT_URI;
  4791. fFeatures[kFeatureIdEvent]->data = eventFt;
  4792. fFeatures[kFeatureIdHardRtCapable]->URI = LV2_CORE__hardRTCapable;
  4793. fFeatures[kFeatureIdHardRtCapable]->data = nullptr;
  4794. fFeatures[kFeatureIdInPlaceBroken]->URI = LV2_CORE__inPlaceBroken;
  4795. fFeatures[kFeatureIdInPlaceBroken]->data = nullptr;
  4796. fFeatures[kFeatureIdIsLive]->URI = LV2_CORE__isLive;
  4797. fFeatures[kFeatureIdIsLive]->data = nullptr;
  4798. fFeatures[kFeatureIdLogs]->URI = LV2_LOG__log;
  4799. fFeatures[kFeatureIdLogs]->data = logFt;
  4800. fFeatures[kFeatureIdOptions]->URI = LV2_OPTIONS__options;
  4801. fFeatures[kFeatureIdOptions]->data = fLv2Options.opts;
  4802. fFeatures[kFeatureIdPrograms]->URI = LV2_PROGRAMS__Host;
  4803. fFeatures[kFeatureIdPrograms]->data = programsFt;
  4804. fFeatures[kFeatureIdResizePort]->URI = LV2_RESIZE_PORT__resize;
  4805. fFeatures[kFeatureIdResizePort]->data = rsPortFt;
  4806. fFeatures[kFeatureIdRtMemPool]->URI = LV2_RTSAFE_MEMORY_POOL__Pool;
  4807. fFeatures[kFeatureIdRtMemPool]->data = rtMemPoolFt;
  4808. fFeatures[kFeatureIdRtMemPoolOld]->URI = LV2_RTSAFE_MEMORY_POOL_DEPRECATED_URI;
  4809. fFeatures[kFeatureIdRtMemPoolOld]->data = rtMemPoolOldFt;
  4810. fFeatures[kFeatureIdStateMakePath]->URI = LV2_STATE__makePath;
  4811. fFeatures[kFeatureIdStateMakePath]->data = stateMakePathFt;
  4812. fFeatures[kFeatureIdStateMapPath]->URI = LV2_STATE__mapPath;
  4813. fFeatures[kFeatureIdStateMapPath]->data = stateMapPathFt;
  4814. fFeatures[kFeatureIdStrictBounds]->URI = LV2_PORT_PROPS__supportsStrictBounds;
  4815. fFeatures[kFeatureIdStrictBounds]->data = nullptr;
  4816. fFeatures[kFeatureIdUriMap]->URI = LV2_URI_MAP_URI;
  4817. fFeatures[kFeatureIdUriMap]->data = uriMapFt;
  4818. fFeatures[kFeatureIdUridMap]->URI = LV2_URID__map;
  4819. fFeatures[kFeatureIdUridMap]->data = uridMapFt;
  4820. fFeatures[kFeatureIdUridUnmap]->URI = LV2_URID__unmap;
  4821. fFeatures[kFeatureIdUridUnmap]->data = uridUnmapFt;
  4822. fFeatures[kFeatureIdWorker]->URI = LV2_WORKER__schedule;
  4823. fFeatures[kFeatureIdWorker]->data = workerFt;
  4824. fFeatures[kFeatureIdInlineDisplay]->URI = LV2_INLINEDISPLAY__queue_draw;
  4825. fFeatures[kFeatureIdInlineDisplay]->data = inlineDisplay;
  4826. fFeatures[kFeatureIdMidnam]->URI = LV2_MIDNAM__update;
  4827. fFeatures[kFeatureIdMidnam]->data = midnam;
  4828. // ---------------------------------------------------------------
  4829. // initialize plugin
  4830. try {
  4831. fHandle = fDescriptor->instantiate(fDescriptor, pData->engine->getSampleRate(), fRdfDescriptor->Bundle, fFeatures);
  4832. } catch(...) {}
  4833. if (fHandle == nullptr)
  4834. {
  4835. pData->engine->setLastError("Plugin failed to initialize");
  4836. return false;
  4837. }
  4838. recheckExtensions();
  4839. // ---------------------------------------------------------------
  4840. // set options
  4841. pData->options = 0x0;
  4842. if (fLatencyIndex >= 0 || getMidiOutCount() != 0 || fNeedsFixedBuffers)
  4843. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  4844. else if (options & PLUGIN_OPTION_FIXED_BUFFERS)
  4845. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  4846. if (pData->engine->getOptions().forceStereo)
  4847. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  4848. else if (options & PLUGIN_OPTION_FORCE_STEREO)
  4849. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  4850. if (getMidiInCount() != 0)
  4851. {
  4852. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CONTROL_CHANGES))
  4853. pData->options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  4854. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CHANNEL_PRESSURE))
  4855. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  4856. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH))
  4857. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  4858. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PITCHBEND))
  4859. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  4860. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_ALL_SOUND_OFF))
  4861. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  4862. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PROGRAM_CHANGES))
  4863. pData->options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  4864. }
  4865. if (fExt.programs != nullptr && (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) == 0)
  4866. {
  4867. if (isPluginOptionEnabled(options, PLUGIN_OPTION_MAP_PROGRAM_CHANGES))
  4868. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  4869. }
  4870. // ---------------------------------------------------------------
  4871. // gui stuff
  4872. if (fRdfDescriptor->UICount != 0)
  4873. initUi();
  4874. return true;
  4875. }
  4876. // -------------------------------------------------------------------
  4877. void initUi()
  4878. {
  4879. // ---------------------------------------------------------------
  4880. // find the most appropriate ui
  4881. int eQt4, eQt5, eGtk2, eGtk3, eCocoa, eWindows, eX11, eMod, iCocoa, iWindows, iX11, iExt, iFinal;
  4882. eQt4 = eQt5 = eGtk2 = eGtk3 = eCocoa = eWindows = eX11 = eMod = iCocoa = iWindows = iX11 = iExt = iFinal = -1;
  4883. #if defined(LV2_UIS_ONLY_BRIDGES)
  4884. const bool preferUiBridges = true;
  4885. #elif defined(BUILD_BRIDGE)
  4886. const bool preferUiBridges = false;
  4887. #else
  4888. const bool preferUiBridges = pData->engine->getOptions().preferUiBridges;
  4889. #endif
  4890. bool hasShowInterface = false;
  4891. for (uint32_t i=0; i < fRdfDescriptor->UICount; ++i)
  4892. {
  4893. CARLA_SAFE_ASSERT_CONTINUE(fRdfDescriptor->UIs[i].URI != nullptr);
  4894. const int ii(static_cast<int>(i));
  4895. switch (fRdfDescriptor->UIs[i].Type)
  4896. {
  4897. case LV2_UI_QT4:
  4898. if (isUiBridgeable(i))
  4899. eQt4 = ii;
  4900. break;
  4901. case LV2_UI_QT5:
  4902. if (isUiBridgeable(i))
  4903. eQt5 = ii;
  4904. break;
  4905. case LV2_UI_GTK2:
  4906. if (isUiBridgeable(i))
  4907. eGtk2 = ii;
  4908. break;
  4909. case LV2_UI_GTK3:
  4910. if (isUiBridgeable(i))
  4911. eGtk3 = ii;
  4912. break;
  4913. #ifdef CARLA_OS_MAC
  4914. case LV2_UI_COCOA:
  4915. if (isUiBridgeable(i) && preferUiBridges)
  4916. eCocoa = ii;
  4917. iCocoa = ii;
  4918. break;
  4919. #endif
  4920. #ifdef CARLA_OS_WIN
  4921. case LV2_UI_WINDOWS:
  4922. if (isUiBridgeable(i) && preferUiBridges)
  4923. eWindows = ii;
  4924. iWindows = ii;
  4925. break;
  4926. #endif
  4927. case LV2_UI_X11:
  4928. if (isUiBridgeable(i) && preferUiBridges)
  4929. eX11 = ii;
  4930. iX11 = ii;
  4931. break;
  4932. case LV2_UI_EXTERNAL:
  4933. case LV2_UI_OLD_EXTERNAL:
  4934. iExt = ii;
  4935. break;
  4936. case LV2_UI_MOD:
  4937. eMod = ii;
  4938. break;
  4939. default:
  4940. break;
  4941. }
  4942. }
  4943. /**/ if (eQt4 >= 0)
  4944. iFinal = eQt4;
  4945. else if (eQt5 >= 0)
  4946. iFinal = eQt5;
  4947. else if (eGtk2 >= 0)
  4948. iFinal = eGtk2;
  4949. else if (eGtk3 >= 0)
  4950. iFinal = eGtk3;
  4951. #ifdef CARLA_OS_MAC
  4952. else if (eCocoa >= 0)
  4953. iFinal = eCocoa;
  4954. #endif
  4955. #ifdef CARLA_OS_WIN
  4956. else if (eWindows >= 0)
  4957. iFinal = eWindows;
  4958. #endif
  4959. #ifdef HAVE_X11
  4960. else if (eX11 >= 0)
  4961. iFinal = eX11;
  4962. #endif
  4963. #ifndef LV2_UIS_ONLY_BRIDGES
  4964. # ifdef CARLA_OS_MAC
  4965. else if (iCocoa >= 0)
  4966. iFinal = iCocoa;
  4967. # endif
  4968. # ifdef CARLA_OS_WIN
  4969. else if (iWindows >= 0)
  4970. iFinal = iWindows;
  4971. # endif
  4972. # ifdef HAVE_X11
  4973. else if (iX11 >= 0)
  4974. iFinal = iX11;
  4975. # endif
  4976. #endif
  4977. else if (iExt >= 0)
  4978. iFinal = iExt;
  4979. #ifndef BUILD_BRIDGE
  4980. if (iFinal < 0)
  4981. #endif
  4982. {
  4983. // no suitable UI found, see if there's one which supports ui:showInterface
  4984. for (uint32_t i=0; i < fRdfDescriptor->UICount && ! hasShowInterface; ++i)
  4985. {
  4986. LV2_RDF_UI* const ui(&fRdfDescriptor->UIs[i]);
  4987. for (uint32_t j=0; j < ui->ExtensionCount; ++j)
  4988. {
  4989. CARLA_SAFE_ASSERT_CONTINUE(ui->Extensions[j] != nullptr);
  4990. if (std::strcmp(ui->Extensions[j], LV2_UI__showInterface) != 0)
  4991. continue;
  4992. iFinal = static_cast<int>(i);
  4993. hasShowInterface = true;
  4994. break;
  4995. }
  4996. }
  4997. if (iFinal < 0)
  4998. {
  4999. if (eMod < 0)
  5000. {
  5001. carla_stderr("Failed to find an appropriate LV2 UI for this plugin");
  5002. return;
  5003. }
  5004. // use MODGUI as last resort
  5005. iFinal = eMod;
  5006. }
  5007. }
  5008. fUI.rdfDescriptor = &fRdfDescriptor->UIs[iFinal];
  5009. // ---------------------------------------------------------------
  5010. // check supported ui features
  5011. bool canContinue = true;
  5012. bool canDelete = true;
  5013. for (uint32_t i=0; i < fUI.rdfDescriptor->FeatureCount; ++i)
  5014. {
  5015. const char* const uri(fUI.rdfDescriptor->Features[i].URI);
  5016. CARLA_SAFE_ASSERT_CONTINUE(uri != nullptr && uri[0] != '\0');
  5017. if (! is_lv2_ui_feature_supported(uri))
  5018. {
  5019. if (fUI.rdfDescriptor->Features[i].Required)
  5020. {
  5021. carla_stderr("Plugin UI requires a feature that is not supported:\n%s", uri);
  5022. canContinue = false;
  5023. break;
  5024. }
  5025. carla_stderr("Plugin UI wants a feature that is not supported (ignored):\n%s", uri);
  5026. }
  5027. if (std::strcmp(uri, LV2_UI__makeResident) == 0 || std::strcmp(uri, LV2_UI__makeSONameResident) == 0)
  5028. canDelete = false;
  5029. }
  5030. if (! canContinue)
  5031. {
  5032. fUI.rdfDescriptor = nullptr;
  5033. return;
  5034. }
  5035. // ---------------------------------------------------------------
  5036. // initialize ui according to type
  5037. const LV2_Property uiType(fUI.rdfDescriptor->Type);
  5038. if (
  5039. (iFinal == eQt4 ||
  5040. iFinal == eQt5 ||
  5041. iFinal == eGtk2 ||
  5042. iFinal == eGtk3 ||
  5043. iFinal == eCocoa ||
  5044. iFinal == eWindows ||
  5045. iFinal == eX11 ||
  5046. iFinal == eMod)
  5047. #ifdef BUILD_BRIDGE
  5048. && ! hasShowInterface
  5049. #endif
  5050. )
  5051. {
  5052. // -----------------------------------------------------------
  5053. // initialize ui-bridge
  5054. if (const char* const bridgeBinary = getUiBridgeBinary(uiType))
  5055. {
  5056. carla_stdout("Will use UI-Bridge for '%s', binary: \"%s\"", pData->name, bridgeBinary);
  5057. CarlaString guiTitle(pData->name);
  5058. guiTitle += " (GUI)";
  5059. fLv2Options.windowTitle = guiTitle.dup();
  5060. fUI.type = UI::TYPE_BRIDGE;
  5061. fPipeServer.setData(bridgeBinary, fRdfDescriptor->URI, fUI.rdfDescriptor->URI);
  5062. delete[] bridgeBinary;
  5063. return;
  5064. }
  5065. if (iFinal == eQt4 || iFinal == eQt5 || iFinal == eGtk2 || iFinal == eGtk3 || iFinal == eMod)
  5066. {
  5067. carla_stderr2("Failed to find UI bridge binary for '%s', cannot use UI", pData->name);
  5068. fUI.rdfDescriptor = nullptr;
  5069. return;
  5070. }
  5071. }
  5072. #ifdef LV2_UIS_ONLY_BRIDGES
  5073. carla_stderr2("Failed to get an UI working, canBridge:%s", bool2str(isUiBridgeable(static_cast<uint32_t>(iFinal))));
  5074. fUI.rdfDescriptor = nullptr;
  5075. return;
  5076. #endif
  5077. // ---------------------------------------------------------------
  5078. // open UI DLL
  5079. if (! pData->uiLibOpen(fUI.rdfDescriptor->Binary, canDelete))
  5080. {
  5081. carla_stderr2("Could not load UI library, error was:\n%s", pData->libError(fUI.rdfDescriptor->Binary));
  5082. fUI.rdfDescriptor = nullptr;
  5083. return;
  5084. }
  5085. // ---------------------------------------------------------------
  5086. // get UI DLL main entry
  5087. LV2UI_DescriptorFunction uiDescFn = pData->uiLibSymbol<LV2UI_DescriptorFunction>("lv2ui_descriptor");
  5088. if (uiDescFn == nullptr)
  5089. {
  5090. carla_stderr2("Could not find the LV2UI Descriptor in the UI library");
  5091. pData->uiLibClose();
  5092. fUI.rdfDescriptor = nullptr;
  5093. return;
  5094. }
  5095. // ---------------------------------------------------------------
  5096. // get UI descriptor that matches UI URI
  5097. uint32_t i = 0;
  5098. while ((fUI.descriptor = uiDescFn(i++)))
  5099. {
  5100. if (std::strcmp(fUI.descriptor->URI, fUI.rdfDescriptor->URI) == 0)
  5101. break;
  5102. }
  5103. if (fUI.descriptor == nullptr)
  5104. {
  5105. carla_stderr2("Could not find the requested GUI in the plugin UI library");
  5106. pData->uiLibClose();
  5107. fUI.rdfDescriptor = nullptr;
  5108. return;
  5109. }
  5110. // ---------------------------------------------------------------
  5111. // check if ui is usable
  5112. switch (uiType)
  5113. {
  5114. case LV2_UI_NONE:
  5115. carla_stdout("Will use LV2 Show Interface for '%s'", pData->name);
  5116. fUI.type = UI::TYPE_EMBED;
  5117. break;
  5118. case LV2_UI_QT4:
  5119. carla_stdout("Will use LV2 Qt4 UI for '%s', NOT!", pData->name);
  5120. fUI.type = UI::TYPE_EMBED;
  5121. break;
  5122. case LV2_UI_QT5:
  5123. carla_stdout("Will use LV2 Qt5 UI for '%s', NOT!", pData->name);
  5124. fUI.type = UI::TYPE_EMBED;
  5125. break;
  5126. case LV2_UI_GTK2:
  5127. carla_stdout("Will use LV2 Gtk2 UI for '%s', NOT!", pData->name);
  5128. fUI.type = UI::TYPE_EMBED;
  5129. break;
  5130. case LV2_UI_GTK3:
  5131. carla_stdout("Will use LV2 Gtk3 UI for '%s', NOT!", pData->name);
  5132. fUI.type = UI::TYPE_EMBED;
  5133. break;
  5134. #ifdef CARLA_OS_MAC
  5135. case LV2_UI_COCOA:
  5136. carla_stdout("Will use LV2 Cocoa UI for '%s'", pData->name);
  5137. fUI.type = UI::TYPE_EMBED;
  5138. break;
  5139. #endif
  5140. #ifdef CARLA_OS_WIN
  5141. case LV2_UI_WINDOWS:
  5142. carla_stdout("Will use LV2 Windows UI for '%s'", pData->name);
  5143. fUI.type = UI::TYPE_EMBED;
  5144. break;
  5145. #endif
  5146. case LV2_UI_X11:
  5147. #ifdef HAVE_X11
  5148. carla_stdout("Will use LV2 X11 UI for '%s'", pData->name);
  5149. #else
  5150. carla_stdout("Will use LV2 X11 UI for '%s', NOT!", pData->name);
  5151. #endif
  5152. fUI.type = UI::TYPE_EMBED;
  5153. break;
  5154. case LV2_UI_EXTERNAL:
  5155. case LV2_UI_OLD_EXTERNAL:
  5156. carla_stdout("Will use LV2 External UI for '%s'", pData->name);
  5157. fUI.type = UI::TYPE_EXTERNAL;
  5158. break;
  5159. }
  5160. if (fUI.type == UI::TYPE_NULL)
  5161. {
  5162. pData->uiLibClose();
  5163. fUI.descriptor = nullptr;
  5164. fUI.rdfDescriptor = nullptr;
  5165. return;
  5166. }
  5167. // ---------------------------------------------------------------
  5168. // initialize ui data
  5169. CarlaString guiTitle(pData->name);
  5170. guiTitle += " (GUI)";
  5171. fLv2Options.windowTitle = guiTitle.dup();
  5172. fLv2Options.opts[CarlaPluginLV2Options::WindowTitle].size = (uint32_t)std::strlen(fLv2Options.windowTitle);
  5173. fLv2Options.opts[CarlaPluginLV2Options::WindowTitle].value = fLv2Options.windowTitle;
  5174. // ---------------------------------------------------------------
  5175. // initialize ui features (part 1)
  5176. LV2_Extension_Data_Feature* const uiDataFt = new LV2_Extension_Data_Feature;
  5177. uiDataFt->data_access = fDescriptor->extension_data;
  5178. LV2UI_Port_Map* const uiPortMapFt = new LV2UI_Port_Map;
  5179. uiPortMapFt->handle = this;
  5180. uiPortMapFt->port_index = carla_lv2_ui_port_map;
  5181. LV2UI_Resize* const uiResizeFt = new LV2UI_Resize;
  5182. uiResizeFt->handle = this;
  5183. uiResizeFt->ui_resize = carla_lv2_ui_resize;
  5184. LV2UI_Touch* const uiTouchFt = new LV2UI_Touch;
  5185. uiTouchFt->handle = this;
  5186. uiTouchFt->touch = carla_lv2_ui_touch;
  5187. LV2_External_UI_Host* const uiExternalHostFt = new LV2_External_UI_Host;
  5188. uiExternalHostFt->ui_closed = carla_lv2_external_ui_closed;
  5189. uiExternalHostFt->plugin_human_id = fLv2Options.windowTitle;
  5190. // ---------------------------------------------------------------
  5191. // initialize ui features (part 2)
  5192. for (uint32_t j=kFeatureCountPlugin; j < kFeatureCountAll; ++j)
  5193. fFeatures[j] = new LV2_Feature;
  5194. fFeatures[kFeatureIdUiDataAccess]->URI = LV2_DATA_ACCESS_URI;
  5195. fFeatures[kFeatureIdUiDataAccess]->data = uiDataFt;
  5196. fFeatures[kFeatureIdUiInstanceAccess]->URI = LV2_INSTANCE_ACCESS_URI;
  5197. fFeatures[kFeatureIdUiInstanceAccess]->data = fHandle;
  5198. fFeatures[kFeatureIdUiIdleInterface]->URI = LV2_UI__idleInterface;
  5199. fFeatures[kFeatureIdUiIdleInterface]->data = nullptr;
  5200. fFeatures[kFeatureIdUiFixedSize]->URI = LV2_UI__fixedSize;
  5201. fFeatures[kFeatureIdUiFixedSize]->data = nullptr;
  5202. fFeatures[kFeatureIdUiMakeResident]->URI = LV2_UI__makeResident;
  5203. fFeatures[kFeatureIdUiMakeResident]->data = nullptr;
  5204. fFeatures[kFeatureIdUiMakeResident2]->URI = LV2_UI__makeSONameResident;
  5205. fFeatures[kFeatureIdUiMakeResident2]->data = nullptr;
  5206. fFeatures[kFeatureIdUiNoUserResize]->URI = LV2_UI__noUserResize;
  5207. fFeatures[kFeatureIdUiNoUserResize]->data = nullptr;
  5208. fFeatures[kFeatureIdUiParent]->URI = LV2_UI__parent;
  5209. fFeatures[kFeatureIdUiParent]->data = nullptr;
  5210. fFeatures[kFeatureIdUiPortMap]->URI = LV2_UI__portMap;
  5211. fFeatures[kFeatureIdUiPortMap]->data = uiPortMapFt;
  5212. fFeatures[kFeatureIdUiPortSubscribe]->URI = LV2_UI__portSubscribe;
  5213. fFeatures[kFeatureIdUiPortSubscribe]->data = nullptr;
  5214. fFeatures[kFeatureIdUiResize]->URI = LV2_UI__resize;
  5215. fFeatures[kFeatureIdUiResize]->data = uiResizeFt;
  5216. fFeatures[kFeatureIdUiTouch]->URI = LV2_UI__touch;
  5217. fFeatures[kFeatureIdUiTouch]->data = uiTouchFt;
  5218. fFeatures[kFeatureIdExternalUi]->URI = LV2_EXTERNAL_UI__Host;
  5219. fFeatures[kFeatureIdExternalUi]->data = uiExternalHostFt;
  5220. fFeatures[kFeatureIdExternalUiOld]->URI = LV2_EXTERNAL_UI_DEPRECATED_URI;
  5221. fFeatures[kFeatureIdExternalUiOld]->data = uiExternalHostFt;
  5222. // ---------------------------------------------------------------
  5223. // initialize ui extensions
  5224. if (fUI.descriptor->extension_data == nullptr)
  5225. return;
  5226. fExt.uiidle = (const LV2UI_Idle_Interface*)fUI.descriptor->extension_data(LV2_UI__idleInterface);
  5227. fExt.uishow = (const LV2UI_Show_Interface*)fUI.descriptor->extension_data(LV2_UI__showInterface);
  5228. fExt.uiresize = (const LV2UI_Resize*)fUI.descriptor->extension_data(LV2_UI__resize);
  5229. fExt.uiprograms = (const LV2_Programs_UI_Interface*)fUI.descriptor->extension_data(LV2_PROGRAMS__UIInterface);
  5230. // check if invalid
  5231. if (fExt.uiidle != nullptr && fExt.uiidle->idle == nullptr)
  5232. fExt.uiidle = nullptr;
  5233. if (fExt.uishow != nullptr && (fExt.uishow->show == nullptr || fExt.uishow->hide == nullptr))
  5234. fExt.uishow = nullptr;
  5235. if (fExt.uiresize != nullptr && fExt.uiresize->ui_resize == nullptr)
  5236. fExt.uiresize = nullptr;
  5237. if (fExt.uiprograms != nullptr && fExt.uiprograms->select_program == nullptr)
  5238. fExt.uiprograms = nullptr;
  5239. // don't use uiidle if external
  5240. if (fUI.type == UI::TYPE_EXTERNAL)
  5241. fExt.uiidle = nullptr;
  5242. }
  5243. // -------------------------------------------------------------------
  5244. void handleTransferAtom(const uint32_t portIndex, const LV2_Atom* const atom)
  5245. {
  5246. CARLA_SAFE_ASSERT_RETURN(atom != nullptr,);
  5247. carla_debug("CarlaPluginLV2::handleTransferAtom(%i, %p)", portIndex, atom);
  5248. fAtomBufferEvIn.put(atom, portIndex);
  5249. }
  5250. void handleUridMap(const LV2_URID urid, const char* const uri)
  5251. {
  5252. CARLA_SAFE_ASSERT_RETURN(urid != kUridNull,);
  5253. CARLA_SAFE_ASSERT_RETURN(uri != nullptr && uri[0] != '\0',);
  5254. carla_debug("CarlaPluginLV2::handleUridMap(%i v " P_SIZE ", \"%s\")", urid, fCustomURIDs.size()-1, uri);
  5255. const std::size_t uriCount(fCustomURIDs.size());
  5256. if (urid < uriCount)
  5257. {
  5258. const char* const ourURI(carla_lv2_urid_unmap(this, urid));
  5259. CARLA_SAFE_ASSERT_RETURN(ourURI != nullptr && ourURI != kUnmapFallback,);
  5260. if (std::strcmp(ourURI, uri) != 0)
  5261. {
  5262. carla_stderr2("PLUGIN :: wrong URI '%s' vs '%s'", ourURI, uri);
  5263. }
  5264. }
  5265. else
  5266. {
  5267. CARLA_SAFE_ASSERT_RETURN(urid == uriCount,);
  5268. fCustomURIDs.push_back(uri);
  5269. }
  5270. }
  5271. // -------------------------------------------------------------------
  5272. private:
  5273. LV2_Handle fHandle;
  5274. LV2_Handle fHandle2;
  5275. LV2_Feature* fFeatures[kFeatureCountAll+1];
  5276. const LV2_Descriptor* fDescriptor;
  5277. const LV2_RDF_Descriptor* fRdfDescriptor;
  5278. float** fAudioInBuffers;
  5279. float** fAudioOutBuffers;
  5280. float** fCvInBuffers;
  5281. float** fCvOutBuffers;
  5282. float* fParamBuffers;
  5283. bool fNeedsFixedBuffers;
  5284. bool fNeedsUiClose;
  5285. bool fInlineDisplayNeedsRedraw;
  5286. int64_t fInlineDisplayLastRedrawTime;
  5287. int32_t fLatencyIndex; // -1 if invalid
  5288. int fStrictBounds; // -1 unsupported, 0 optional, 1 required
  5289. Lv2AtomRingBuffer fAtomBufferEvIn;
  5290. Lv2AtomRingBuffer fAtomBufferUiOut;
  5291. Lv2AtomRingBuffer fAtomBufferWorkerIn;
  5292. Lv2AtomRingBuffer fAtomBufferWorkerResp;
  5293. LV2_Atom_Forge fAtomForge;
  5294. uint8_t* fAtomBufferUiOutTmpData;
  5295. uint8_t* fAtomBufferWorkerInTmpData;
  5296. CarlaPluginLV2EventData fEventsIn;
  5297. CarlaPluginLV2EventData fEventsOut;
  5298. CarlaPluginLV2Options fLv2Options;
  5299. CarlaPipeServerLV2 fPipeServer;
  5300. std::vector<std::string> fCustomURIDs;
  5301. bool fFirstActive; // first process() call after activate()
  5302. void* fLastStateChunk;
  5303. EngineTimeInfo fLastTimeInfo;
  5304. // if plugin provides path parameter, use it as fake "gui"
  5305. CarlaString fFilePathURI;
  5306. struct Extensions {
  5307. const LV2_Options_Interface* options;
  5308. const LV2_State_Interface* state;
  5309. const LV2_Worker_Interface* worker;
  5310. const LV2_Inline_Display_Interface* inlineDisplay;
  5311. const LV2_Midnam_Interface* midnam;
  5312. const LV2_Programs_Interface* programs;
  5313. const LV2UI_Idle_Interface* uiidle;
  5314. const LV2UI_Show_Interface* uishow;
  5315. const LV2UI_Resize* uiresize;
  5316. const LV2_Programs_UI_Interface* uiprograms;
  5317. Extensions()
  5318. : options(nullptr),
  5319. state(nullptr),
  5320. worker(nullptr),
  5321. inlineDisplay(nullptr),
  5322. midnam(nullptr),
  5323. programs(nullptr),
  5324. uiidle(nullptr),
  5325. uishow(nullptr),
  5326. uiresize(nullptr),
  5327. uiprograms(nullptr) {}
  5328. CARLA_DECLARE_NON_COPY_STRUCT(Extensions);
  5329. } fExt;
  5330. struct UI {
  5331. enum Type {
  5332. TYPE_NULL = 0,
  5333. TYPE_BRIDGE,
  5334. TYPE_EMBED,
  5335. TYPE_EXTERNAL
  5336. };
  5337. Type type;
  5338. LV2UI_Handle handle;
  5339. LV2UI_Widget widget;
  5340. const LV2UI_Descriptor* descriptor;
  5341. const LV2_RDF_UI* rdfDescriptor;
  5342. CarlaPluginUI* window;
  5343. UI()
  5344. : type(TYPE_NULL),
  5345. handle(nullptr),
  5346. widget(nullptr),
  5347. descriptor(nullptr),
  5348. rdfDescriptor(nullptr),
  5349. window(nullptr) {}
  5350. ~UI()
  5351. {
  5352. CARLA_SAFE_ASSERT(handle == nullptr);
  5353. CARLA_SAFE_ASSERT(widget == nullptr);
  5354. CARLA_SAFE_ASSERT(descriptor == nullptr);
  5355. CARLA_SAFE_ASSERT(rdfDescriptor == nullptr);
  5356. CARLA_SAFE_ASSERT(window == nullptr);
  5357. }
  5358. CARLA_DECLARE_NON_COPY_STRUCT(UI);
  5359. } fUI;
  5360. // -------------------------------------------------------------------
  5361. // Event Feature
  5362. static uint32_t carla_lv2_event_ref(LV2_Event_Callback_Data callback_data, LV2_Event* event)
  5363. {
  5364. CARLA_SAFE_ASSERT_RETURN(callback_data != nullptr, 0);
  5365. CARLA_SAFE_ASSERT_RETURN(event != nullptr, 0);
  5366. carla_debug("carla_lv2_event_ref(%p, %p)", callback_data, event);
  5367. return 0;
  5368. }
  5369. static uint32_t carla_lv2_event_unref(LV2_Event_Callback_Data callback_data, LV2_Event* event)
  5370. {
  5371. CARLA_SAFE_ASSERT_RETURN(callback_data != nullptr, 0);
  5372. CARLA_SAFE_ASSERT_RETURN(event != nullptr, 0);
  5373. carla_debug("carla_lv2_event_unref(%p, %p)", callback_data, event);
  5374. return 0;
  5375. }
  5376. // -------------------------------------------------------------------
  5377. // Logs Feature
  5378. static int carla_lv2_log_printf(LV2_Log_Handle handle, LV2_URID type, const char* fmt, ...)
  5379. {
  5380. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, 0);
  5381. CARLA_SAFE_ASSERT_RETURN(type != kUridNull, 0);
  5382. CARLA_SAFE_ASSERT_RETURN(fmt != nullptr, 0);
  5383. #ifndef DEBUG
  5384. if (type == kUridLogTrace)
  5385. return 0;
  5386. #endif
  5387. va_list args;
  5388. va_start(args, fmt);
  5389. const int ret(carla_lv2_log_vprintf(handle, type, fmt, args));
  5390. va_end(args);
  5391. return ret;
  5392. }
  5393. static int carla_lv2_log_vprintf(LV2_Log_Handle handle, LV2_URID type, const char* fmt, va_list ap)
  5394. {
  5395. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, 0);
  5396. CARLA_SAFE_ASSERT_RETURN(type != kUridNull, 0);
  5397. CARLA_SAFE_ASSERT_RETURN(fmt != nullptr, 0);
  5398. int ret = 0;
  5399. switch (type)
  5400. {
  5401. case kUridLogError:
  5402. std::fprintf(stderr, "\x1b[31m");
  5403. ret = std::vfprintf(stderr, fmt, ap);
  5404. std::fprintf(stderr, "\x1b[0m");
  5405. break;
  5406. case kUridLogNote:
  5407. ret = std::vfprintf(stdout, fmt, ap);
  5408. break;
  5409. case kUridLogTrace:
  5410. #ifdef DEBUG
  5411. std::fprintf(stdout, "\x1b[30;1m");
  5412. ret = std::vfprintf(stdout, fmt, ap);
  5413. std::fprintf(stdout, "\x1b[0m");
  5414. #endif
  5415. break;
  5416. case kUridLogWarning:
  5417. ret = std::vfprintf(stderr, fmt, ap);
  5418. break;
  5419. default:
  5420. break;
  5421. }
  5422. return ret;
  5423. }
  5424. // -------------------------------------------------------------------
  5425. // Programs Feature
  5426. static void carla_lv2_program_changed(LV2_Programs_Handle handle, int32_t index)
  5427. {
  5428. CARLA_SAFE_ASSERT_RETURN(handle != nullptr,);
  5429. carla_debug("carla_lv2_program_changed(%p, %i)", handle, index);
  5430. ((CarlaPluginLV2*)handle)->handleProgramChanged(index);
  5431. }
  5432. // -------------------------------------------------------------------
  5433. // Resize Port Feature
  5434. static LV2_Resize_Port_Status carla_lv2_resize_port(LV2_Resize_Port_Feature_Data data, uint32_t index, size_t size)
  5435. {
  5436. CARLA_SAFE_ASSERT_RETURN(data != nullptr, LV2_RESIZE_PORT_ERR_UNKNOWN);
  5437. carla_debug("carla_lv2_program_changed(%p, %i, " P_SIZE ")", data, index, size);
  5438. return ((CarlaPluginLV2*)data)->handleResizePort(index, size);
  5439. }
  5440. // -------------------------------------------------------------------
  5441. // State Feature
  5442. static char* carla_lv2_state_make_path(LV2_State_Make_Path_Handle handle, const char* path)
  5443. {
  5444. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, nullptr);
  5445. CARLA_SAFE_ASSERT_RETURN(path != nullptr && path[0] != '\0', nullptr);
  5446. carla_debug("carla_lv2_state_make_path(%p, \"%s\")", handle, path);
  5447. File file;
  5448. if (File::isAbsolutePath(path))
  5449. file = File(path);
  5450. else
  5451. file = File::getCurrentWorkingDirectory().getChildFile(path);
  5452. file.getParentDirectory().createDirectory();
  5453. return strdup(file.getFullPathName().toRawUTF8());
  5454. }
  5455. static char* carla_lv2_state_map_abstract_path(LV2_State_Map_Path_Handle handle, const char* absolute_path)
  5456. {
  5457. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, strdup(""));
  5458. CARLA_SAFE_ASSERT_RETURN(absolute_path != nullptr && absolute_path[0] != '\0', strdup(""));
  5459. carla_debug("carla_lv2_state_map_abstract_path(%p, \"%s\")", handle, absolute_path);
  5460. // may already be an abstract path
  5461. if (! File::isAbsolutePath(absolute_path))
  5462. return strdup(absolute_path);
  5463. return strdup(File(absolute_path).getRelativePathFrom(File::getCurrentWorkingDirectory()).toRawUTF8());
  5464. }
  5465. static char* carla_lv2_state_map_absolute_path(LV2_State_Map_Path_Handle handle, const char* abstract_path)
  5466. {
  5467. const char* const cwd(File::getCurrentWorkingDirectory().getFullPathName().toRawUTF8());
  5468. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, strdup(cwd));
  5469. CARLA_SAFE_ASSERT_RETURN(abstract_path != nullptr && abstract_path[0] != '\0', strdup(cwd));
  5470. carla_debug("carla_lv2_state_map_absolute_path(%p, \"%s\")", handle, abstract_path);
  5471. // may already be an absolute path
  5472. if (File::isAbsolutePath(abstract_path))
  5473. return strdup(abstract_path);
  5474. return strdup(File::getCurrentWorkingDirectory().getChildFile(abstract_path).getFullPathName().toRawUTF8());
  5475. }
  5476. 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)
  5477. {
  5478. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, LV2_STATE_ERR_UNKNOWN);
  5479. carla_debug("carla_lv2_state_store(%p, %i, %p, " P_SIZE ", %i, %i)", handle, key, value, size, type, flags);
  5480. return ((CarlaPluginLV2*)handle)->handleStateStore(key, value, size, type, flags);
  5481. }
  5482. static const void* carla_lv2_state_retrieve(LV2_State_Handle handle, uint32_t key, size_t* size, uint32_t* type, uint32_t* flags)
  5483. {
  5484. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, nullptr);
  5485. carla_debug("carla_lv2_state_retrieve(%p, %i, %p, %p, %p)", handle, key, size, type, flags);
  5486. return ((CarlaPluginLV2*)handle)->handleStateRetrieve(key, size, type, flags);
  5487. }
  5488. // -------------------------------------------------------------------
  5489. // URI-Map Feature
  5490. static uint32_t carla_lv2_uri_to_id(LV2_URI_Map_Callback_Data data, const char* map, const char* uri)
  5491. {
  5492. carla_debug("carla_lv2_uri_to_id(%p, \"%s\", \"%s\")", data, map, uri);
  5493. return carla_lv2_urid_map((LV2_URID_Map_Handle*)data, uri);
  5494. // unused
  5495. (void)map;
  5496. }
  5497. // -------------------------------------------------------------------
  5498. // URID Feature
  5499. static LV2_URID carla_lv2_urid_map(LV2_URID_Map_Handle handle, const char* uri)
  5500. {
  5501. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, kUridNull);
  5502. CARLA_SAFE_ASSERT_RETURN(uri != nullptr && uri[0] != '\0', kUridNull);
  5503. carla_debug("carla_lv2_urid_map(%p, \"%s\")", handle, uri);
  5504. // Atom types
  5505. if (std::strcmp(uri, LV2_ATOM__Blank) == 0)
  5506. return kUridAtomBlank;
  5507. if (std::strcmp(uri, LV2_ATOM__Bool) == 0)
  5508. return kUridAtomBool;
  5509. if (std::strcmp(uri, LV2_ATOM__Chunk) == 0)
  5510. return kUridAtomChunk;
  5511. if (std::strcmp(uri, LV2_ATOM__Double) == 0)
  5512. return kUridAtomDouble;
  5513. if (std::strcmp(uri, LV2_ATOM__Event) == 0)
  5514. return kUridAtomEvent;
  5515. if (std::strcmp(uri, LV2_ATOM__Float) == 0)
  5516. return kUridAtomFloat;
  5517. if (std::strcmp(uri, LV2_ATOM__Int) == 0)
  5518. return kUridAtomInt;
  5519. if (std::strcmp(uri, LV2_ATOM__Literal) == 0)
  5520. return kUridAtomLiteral;
  5521. if (std::strcmp(uri, LV2_ATOM__Long) == 0)
  5522. return kUridAtomLong;
  5523. if (std::strcmp(uri, LV2_ATOM__Number) == 0)
  5524. return kUridAtomNumber;
  5525. if (std::strcmp(uri, LV2_ATOM__Object) == 0)
  5526. return kUridAtomObject;
  5527. if (std::strcmp(uri, LV2_ATOM__Path) == 0)
  5528. return kUridAtomPath;
  5529. if (std::strcmp(uri, LV2_ATOM__Property) == 0)
  5530. return kUridAtomProperty;
  5531. if (std::strcmp(uri, LV2_ATOM__Resource) == 0)
  5532. return kUridAtomResource;
  5533. if (std::strcmp(uri, LV2_ATOM__Sequence) == 0)
  5534. return kUridAtomSequence;
  5535. if (std::strcmp(uri, LV2_ATOM__Sound) == 0)
  5536. return kUridAtomSound;
  5537. if (std::strcmp(uri, LV2_ATOM__String) == 0)
  5538. return kUridAtomString;
  5539. if (std::strcmp(uri, LV2_ATOM__Tuple) == 0)
  5540. return kUridAtomTuple;
  5541. if (std::strcmp(uri, LV2_ATOM__URI) == 0)
  5542. return kUridAtomURI;
  5543. if (std::strcmp(uri, LV2_ATOM__URID) == 0)
  5544. return kUridAtomURID;
  5545. if (std::strcmp(uri, LV2_ATOM__Vector) == 0)
  5546. return kUridAtomVector;
  5547. if (std::strcmp(uri, LV2_ATOM__atomTransfer) == 0)
  5548. return kUridAtomTransferAtom;
  5549. if (std::strcmp(uri, LV2_ATOM__eventTransfer) == 0)
  5550. return kUridAtomTransferEvent;
  5551. // BufSize types
  5552. if (std::strcmp(uri, LV2_BUF_SIZE__maxBlockLength) == 0)
  5553. return kUridBufMaxLength;
  5554. if (std::strcmp(uri, LV2_BUF_SIZE__minBlockLength) == 0)
  5555. return kUridBufMinLength;
  5556. if (std::strcmp(uri, LV2_BUF_SIZE__nominalBlockLength) == 0)
  5557. return kUridBufNominalLength;
  5558. if (std::strcmp(uri, LV2_BUF_SIZE__sequenceSize) == 0)
  5559. return kUridBufSequenceSize;
  5560. // Log types
  5561. if (std::strcmp(uri, LV2_LOG__Error) == 0)
  5562. return kUridLogError;
  5563. if (std::strcmp(uri, LV2_LOG__Note) == 0)
  5564. return kUridLogNote;
  5565. if (std::strcmp(uri, LV2_LOG__Trace) == 0)
  5566. return kUridLogTrace;
  5567. if (std::strcmp(uri, LV2_LOG__Warning) == 0)
  5568. return kUridLogWarning;
  5569. // Patch types
  5570. if (std::strcmp(uri, LV2_PATCH__Set) == 0)
  5571. return kUridPatchSet;
  5572. if (std::strcmp(uri, LV2_PATCH__property) == 0)
  5573. return kUridPatchPoperty;
  5574. if (std::strcmp(uri, LV2_PATCH__value) == 0)
  5575. return kUridPatchValue;
  5576. // Time types
  5577. if (std::strcmp(uri, LV2_TIME__Position) == 0)
  5578. return kUridTimePosition;
  5579. if (std::strcmp(uri, LV2_TIME__bar) == 0)
  5580. return kUridTimeBar;
  5581. if (std::strcmp(uri, LV2_TIME__barBeat) == 0)
  5582. return kUridTimeBarBeat;
  5583. if (std::strcmp(uri, LV2_TIME__beat) == 0)
  5584. return kUridTimeBeat;
  5585. if (std::strcmp(uri, LV2_TIME__beatUnit) == 0)
  5586. return kUridTimeBeatUnit;
  5587. if (std::strcmp(uri, LV2_TIME__beatsPerBar) == 0)
  5588. return kUridTimeBeatsPerBar;
  5589. if (std::strcmp(uri, LV2_TIME__beatsPerMinute) == 0)
  5590. return kUridTimeBeatsPerMinute;
  5591. if (std::strcmp(uri, LV2_TIME__frame) == 0)
  5592. return kUridTimeFrame;
  5593. if (std::strcmp(uri, LV2_TIME__framesPerSecond) == 0)
  5594. return kUridTimeFramesPerSecond;
  5595. if (std::strcmp(uri, LV2_TIME__speed) == 0)
  5596. return kUridTimeSpeed;
  5597. if (std::strcmp(uri, LV2_KXSTUDIO_PROPERTIES__TimePositionTicksPerBeat) == 0)
  5598. return kUridTimeTicksPerBeat;
  5599. // Others
  5600. if (std::strcmp(uri, LV2_MIDI__MidiEvent) == 0)
  5601. return kUridMidiEvent;
  5602. if (std::strcmp(uri, LV2_PARAMETERS__sampleRate) == 0)
  5603. return kUridParamSampleRate;
  5604. if (std::strcmp(uri, LV2_UI__scaleFactor) == 0)
  5605. return kUridScaleFactor;
  5606. if (std::strcmp(uri, LV2_UI__windowTitle) == 0)
  5607. return kUridWindowTitle;
  5608. // Custom Carla types
  5609. if (std::strcmp(uri, URI_CARLA_ATOM_WORKER_IN) == 0)
  5610. return kUridCarlaAtomWorkerIn;
  5611. if (std::strcmp(uri, URI_CARLA_ATOM_WORKER_RESP) == 0)
  5612. return kUridCarlaAtomWorkerResp;
  5613. if (std::strcmp(uri, LV2_KXSTUDIO_PROPERTIES__TransientWindowId) == 0)
  5614. return kUridCarlaTransientWindowId;
  5615. // Custom plugin types
  5616. return ((CarlaPluginLV2*)handle)->getCustomURID(uri);
  5617. }
  5618. static const char* carla_lv2_urid_unmap(LV2_URID_Map_Handle handle, LV2_URID urid)
  5619. {
  5620. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, nullptr);
  5621. CARLA_SAFE_ASSERT_RETURN(urid != kUridNull, nullptr);
  5622. carla_debug("carla_lv2_urid_unmap(%p, %i)", handle, urid);
  5623. switch (urid)
  5624. {
  5625. // Atom types
  5626. case kUridAtomBlank:
  5627. return LV2_ATOM__Blank;
  5628. case kUridAtomBool:
  5629. return LV2_ATOM__Bool;
  5630. case kUridAtomChunk:
  5631. return LV2_ATOM__Chunk;
  5632. case kUridAtomDouble:
  5633. return LV2_ATOM__Double;
  5634. case kUridAtomEvent:
  5635. return LV2_ATOM__Event;
  5636. case kUridAtomFloat:
  5637. return LV2_ATOM__Float;
  5638. case kUridAtomInt:
  5639. return LV2_ATOM__Int;
  5640. case kUridAtomLiteral:
  5641. return LV2_ATOM__Literal;
  5642. case kUridAtomLong:
  5643. return LV2_ATOM__Long;
  5644. case kUridAtomNumber:
  5645. return LV2_ATOM__Number;
  5646. case kUridAtomObject:
  5647. return LV2_ATOM__Object;
  5648. case kUridAtomPath:
  5649. return LV2_ATOM__Path;
  5650. case kUridAtomProperty:
  5651. return LV2_ATOM__Property;
  5652. case kUridAtomResource:
  5653. return LV2_ATOM__Resource;
  5654. case kUridAtomSequence:
  5655. return LV2_ATOM__Sequence;
  5656. case kUridAtomSound:
  5657. return LV2_ATOM__Sound;
  5658. case kUridAtomString:
  5659. return LV2_ATOM__String;
  5660. case kUridAtomTuple:
  5661. return LV2_ATOM__Tuple;
  5662. case kUridAtomURI:
  5663. return LV2_ATOM__URI;
  5664. case kUridAtomURID:
  5665. return LV2_ATOM__URID;
  5666. case kUridAtomVector:
  5667. return LV2_ATOM__Vector;
  5668. case kUridAtomTransferAtom:
  5669. return LV2_ATOM__atomTransfer;
  5670. case kUridAtomTransferEvent:
  5671. return LV2_ATOM__eventTransfer;
  5672. // BufSize types
  5673. case kUridBufMaxLength:
  5674. return LV2_BUF_SIZE__maxBlockLength;
  5675. case kUridBufMinLength:
  5676. return LV2_BUF_SIZE__minBlockLength;
  5677. case kUridBufNominalLength:
  5678. return LV2_BUF_SIZE__nominalBlockLength;
  5679. case kUridBufSequenceSize:
  5680. return LV2_BUF_SIZE__sequenceSize;
  5681. // Log types
  5682. case kUridLogError:
  5683. return LV2_LOG__Error;
  5684. case kUridLogNote:
  5685. return LV2_LOG__Note;
  5686. case kUridLogTrace:
  5687. return LV2_LOG__Trace;
  5688. case kUridLogWarning:
  5689. return LV2_LOG__Warning;
  5690. // Patch types
  5691. case kUridPatchSet:
  5692. return LV2_PATCH__Set;
  5693. case kUridPatchPoperty:
  5694. return LV2_PATCH__property;
  5695. case kUridPatchValue:
  5696. return LV2_PATCH__value;
  5697. // Time types
  5698. case kUridTimePosition:
  5699. return LV2_TIME__Position;
  5700. case kUridTimeBar:
  5701. return LV2_TIME__bar;
  5702. case kUridTimeBarBeat:
  5703. return LV2_TIME__barBeat;
  5704. case kUridTimeBeat:
  5705. return LV2_TIME__beat;
  5706. case kUridTimeBeatUnit:
  5707. return LV2_TIME__beatUnit;
  5708. case kUridTimeBeatsPerBar:
  5709. return LV2_TIME__beatsPerBar;
  5710. case kUridTimeBeatsPerMinute:
  5711. return LV2_TIME__beatsPerMinute;
  5712. case kUridTimeFrame:
  5713. return LV2_TIME__frame;
  5714. case kUridTimeFramesPerSecond:
  5715. return LV2_TIME__framesPerSecond;
  5716. case kUridTimeSpeed:
  5717. return LV2_TIME__speed;
  5718. case kUridTimeTicksPerBeat:
  5719. return LV2_KXSTUDIO_PROPERTIES__TimePositionTicksPerBeat;
  5720. // Others
  5721. case kUridMidiEvent:
  5722. return LV2_MIDI__MidiEvent;
  5723. case kUridParamSampleRate:
  5724. return LV2_PARAMETERS__sampleRate;
  5725. case kUridScaleFactor:
  5726. return LV2_UI__scaleFactor;
  5727. case kUridWindowTitle:
  5728. return LV2_UI__windowTitle;
  5729. // Custom Carla types
  5730. case kUridCarlaAtomWorkerIn:
  5731. return URI_CARLA_ATOM_WORKER_IN;
  5732. case kUridCarlaAtomWorkerResp:
  5733. return URI_CARLA_ATOM_WORKER_RESP;
  5734. case kUridCarlaTransientWindowId:
  5735. return LV2_KXSTUDIO_PROPERTIES__TransientWindowId;
  5736. }
  5737. // Custom plugin types
  5738. return ((CarlaPluginLV2*)handle)->getCustomURIDString(urid);
  5739. }
  5740. // -------------------------------------------------------------------
  5741. // Worker Feature
  5742. static LV2_Worker_Status carla_lv2_worker_schedule(LV2_Worker_Schedule_Handle handle, uint32_t size, const void* data)
  5743. {
  5744. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, LV2_WORKER_ERR_UNKNOWN);
  5745. carla_debug("carla_lv2_worker_schedule(%p, %i, %p)", handle, size, data);
  5746. return ((CarlaPluginLV2*)handle)->handleWorkerSchedule(size, data);
  5747. }
  5748. static LV2_Worker_Status carla_lv2_worker_respond(LV2_Worker_Respond_Handle handle, uint32_t size, const void* data)
  5749. {
  5750. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, LV2_WORKER_ERR_UNKNOWN);
  5751. carla_debug("carla_lv2_worker_respond(%p, %i, %p)", handle, size, data);
  5752. return ((CarlaPluginLV2*)handle)->handleWorkerRespond(size, data);
  5753. }
  5754. // -------------------------------------------------------------------
  5755. // Inline Display Feature
  5756. static void carla_lv2_inline_display_queue_draw(LV2_Inline_Display_Handle handle)
  5757. {
  5758. CARLA_SAFE_ASSERT_RETURN(handle != nullptr,);
  5759. // carla_debug("carla_lv2_inline_display_queue_draw(%p)", handle);
  5760. ((CarlaPluginLV2*)handle)->handleInlineDisplayQueueRedraw();
  5761. }
  5762. // -------------------------------------------------------------------
  5763. // Midnam Feature
  5764. static void carla_lv2_midnam_update(LV2_Midnam_Handle handle)
  5765. {
  5766. CARLA_SAFE_ASSERT_RETURN(handle != nullptr,);
  5767. carla_stdout("carla_lv2_midnam_update(%p)", handle);
  5768. ((CarlaPluginLV2*)handle)->handleMidnamUpdate();
  5769. }
  5770. // -------------------------------------------------------------------
  5771. // External UI Feature
  5772. static void carla_lv2_external_ui_closed(LV2UI_Controller controller)
  5773. {
  5774. CARLA_SAFE_ASSERT_RETURN(controller != nullptr,);
  5775. carla_debug("carla_lv2_external_ui_closed(%p)", controller);
  5776. ((CarlaPluginLV2*)controller)->handleExternalUIClosed();
  5777. }
  5778. // -------------------------------------------------------------------
  5779. // UI Port-Map Feature
  5780. static uint32_t carla_lv2_ui_port_map(LV2UI_Feature_Handle handle, const char* symbol)
  5781. {
  5782. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, LV2UI_INVALID_PORT_INDEX);
  5783. carla_debug("carla_lv2_ui_port_map(%p, \"%s\")", handle, symbol);
  5784. return ((CarlaPluginLV2*)handle)->handleUIPortMap(symbol);
  5785. }
  5786. // -------------------------------------------------------------------
  5787. // UI Resize Feature
  5788. static int carla_lv2_ui_resize(LV2UI_Feature_Handle handle, int width, int height)
  5789. {
  5790. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, 1);
  5791. carla_debug("carla_lv2_ui_resize(%p, %i, %i)", handle, width, height);
  5792. return ((CarlaPluginLV2*)handle)->handleUIResize(width, height);
  5793. }
  5794. // -------------------------------------------------------------------
  5795. // UI Touch Feature
  5796. static void carla_lv2_ui_touch(LV2UI_Feature_Handle handle, uint32_t port_index, bool touch)
  5797. {
  5798. CARLA_SAFE_ASSERT_RETURN(handle != nullptr,);
  5799. carla_debug("carla_lv2_ui_touch(%p, %u, %s)", handle, port_index, bool2str(touch));
  5800. ((CarlaPluginLV2*)handle)->handleUITouch(port_index, touch);
  5801. }
  5802. // -------------------------------------------------------------------
  5803. // UI Extension
  5804. static void carla_lv2_ui_write_function(LV2UI_Controller controller, uint32_t port_index, uint32_t buffer_size, uint32_t format, const void* buffer)
  5805. {
  5806. CARLA_SAFE_ASSERT_RETURN(controller != nullptr,);
  5807. carla_debug("carla_lv2_ui_write_function(%p, %i, %i, %i, %p)", controller, port_index, buffer_size, format, buffer);
  5808. ((CarlaPluginLV2*)controller)->handleUIWrite(port_index, buffer_size, format, buffer);
  5809. }
  5810. // -------------------------------------------------------------------
  5811. // Lilv State
  5812. static void carla_lilv_set_port_value(const char* port_symbol, void* user_data, const void* value, uint32_t size, uint32_t type)
  5813. {
  5814. CARLA_SAFE_ASSERT_RETURN(user_data != nullptr,);
  5815. carla_debug("carla_lilv_set_port_value(\"%s\", %p, %p, %i, %i", port_symbol, user_data, value, size, type);
  5816. ((CarlaPluginLV2*)user_data)->handleLilvSetPortValue(port_symbol, value, size, type);
  5817. }
  5818. // -------------------------------------------------------------------
  5819. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginLV2)
  5820. };
  5821. // -------------------------------------------------------------------------------------------------------------------
  5822. bool CarlaPipeServerLV2::msgReceived(const char* const msg) noexcept
  5823. {
  5824. if (std::strcmp(msg, "exiting") == 0)
  5825. {
  5826. closePipeServer();
  5827. fUiState = UiHide;
  5828. return true;
  5829. }
  5830. if (std::strcmp(msg, "control") == 0)
  5831. {
  5832. uint32_t index;
  5833. float value;
  5834. CARLA_SAFE_ASSERT_RETURN(readNextLineAsUInt(index), true);
  5835. CARLA_SAFE_ASSERT_RETURN(readNextLineAsFloat(value), true);
  5836. try {
  5837. kPlugin->handleUIWrite(index, sizeof(float), kUridNull, &value);
  5838. } CARLA_SAFE_EXCEPTION("magReceived control");
  5839. return true;
  5840. }
  5841. if (std::strcmp(msg, "atom") == 0)
  5842. {
  5843. uint32_t index, size;
  5844. const char* base64atom;
  5845. CARLA_SAFE_ASSERT_RETURN(readNextLineAsUInt(index), true);
  5846. CARLA_SAFE_ASSERT_RETURN(readNextLineAsUInt(size), true);
  5847. CARLA_SAFE_ASSERT_RETURN(readNextLineAsString(base64atom), true);
  5848. std::vector<uint8_t> chunk(carla_getChunkFromBase64String(base64atom));
  5849. delete[] base64atom;
  5850. CARLA_SAFE_ASSERT_RETURN(chunk.size() >= sizeof(LV2_Atom), true);
  5851. #ifdef CARLA_PROPER_CPP11_SUPPORT
  5852. const LV2_Atom* const atom((const LV2_Atom*)chunk.data());
  5853. #else
  5854. const LV2_Atom* const atom((const LV2_Atom*)&chunk.front());
  5855. #endif
  5856. CARLA_SAFE_ASSERT_RETURN(lv2_atom_total_size(atom) == chunk.size(), true);
  5857. try {
  5858. kPlugin->handleUIWrite(index, lv2_atom_total_size(atom), kUridAtomTransferEvent, atom);
  5859. } CARLA_SAFE_EXCEPTION("magReceived atom");
  5860. return true;
  5861. }
  5862. if (std::strcmp(msg, "program") == 0)
  5863. {
  5864. uint32_t index;
  5865. CARLA_SAFE_ASSERT_RETURN(readNextLineAsUInt(index), true);
  5866. try {
  5867. kPlugin->setMidiProgram(static_cast<int32_t>(index), false, true, true, false);
  5868. } CARLA_SAFE_EXCEPTION("msgReceived program");
  5869. return true;
  5870. }
  5871. if (std::strcmp(msg, "urid") == 0)
  5872. {
  5873. uint32_t urid;
  5874. const char* uri;
  5875. CARLA_SAFE_ASSERT_RETURN(readNextLineAsUInt(urid), true);
  5876. CARLA_SAFE_ASSERT_RETURN(readNextLineAsString(uri), true);
  5877. if (urid != 0)
  5878. {
  5879. try {
  5880. kPlugin->handleUridMap(urid, uri);
  5881. } CARLA_SAFE_EXCEPTION("msgReceived urid");
  5882. }
  5883. delete[] uri;
  5884. return true;
  5885. }
  5886. if (std::strcmp(msg, "reloadprograms") == 0)
  5887. {
  5888. int32_t index;
  5889. CARLA_SAFE_ASSERT_RETURN(readNextLineAsInt(index), true);
  5890. try {
  5891. kPlugin->handleProgramChanged(index);
  5892. } CARLA_SAFE_EXCEPTION("handleProgramChanged");
  5893. return true;
  5894. }
  5895. return false;
  5896. }
  5897. // -------------------------------------------------------------------------------------------------------------------
  5898. CarlaPlugin* CarlaPlugin::newLV2(const Initializer& init)
  5899. {
  5900. carla_debug("CarlaPlugin::newLV2({%p, \"%s\", \"%s\", " P_INT64 "})", init.engine, init.name, init.label, init.uniqueId);
  5901. CarlaPluginLV2* const plugin(new CarlaPluginLV2(init.engine, init.id));
  5902. if (! plugin->init(init.name, init.label, init.options))
  5903. {
  5904. delete plugin;
  5905. return nullptr;
  5906. }
  5907. return plugin;
  5908. }
  5909. // used in CarlaStandalone.cpp
  5910. const void* carla_render_inline_display_lv2(CarlaPlugin* plugin, uint32_t width, uint32_t height);
  5911. const void* carla_render_inline_display_lv2(CarlaPlugin* plugin, uint32_t width, uint32_t height)
  5912. {
  5913. CarlaPluginLV2* const lv2Plugin = (CarlaPluginLV2*)plugin;
  5914. return lv2Plugin->renderInlineDisplay(width, height);
  5915. }
  5916. // -------------------------------------------------------------------------------------------------------------------
  5917. CARLA_BACKEND_END_NAMESPACE