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.

8227 lines
302KB

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