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.

7826 lines
288KB

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