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.

8207 lines
300KB

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