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.

7236 lines
265KB

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