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.

7819 lines
288KB

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