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.

7768 lines
285KB

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