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.

7898 lines
291KB

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