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.

7824 lines
288KB

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