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.

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