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.

8224 lines
301KB

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