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.

7804 lines
287KB

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