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.

7790 lines
286KB

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