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.

8217 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. }
  2588. else if (rdfParam.Flags & LV2_PARAMETER_FLAG_OUTPUT)
  2589. {
  2590. pData->param.data[j].type = PARAMETER_OUTPUT;
  2591. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  2592. pData->param.data[j].hints |= PARAMETER_IS_AUTOMABLE;
  2593. needsCtrlOut = true;
  2594. hasPatchParameterOutputs = true;
  2595. }
  2596. pData->param.ranges[j].min = min;
  2597. pData->param.ranges[j].max = max;
  2598. pData->param.ranges[j].def = def;
  2599. pData->param.ranges[j].step = step;
  2600. pData->param.ranges[j].stepSmall = stepSmall;
  2601. pData->param.ranges[j].stepLarge = stepLarge;
  2602. fParamBuffers[j] = def;
  2603. }
  2604. if (needsCtrlIn)
  2605. {
  2606. portName.clear();
  2607. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  2608. {
  2609. portName = pData->name;
  2610. portName += ":";
  2611. }
  2612. portName += "events-in";
  2613. portName.truncate(portNameSize);
  2614. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, 0);
  2615. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2616. pData->event.cvSourcePorts = pData->client->createCVSourcePorts();
  2617. #endif
  2618. }
  2619. if (needsCtrlOut)
  2620. {
  2621. portName.clear();
  2622. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  2623. {
  2624. portName = pData->name;
  2625. portName += ":";
  2626. }
  2627. portName += "events-out";
  2628. portName.truncate(portNameSize);
  2629. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, 0);
  2630. }
  2631. if (fExt.worker != nullptr && fEventsIn.ctrl != nullptr)
  2632. {
  2633. fAtomBufferWorkerIn.createBuffer(eventBufferSize);
  2634. fAtomBufferWorkerResp.createBuffer(eventBufferSize);
  2635. fAtomBufferWorkerInTmpData = new uint8_t[fAtomBufferWorkerIn.getSize()];
  2636. }
  2637. if (fRdfDescriptor->ParameterCount > 0 ||
  2638. (fUI.type != UI::TYPE_NULL && fEventsIn.count > 0 && (fEventsIn.data[0].type & CARLA_EVENT_DATA_ATOM) != 0))
  2639. fAtomBufferEvIn.createBuffer(eventBufferSize);
  2640. if (hasPatchParameterOutputs ||
  2641. (fUI.type != UI::TYPE_NULL && fEventsOut.count > 0 && (fEventsOut.data[0].type & CARLA_EVENT_DATA_ATOM) != 0))
  2642. {
  2643. fAtomBufferUiOut.createBuffer(std::min(eventBufferSize*32, 1638400U));
  2644. fAtomBufferUiOutTmpData = new uint8_t[fAtomBufferUiOut.getSize()];
  2645. }
  2646. if (fEventsIn.ctrl != nullptr && fEventsIn.ctrl->port == nullptr)
  2647. fEventsIn.ctrl->port = pData->event.portIn;
  2648. if (fEventsOut.ctrl != nullptr && fEventsOut.ctrl->port == nullptr)
  2649. fEventsOut.ctrl->port = pData->event.portOut;
  2650. if (fEventsIn.ctrl != nullptr && fExt.midnam != nullptr)
  2651. {
  2652. if (char* const midnam = fExt.midnam->midnam(fHandle))
  2653. {
  2654. fEventsIn.ctrl->port->setMetaData("http://www.midi.org/dtds/MIDINameDocument10.dtd",
  2655. midnam, "text/xml");
  2656. if (fExt.midnam->free != nullptr)
  2657. fExt.midnam->free(midnam);
  2658. }
  2659. }
  2660. if (forcedStereoIn || forcedStereoOut)
  2661. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  2662. else
  2663. pData->options &= ~PLUGIN_OPTION_FORCE_STEREO;
  2664. // plugin hints
  2665. pData->hints = (pData->hints & PLUGIN_HAS_INLINE_DISPLAY) ? PLUGIN_HAS_INLINE_DISPLAY : 0
  2666. | (pData->hints & PLUGIN_NEEDS_UI_MAIN_THREAD) ? PLUGIN_NEEDS_UI_MAIN_THREAD : 0;
  2667. if (isRealtimeSafe())
  2668. pData->hints |= PLUGIN_IS_RTSAFE;
  2669. if (fUI.type != UI::TYPE_NULL || fFilePathURI.isNotEmpty())
  2670. {
  2671. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  2672. if (fUI.type == UI::TYPE_EMBED || fUI.type == UI::TYPE_EXTERNAL)
  2673. pData->hints |= PLUGIN_NEEDS_UI_MAIN_THREAD;
  2674. }
  2675. if (LV2_IS_GENERATOR(fRdfDescriptor->Type[0], fRdfDescriptor->Type[1]))
  2676. pData->hints |= PLUGIN_IS_SYNTH;
  2677. if (aOuts > 0 && (aIns == aOuts || aIns == 1))
  2678. pData->hints |= PLUGIN_CAN_DRYWET;
  2679. if (aOuts > 0)
  2680. pData->hints |= PLUGIN_CAN_VOLUME;
  2681. if (aOuts >= 2 && aOuts % 2 == 0)
  2682. pData->hints |= PLUGIN_CAN_BALANCE;
  2683. // extra plugin hints
  2684. pData->extraHints = 0x0;
  2685. // check initial latency
  2686. findInitialLatencyValue(aIns, cvIns, aOuts, cvOuts);
  2687. bufferSizeChanged(pData->engine->getBufferSize());
  2688. reloadPrograms(true);
  2689. evIns.clear();
  2690. evOuts.clear();
  2691. if (pData->active)
  2692. activate();
  2693. carla_debug("CarlaPluginLV2::reload() - end");
  2694. }
  2695. void findInitialLatencyValue(const uint32_t aIns,
  2696. const uint32_t cvIns,
  2697. const uint32_t aOuts,
  2698. const uint32_t cvOuts) const
  2699. {
  2700. if (fLatencyIndex < 0)
  2701. return;
  2702. // we need to pre-run the plugin so it can update its latency control-port
  2703. const uint32_t bufferSize = static_cast<uint32_t>(fLv2Options.nominalBufferSize);
  2704. float tmpIn [( aIns+cvIns > 0) ? aIns+cvIns : 1][bufferSize];
  2705. float tmpOut[(aOuts+cvOuts > 0) ? aOuts+cvOuts : 1][bufferSize];
  2706. {
  2707. uint32_t i=0;
  2708. for (; i < aIns; ++i)
  2709. {
  2710. carla_zeroFloats(tmpIn[i], bufferSize);
  2711. try {
  2712. fDescriptor->connect_port(fHandle, pData->audioIn.ports[i].rindex, tmpIn[i]);
  2713. } CARLA_SAFE_EXCEPTION("LV2 connect_port latency audio input");
  2714. }
  2715. for (uint32_t j=0; j < cvIns; ++i, ++j)
  2716. {
  2717. carla_zeroFloats(tmpIn[i], bufferSize);
  2718. try {
  2719. fDescriptor->connect_port(fHandle, pData->cvIn.ports[j].rindex, tmpIn[i]);
  2720. } CARLA_SAFE_EXCEPTION("LV2 connect_port latency cv input");
  2721. }
  2722. }
  2723. {
  2724. uint32_t i=0;
  2725. for (; i < aOuts; ++i)
  2726. {
  2727. carla_zeroFloats(tmpOut[i], bufferSize);
  2728. try {
  2729. fDescriptor->connect_port(fHandle, pData->audioOut.ports[i].rindex, tmpOut[i]);
  2730. } CARLA_SAFE_EXCEPTION("LV2 connect_port latency audio output");
  2731. }
  2732. for (uint32_t j=0; j < cvOuts; ++i, ++j)
  2733. {
  2734. carla_zeroFloats(tmpOut[i], bufferSize);
  2735. try {
  2736. fDescriptor->connect_port(fHandle, pData->cvOut.ports[j].rindex, tmpOut[i]);
  2737. } CARLA_SAFE_EXCEPTION("LV2 connect_port latency cv output");
  2738. }
  2739. }
  2740. if (fDescriptor->activate != nullptr)
  2741. {
  2742. try {
  2743. fDescriptor->activate(fHandle);
  2744. } CARLA_SAFE_EXCEPTION("LV2 latency activate");
  2745. }
  2746. try {
  2747. fDescriptor->run(fHandle, bufferSize);
  2748. } CARLA_SAFE_EXCEPTION("LV2 latency run");
  2749. if (fDescriptor->deactivate != nullptr)
  2750. {
  2751. try {
  2752. fDescriptor->deactivate(fHandle);
  2753. } CARLA_SAFE_EXCEPTION("LV2 latency deactivate");
  2754. }
  2755. // done, let's get the value
  2756. if (const uint32_t latency = getLatencyInFrames())
  2757. {
  2758. pData->client->setLatency(latency);
  2759. #ifndef BUILD_BRIDGE
  2760. pData->latency.recreateBuffers(std::max(aIns, aOuts), latency);
  2761. #endif
  2762. }
  2763. }
  2764. void reloadPrograms(const bool doInit) override
  2765. {
  2766. carla_debug("CarlaPluginLV2::reloadPrograms(%s)", bool2str(doInit));
  2767. const uint32_t oldCount = pData->midiprog.count;
  2768. const int32_t current = pData->midiprog.current;
  2769. // special LV2 programs handling
  2770. if (doInit)
  2771. {
  2772. pData->prog.clear();
  2773. const uint32_t presetCount(fRdfDescriptor->PresetCount);
  2774. if (presetCount > 0)
  2775. {
  2776. pData->prog.createNew(presetCount);
  2777. for (uint32_t i=0; i < presetCount; ++i)
  2778. pData->prog.names[i] = carla_strdup(fRdfDescriptor->Presets[i].Label);
  2779. }
  2780. }
  2781. // Delete old programs
  2782. pData->midiprog.clear();
  2783. // Query new programs
  2784. uint32_t newCount = 0;
  2785. if (fExt.programs != nullptr && fExt.programs->get_program != nullptr && fExt.programs->select_program != nullptr)
  2786. {
  2787. for (; fExt.programs->get_program(fHandle, newCount);)
  2788. ++newCount;
  2789. }
  2790. if (newCount > 0)
  2791. {
  2792. pData->midiprog.createNew(newCount);
  2793. // Update data
  2794. for (uint32_t i=0; i < newCount; ++i)
  2795. {
  2796. const LV2_Program_Descriptor* const pdesc(fExt.programs->get_program(fHandle, i));
  2797. CARLA_SAFE_ASSERT_CONTINUE(pdesc != nullptr);
  2798. CARLA_SAFE_ASSERT(pdesc->name != nullptr);
  2799. pData->midiprog.data[i].bank = pdesc->bank;
  2800. pData->midiprog.data[i].program = pdesc->program;
  2801. pData->midiprog.data[i].name = carla_strdup(pdesc->name);
  2802. }
  2803. }
  2804. if (doInit)
  2805. {
  2806. if (newCount > 0)
  2807. {
  2808. setMidiProgram(0, false, false, false, true);
  2809. }
  2810. else if (fHasLoadDefaultState)
  2811. {
  2812. // load default state
  2813. if (LilvState* const state = Lv2WorldClass::getInstance().getStateFromURI(fDescriptor->URI,
  2814. (const LV2_URID_Map*)fFeatures[kFeatureIdUridMap]->data))
  2815. {
  2816. lilv_state_restore(state, fExt.state, fHandle, carla_lilv_set_port_value, this, 0, fFeatures);
  2817. if (fHandle2 != nullptr)
  2818. lilv_state_restore(state, fExt.state, fHandle2, carla_lilv_set_port_value, this, 0, fFeatures);
  2819. lilv_state_free(state);
  2820. }
  2821. }
  2822. }
  2823. else
  2824. {
  2825. // Check if current program is invalid
  2826. bool programChanged = false;
  2827. if (newCount == oldCount+1)
  2828. {
  2829. // one midi program added, probably created by user
  2830. pData->midiprog.current = static_cast<int32_t>(oldCount);
  2831. programChanged = true;
  2832. }
  2833. else if (current < 0 && newCount > 0)
  2834. {
  2835. // programs exist now, but not before
  2836. pData->midiprog.current = 0;
  2837. programChanged = true;
  2838. }
  2839. else if (current >= 0 && newCount == 0)
  2840. {
  2841. // programs existed before, but not anymore
  2842. pData->midiprog.current = -1;
  2843. programChanged = true;
  2844. }
  2845. else if (current >= static_cast<int32_t>(newCount))
  2846. {
  2847. // current midi program > count
  2848. pData->midiprog.current = 0;
  2849. programChanged = true;
  2850. }
  2851. else
  2852. {
  2853. // no change
  2854. pData->midiprog.current = current;
  2855. }
  2856. if (programChanged)
  2857. setMidiProgram(pData->midiprog.current, true, true, true, false);
  2858. pData->engine->callback(true, true, ENGINE_CALLBACK_RELOAD_PROGRAMS, pData->id, 0, 0, 0, 0.0f, nullptr);
  2859. }
  2860. }
  2861. // -------------------------------------------------------------------
  2862. // Plugin processing
  2863. void activate() noexcept override
  2864. {
  2865. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr,);
  2866. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr,);
  2867. if (fDescriptor->activate != nullptr)
  2868. {
  2869. try {
  2870. fDescriptor->activate(fHandle);
  2871. } CARLA_SAFE_EXCEPTION("LV2 activate");
  2872. if (fHandle2 != nullptr)
  2873. {
  2874. try {
  2875. fDescriptor->activate(fHandle2);
  2876. } CARLA_SAFE_EXCEPTION("LV2 activate #2");
  2877. }
  2878. }
  2879. fFirstActive = true;
  2880. }
  2881. void deactivate() noexcept override
  2882. {
  2883. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr,);
  2884. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr,);
  2885. if (fDescriptor->deactivate != nullptr)
  2886. {
  2887. try {
  2888. fDescriptor->deactivate(fHandle);
  2889. } CARLA_SAFE_EXCEPTION("LV2 deactivate");
  2890. if (fHandle2 != nullptr)
  2891. {
  2892. try {
  2893. fDescriptor->deactivate(fHandle2);
  2894. } CARLA_SAFE_EXCEPTION("LV2 deactivate #2");
  2895. }
  2896. }
  2897. }
  2898. void process(const float* const* const audioIn, float** const audioOut,
  2899. const float* const* const cvIn, float** const cvOut, const uint32_t frames) override
  2900. {
  2901. // --------------------------------------------------------------------------------------------------------
  2902. // Check if active
  2903. if (! pData->active)
  2904. {
  2905. // disable any output sound
  2906. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  2907. carla_zeroFloats(audioOut[i], frames);
  2908. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  2909. carla_zeroFloats(cvOut[i], frames);
  2910. return;
  2911. }
  2912. // --------------------------------------------------------------------------------------------------------
  2913. // Event itenerators from different APIs (input)
  2914. LV2_Atom_Buffer_Iterator evInAtomIters[fEventsIn.count];
  2915. LV2_Event_Iterator evInEventIters[fEventsIn.count];
  2916. LV2_MIDIState evInMidiStates[fEventsIn.count];
  2917. for (uint32_t i=0; i < fEventsIn.count; ++i)
  2918. {
  2919. if (fEventsIn.data[i].type & CARLA_EVENT_DATA_ATOM)
  2920. {
  2921. lv2_atom_buffer_reset(fEventsIn.data[i].atom, true);
  2922. lv2_atom_buffer_begin(&evInAtomIters[i], fEventsIn.data[i].atom);
  2923. }
  2924. else if (fEventsIn.data[i].type & CARLA_EVENT_DATA_EVENT)
  2925. {
  2926. lv2_event_buffer_reset(fEventsIn.data[i].event, LV2_EVENT_AUDIO_STAMP, fEventsIn.data[i].event->data);
  2927. lv2_event_begin(&evInEventIters[i], fEventsIn.data[i].event);
  2928. }
  2929. else if (fEventsIn.data[i].type & CARLA_EVENT_DATA_MIDI_LL)
  2930. {
  2931. fEventsIn.data[i].midi.event_count = 0;
  2932. fEventsIn.data[i].midi.size = 0;
  2933. evInMidiStates[i].midi = &fEventsIn.data[i].midi;
  2934. evInMidiStates[i].frame_count = frames;
  2935. evInMidiStates[i].position = 0;
  2936. }
  2937. }
  2938. for (uint32_t i=0; i < fEventsOut.count; ++i)
  2939. {
  2940. if (fEventsOut.data[i].type & CARLA_EVENT_DATA_ATOM)
  2941. {
  2942. lv2_atom_buffer_reset(fEventsOut.data[i].atom, false);
  2943. }
  2944. else if (fEventsOut.data[i].type & CARLA_EVENT_DATA_EVENT)
  2945. {
  2946. lv2_event_buffer_reset(fEventsOut.data[i].event, LV2_EVENT_AUDIO_STAMP, fEventsOut.data[i].event->data);
  2947. }
  2948. else if (fEventsOut.data[i].type & CARLA_EVENT_DATA_MIDI_LL)
  2949. {
  2950. // not needed
  2951. }
  2952. }
  2953. // --------------------------------------------------------------------------------------------------------
  2954. // Check if needs reset
  2955. if (pData->needsReset)
  2956. {
  2957. if (fEventsIn.ctrl != nullptr && (fEventsIn.ctrl->type & CARLA_EVENT_TYPE_MIDI) != 0)
  2958. {
  2959. const uint32_t j = fEventsIn.ctrlIndex;
  2960. CARLA_ASSERT(j < fEventsIn.count);
  2961. uint8_t midiData[3] = { 0, 0, 0 };
  2962. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  2963. {
  2964. for (uint8_t i=0; i < MAX_MIDI_CHANNELS; ++i)
  2965. {
  2966. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (i & MIDI_CHANNEL_BIT));
  2967. midiData[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  2968. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  2969. lv2_atom_buffer_write(&evInAtomIters[j], 0, 0, kUridMidiEvent, 3, midiData);
  2970. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  2971. lv2_event_write(&evInEventIters[j], 0, 0, kUridMidiEvent, 3, midiData);
  2972. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  2973. lv2midi_put_event(&evInMidiStates[j], 0.0, 3, midiData);
  2974. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (i & MIDI_CHANNEL_BIT));
  2975. midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  2976. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  2977. lv2_atom_buffer_write(&evInAtomIters[j], 0, 0, kUridMidiEvent, 3, midiData);
  2978. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  2979. lv2_event_write(&evInEventIters[j], 0, 0, kUridMidiEvent, 3, midiData);
  2980. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  2981. lv2midi_put_event(&evInMidiStates[j], 0.0, 3, midiData);
  2982. }
  2983. }
  2984. else if (pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  2985. {
  2986. for (uint8_t k=0; k < MAX_MIDI_NOTE; ++k)
  2987. {
  2988. midiData[0] = uint8_t(MIDI_STATUS_NOTE_OFF | (pData->ctrlChannel & MIDI_CHANNEL_BIT));
  2989. midiData[1] = k;
  2990. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  2991. lv2_atom_buffer_write(&evInAtomIters[j], 0, 0, kUridMidiEvent, 3, midiData);
  2992. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  2993. lv2_event_write(&evInEventIters[j], 0, 0, kUridMidiEvent, 3, midiData);
  2994. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  2995. lv2midi_put_event(&evInMidiStates[j], 0.0, 3, midiData);
  2996. }
  2997. }
  2998. }
  2999. pData->needsReset = false;
  3000. }
  3001. // --------------------------------------------------------------------------------------------------------
  3002. // TimeInfo
  3003. const EngineTimeInfo timeInfo(pData->engine->getTimeInfo());
  3004. if (fFirstActive || fLastTimeInfo != timeInfo)
  3005. {
  3006. bool doPostRt;
  3007. int32_t rindex;
  3008. const double barBeat = static_cast<double>(timeInfo.bbt.beat - 1)
  3009. + (timeInfo.bbt.tick / timeInfo.bbt.ticksPerBeat);
  3010. // update input ports
  3011. for (uint32_t k=0; k < pData->param.count; ++k)
  3012. {
  3013. if (pData->param.data[k].type != PARAMETER_INPUT)
  3014. continue;
  3015. if (pData->param.special[k] != PARAMETER_SPECIAL_TIME)
  3016. continue;
  3017. doPostRt = false;
  3018. rindex = pData->param.data[k].rindex;
  3019. CARLA_SAFE_ASSERT_CONTINUE(rindex >= 0 && rindex < static_cast<int32_t>(fRdfDescriptor->PortCount));
  3020. switch (fRdfDescriptor->Ports[rindex].Designation)
  3021. {
  3022. // Non-BBT
  3023. case LV2_PORT_DESIGNATION_TIME_SPEED:
  3024. if (fLastTimeInfo.playing != timeInfo.playing)
  3025. {
  3026. fParamBuffers[k] = timeInfo.playing ? 1.0f : 0.0f;
  3027. doPostRt = true;
  3028. }
  3029. break;
  3030. case LV2_PORT_DESIGNATION_TIME_FRAME:
  3031. if (fLastTimeInfo.frame != timeInfo.frame)
  3032. {
  3033. fParamBuffers[k] = static_cast<float>(timeInfo.frame);
  3034. doPostRt = true;
  3035. }
  3036. break;
  3037. case LV2_PORT_DESIGNATION_TIME_FRAMES_PER_SECOND:
  3038. break;
  3039. // BBT
  3040. case LV2_PORT_DESIGNATION_TIME_BAR:
  3041. if (timeInfo.bbt.valid && fLastTimeInfo.bbt.bar != timeInfo.bbt.bar)
  3042. {
  3043. fParamBuffers[k] = static_cast<float>(timeInfo.bbt.bar - 1);
  3044. doPostRt = true;
  3045. }
  3046. break;
  3047. case LV2_PORT_DESIGNATION_TIME_BAR_BEAT:
  3048. if (timeInfo.bbt.valid && (carla_isNotEqual(fLastTimeInfo.bbt.tick, timeInfo.bbt.tick) ||
  3049. fLastTimeInfo.bbt.beat != timeInfo.bbt.beat))
  3050. {
  3051. fParamBuffers[k] = static_cast<float>(barBeat);
  3052. doPostRt = true;
  3053. }
  3054. break;
  3055. case LV2_PORT_DESIGNATION_TIME_BEAT:
  3056. if (timeInfo.bbt.valid && fLastTimeInfo.bbt.beat != timeInfo.bbt.beat)
  3057. {
  3058. fParamBuffers[k] = static_cast<float>(timeInfo.bbt.beat - 1);
  3059. doPostRt = true;
  3060. }
  3061. break;
  3062. case LV2_PORT_DESIGNATION_TIME_BEAT_UNIT:
  3063. if (timeInfo.bbt.valid && carla_isNotEqual(fLastTimeInfo.bbt.beatType, timeInfo.bbt.beatType))
  3064. {
  3065. fParamBuffers[k] = timeInfo.bbt.beatType;
  3066. doPostRt = true;
  3067. }
  3068. break;
  3069. case LV2_PORT_DESIGNATION_TIME_BEATS_PER_BAR:
  3070. if (timeInfo.bbt.valid && carla_isNotEqual(fLastTimeInfo.bbt.beatsPerBar, timeInfo.bbt.beatsPerBar))
  3071. {
  3072. fParamBuffers[k] = timeInfo.bbt.beatsPerBar;
  3073. doPostRt = true;
  3074. }
  3075. break;
  3076. case LV2_PORT_DESIGNATION_TIME_BEATS_PER_MINUTE:
  3077. if (timeInfo.bbt.valid && carla_isNotEqual(fLastTimeInfo.bbt.beatsPerMinute, timeInfo.bbt.beatsPerMinute))
  3078. {
  3079. fParamBuffers[k] = static_cast<float>(timeInfo.bbt.beatsPerMinute);
  3080. doPostRt = true;
  3081. }
  3082. break;
  3083. case LV2_PORT_DESIGNATION_TIME_TICKS_PER_BEAT:
  3084. if (timeInfo.bbt.valid && carla_isNotEqual(fLastTimeInfo.bbt.ticksPerBeat, timeInfo.bbt.ticksPerBeat))
  3085. {
  3086. fParamBuffers[k] = static_cast<float>(timeInfo.bbt.ticksPerBeat);
  3087. doPostRt = true;
  3088. }
  3089. break;
  3090. }
  3091. if (doPostRt)
  3092. pData->postponeParameterChangeRtEvent(true, static_cast<int32_t>(k), fParamBuffers[k]);
  3093. }
  3094. for (uint32_t i=0; i < fEventsIn.count; ++i)
  3095. {
  3096. if ((fEventsIn.data[i].type & CARLA_EVENT_DATA_ATOM) == 0 || (fEventsIn.data[i].type & CARLA_EVENT_TYPE_TIME) == 0)
  3097. continue;
  3098. uint8_t timeInfoBuf[256];
  3099. LV2_Atom_Forge atomForge;
  3100. initAtomForge(atomForge);
  3101. lv2_atom_forge_set_buffer(&atomForge, timeInfoBuf, sizeof(timeInfoBuf));
  3102. LV2_Atom_Forge_Frame forgeFrame;
  3103. lv2_atom_forge_object(&atomForge, &forgeFrame, kUridNull, kUridTimePosition);
  3104. lv2_atom_forge_key(&atomForge, kUridTimeSpeed);
  3105. lv2_atom_forge_float(&atomForge, timeInfo.playing ? 1.0f : 0.0f);
  3106. lv2_atom_forge_key(&atomForge, kUridTimeFrame);
  3107. lv2_atom_forge_long(&atomForge, static_cast<int64_t>(timeInfo.frame));
  3108. if (timeInfo.bbt.valid)
  3109. {
  3110. lv2_atom_forge_key(&atomForge, kUridTimeBar);
  3111. lv2_atom_forge_long(&atomForge, timeInfo.bbt.bar - 1);
  3112. lv2_atom_forge_key(&atomForge, kUridTimeBarBeat);
  3113. lv2_atom_forge_float(&atomForge, static_cast<float>(barBeat));
  3114. lv2_atom_forge_key(&atomForge, kUridTimeBeat);
  3115. lv2_atom_forge_double(&atomForge, timeInfo.bbt.beat - 1);
  3116. lv2_atom_forge_key(&atomForge, kUridTimeBeatUnit);
  3117. lv2_atom_forge_int(&atomForge, static_cast<int32_t>(timeInfo.bbt.beatType));
  3118. lv2_atom_forge_key(&atomForge, kUridTimeBeatsPerBar);
  3119. lv2_atom_forge_float(&atomForge, timeInfo.bbt.beatsPerBar);
  3120. lv2_atom_forge_key(&atomForge, kUridTimeBeatsPerMinute);
  3121. lv2_atom_forge_float(&atomForge, static_cast<float>(timeInfo.bbt.beatsPerMinute));
  3122. lv2_atom_forge_key(&atomForge, kUridTimeTicksPerBeat);
  3123. lv2_atom_forge_double(&atomForge, timeInfo.bbt.ticksPerBeat);
  3124. }
  3125. lv2_atom_forge_pop(&atomForge, &forgeFrame);
  3126. LV2_Atom* const atom((LV2_Atom*)timeInfoBuf);
  3127. CARLA_SAFE_ASSERT_BREAK(atom->size < 256);
  3128. // send only deprecated blank object for now
  3129. lv2_atom_buffer_write(&evInAtomIters[i], 0, 0, kUridAtomBlank, atom->size, LV2_ATOM_BODY_CONST(atom));
  3130. // for atom:object
  3131. //lv2_atom_buffer_write(&evInAtomIters[i], 0, 0, atom->type, atom->size, LV2_ATOM_BODY_CONST(atom));
  3132. }
  3133. pData->postRtEvents.trySplice();
  3134. fLastTimeInfo = timeInfo;
  3135. }
  3136. // --------------------------------------------------------------------------------------------------------
  3137. // Event Input and Processing
  3138. if (fEventsIn.ctrl != nullptr)
  3139. {
  3140. // ----------------------------------------------------------------------------------------------------
  3141. // Message Input
  3142. if (fAtomBufferEvIn.tryLock())
  3143. {
  3144. if (fAtomBufferEvIn.isDataAvailableForReading())
  3145. {
  3146. const LV2_Atom* atom;
  3147. uint32_t j, portIndex;
  3148. for (; fAtomBufferEvIn.get(atom, portIndex);)
  3149. {
  3150. j = (portIndex < fEventsIn.count) ? portIndex : fEventsIn.ctrlIndex;
  3151. if (! lv2_atom_buffer_write(&evInAtomIters[j], 0, 0, atom->type, atom->size, LV2_ATOM_BODY_CONST(atom)))
  3152. {
  3153. carla_stderr2("Event input buffer full, at least 1 message lost");
  3154. continue;
  3155. }
  3156. inspectAtomForParameterChange(atom);
  3157. }
  3158. }
  3159. fAtomBufferEvIn.unlock();
  3160. }
  3161. // ----------------------------------------------------------------------------------------------------
  3162. // MIDI Input (External)
  3163. if (pData->extNotes.mutex.tryLock())
  3164. {
  3165. if ((fEventsIn.ctrl->type & CARLA_EVENT_TYPE_MIDI) == 0)
  3166. {
  3167. // does not handle MIDI
  3168. pData->extNotes.data.clear();
  3169. }
  3170. else
  3171. {
  3172. const uint32_t j = fEventsIn.ctrlIndex;
  3173. for (RtLinkedList<ExternalMidiNote>::Itenerator it = pData->extNotes.data.begin2(); it.valid(); it.next())
  3174. {
  3175. const ExternalMidiNote& note(it.getValue(kExternalMidiNoteFallback));
  3176. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  3177. uint8_t midiEvent[3];
  3178. midiEvent[0] = uint8_t((note.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT));
  3179. midiEvent[1] = note.note;
  3180. midiEvent[2] = note.velo;
  3181. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  3182. lv2_atom_buffer_write(&evInAtomIters[j], 0, 0, kUridMidiEvent, 3, midiEvent);
  3183. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  3184. lv2_event_write(&evInEventIters[j], 0, 0, kUridMidiEvent, 3, midiEvent);
  3185. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  3186. lv2midi_put_event(&evInMidiStates[j], 0.0, 3, midiEvent);
  3187. }
  3188. pData->extNotes.data.clear();
  3189. }
  3190. pData->extNotes.mutex.unlock();
  3191. } // End of MIDI Input (External)
  3192. // ----------------------------------------------------------------------------------------------------
  3193. // Event Input (System)
  3194. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  3195. bool allNotesOffSent = false;
  3196. #endif
  3197. bool isSampleAccurate = (pData->options & PLUGIN_OPTION_FIXED_BUFFERS) == 0;
  3198. uint32_t startTime = 0;
  3199. uint32_t timeOffset = 0;
  3200. uint32_t nextBankId;
  3201. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0)
  3202. nextBankId = pData->midiprog.data[pData->midiprog.current].bank;
  3203. else
  3204. nextBankId = 0;
  3205. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  3206. if (cvIn != nullptr && pData->event.cvSourcePorts != nullptr)
  3207. pData->event.cvSourcePorts->initPortBuffers(cvIn + pData->cvIn.count, frames, isSampleAccurate, pData->event.portIn);
  3208. #endif
  3209. const uint32_t numEvents = (fEventsIn.ctrl->port != nullptr) ? fEventsIn.ctrl->port->getEventCount() : 0;
  3210. for (uint32_t i=0; i < numEvents; ++i)
  3211. {
  3212. EngineEvent& event(fEventsIn.ctrl->port->getEvent(i));
  3213. uint32_t eventTime = event.time;
  3214. CARLA_SAFE_ASSERT_UINT2_CONTINUE(eventTime < frames, eventTime, frames);
  3215. if (eventTime < timeOffset)
  3216. {
  3217. carla_stderr2("Timing error, eventTime:%u < timeOffset:%u for '%s'",
  3218. eventTime, timeOffset, pData->name);
  3219. eventTime = timeOffset;
  3220. }
  3221. if (isSampleAccurate && eventTime > timeOffset)
  3222. {
  3223. if (processSingle(audioIn, audioOut, cvIn, cvOut, eventTime - timeOffset, timeOffset))
  3224. {
  3225. startTime = 0;
  3226. timeOffset = eventTime;
  3227. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0)
  3228. nextBankId = pData->midiprog.data[pData->midiprog.current].bank;
  3229. else
  3230. nextBankId = 0;
  3231. for (uint32_t j=0; j < fEventsIn.count; ++j)
  3232. {
  3233. if (fEventsIn.data[j].type & CARLA_EVENT_DATA_ATOM)
  3234. {
  3235. lv2_atom_buffer_reset(fEventsIn.data[j].atom, true);
  3236. lv2_atom_buffer_begin(&evInAtomIters[j], fEventsIn.data[j].atom);
  3237. }
  3238. else if (fEventsIn.data[j].type & CARLA_EVENT_DATA_EVENT)
  3239. {
  3240. lv2_event_buffer_reset(fEventsIn.data[j].event, LV2_EVENT_AUDIO_STAMP, fEventsIn.data[j].event->data);
  3241. lv2_event_begin(&evInEventIters[j], fEventsIn.data[j].event);
  3242. }
  3243. else if (fEventsIn.data[j].type & CARLA_EVENT_DATA_MIDI_LL)
  3244. {
  3245. fEventsIn.data[j].midi.event_count = 0;
  3246. fEventsIn.data[j].midi.size = 0;
  3247. evInMidiStates[j].position = eventTime;
  3248. }
  3249. }
  3250. for (uint32_t j=0; j < fEventsOut.count; ++j)
  3251. {
  3252. if (fEventsOut.data[j].type & CARLA_EVENT_DATA_ATOM)
  3253. {
  3254. lv2_atom_buffer_reset(fEventsOut.data[j].atom, false);
  3255. }
  3256. else if (fEventsOut.data[j].type & CARLA_EVENT_DATA_EVENT)
  3257. {
  3258. lv2_event_buffer_reset(fEventsOut.data[j].event, LV2_EVENT_AUDIO_STAMP, fEventsOut.data[j].event->data);
  3259. }
  3260. else if (fEventsOut.data[j].type & CARLA_EVENT_DATA_MIDI_LL)
  3261. {
  3262. // not needed
  3263. }
  3264. }
  3265. }
  3266. else
  3267. {
  3268. startTime += timeOffset;
  3269. }
  3270. }
  3271. switch (event.type)
  3272. {
  3273. case kEngineEventTypeNull:
  3274. break;
  3275. case kEngineEventTypeControl: {
  3276. EngineControlEvent& ctrlEvent(event.ctrl);
  3277. switch (ctrlEvent.type)
  3278. {
  3279. case kEngineControlEventTypeNull:
  3280. break;
  3281. case kEngineControlEventTypeParameter: {
  3282. float value;
  3283. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  3284. // non-midi
  3285. if (event.channel == kEngineEventNonMidiChannel)
  3286. {
  3287. const uint32_t k = ctrlEvent.param;
  3288. CARLA_SAFE_ASSERT_CONTINUE(k < pData->param.count);
  3289. ctrlEvent.handled = true;
  3290. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  3291. setParameterValueRT(k, value, true);
  3292. continue;
  3293. }
  3294. // Control backend stuff
  3295. if (event.channel == pData->ctrlChannel)
  3296. {
  3297. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  3298. {
  3299. ctrlEvent.handled = true;
  3300. value = ctrlEvent.normalizedValue;
  3301. setDryWetRT(value, true);
  3302. }
  3303. else if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  3304. {
  3305. ctrlEvent.handled = true;
  3306. value = ctrlEvent.normalizedValue*127.0f/100.0f;
  3307. setVolumeRT(value, true);
  3308. }
  3309. else if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  3310. {
  3311. float left, right;
  3312. value = ctrlEvent.normalizedValue/0.5f - 1.0f;
  3313. if (value < 0.0f)
  3314. {
  3315. left = -1.0f;
  3316. right = (value*2.0f)+1.0f;
  3317. }
  3318. else if (value > 0.0f)
  3319. {
  3320. left = (value*2.0f)-1.0f;
  3321. right = 1.0f;
  3322. }
  3323. else
  3324. {
  3325. left = -1.0f;
  3326. right = 1.0f;
  3327. }
  3328. ctrlEvent.handled = true;
  3329. setBalanceLeftRT(left, true);
  3330. setBalanceRightRT(right, true);
  3331. }
  3332. }
  3333. #endif
  3334. // Control plugin parameters
  3335. uint32_t k;
  3336. for (k=0; k < pData->param.count; ++k)
  3337. {
  3338. if (pData->param.data[k].midiChannel != event.channel)
  3339. continue;
  3340. if (pData->param.data[k].mappedControlIndex != ctrlEvent.param)
  3341. continue;
  3342. if (pData->param.data[k].type != PARAMETER_INPUT)
  3343. continue;
  3344. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  3345. continue;
  3346. ctrlEvent.handled = true;
  3347. if (pData->param.data[k].mappedFlags & PARAMETER_MAPPING_MIDI_DELTA)
  3348. value = pData->param.getFinalValueWithMidiDelta(k, fParamBuffers[k], ctrlEvent.midiValue);
  3349. else
  3350. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  3351. setParameterValueRT(k, value, true);
  3352. }
  3353. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param < MAX_MIDI_VALUE)
  3354. {
  3355. uint8_t midiData[3];
  3356. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  3357. midiData[1] = uint8_t(ctrlEvent.param);
  3358. midiData[2] = uint8_t(ctrlEvent.normalizedValue*127.0f);
  3359. const uint32_t mtime(isSampleAccurate ? startTime : eventTime);
  3360. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  3361. lv2_atom_buffer_write(&evInAtomIters[fEventsIn.ctrlIndex], mtime, 0, kUridMidiEvent, 3, midiData);
  3362. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  3363. lv2_event_write(&evInEventIters[fEventsIn.ctrlIndex], mtime, 0, kUridMidiEvent, 3, midiData);
  3364. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  3365. lv2midi_put_event(&evInMidiStates[fEventsIn.ctrlIndex], mtime, 3, midiData);
  3366. }
  3367. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  3368. if (! ctrlEvent.handled)
  3369. checkForMidiLearn(event);
  3370. #endif
  3371. break;
  3372. } // case kEngineControlEventTypeParameter
  3373. case kEngineControlEventTypeMidiBank:
  3374. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  3375. {
  3376. if (event.channel == pData->ctrlChannel)
  3377. nextBankId = ctrlEvent.param;
  3378. }
  3379. else if (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES)
  3380. {
  3381. uint8_t midiData[3];
  3382. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  3383. midiData[1] = MIDI_CONTROL_BANK_SELECT;
  3384. midiData[2] = uint8_t(ctrlEvent.param);
  3385. const uint32_t mtime(isSampleAccurate ? startTime : eventTime);
  3386. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  3387. lv2_atom_buffer_write(&evInAtomIters[fEventsIn.ctrlIndex], mtime, 0, kUridMidiEvent, 3, midiData);
  3388. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  3389. lv2_event_write(&evInEventIters[fEventsIn.ctrlIndex], mtime, 0, kUridMidiEvent, 3, midiData);
  3390. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  3391. lv2midi_put_event(&evInMidiStates[fEventsIn.ctrlIndex], mtime, 3, midiData);
  3392. }
  3393. break;
  3394. case kEngineControlEventTypeMidiProgram:
  3395. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  3396. {
  3397. if (event.channel == pData->ctrlChannel)
  3398. {
  3399. const uint32_t nextProgramId(ctrlEvent.param);
  3400. for (uint32_t k=0; k < pData->midiprog.count; ++k)
  3401. {
  3402. if (pData->midiprog.data[k].bank == nextBankId && pData->midiprog.data[k].program == nextProgramId)
  3403. {
  3404. setMidiProgramRT(k, true);
  3405. break;
  3406. }
  3407. }
  3408. }
  3409. }
  3410. else if (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES)
  3411. {
  3412. uint8_t midiData[2];
  3413. midiData[0] = uint8_t(MIDI_STATUS_PROGRAM_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  3414. midiData[1] = uint8_t(ctrlEvent.param);
  3415. const uint32_t mtime(isSampleAccurate ? startTime : eventTime);
  3416. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  3417. lv2_atom_buffer_write(&evInAtomIters[fEventsIn.ctrlIndex], mtime, 0, kUridMidiEvent, 2, midiData);
  3418. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  3419. lv2_event_write(&evInEventIters[fEventsIn.ctrlIndex], mtime, 0, kUridMidiEvent, 2, midiData);
  3420. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  3421. lv2midi_put_event(&evInMidiStates[fEventsIn.ctrlIndex], mtime, 2, midiData);
  3422. }
  3423. break;
  3424. case kEngineControlEventTypeAllSoundOff:
  3425. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  3426. {
  3427. const uint32_t mtime(isSampleAccurate ? startTime : eventTime);
  3428. uint8_t midiData[3];
  3429. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  3430. midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  3431. midiData[2] = 0;
  3432. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  3433. lv2_atom_buffer_write(&evInAtomIters[fEventsIn.ctrlIndex], mtime, 0, kUridMidiEvent, 3, midiData);
  3434. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  3435. lv2_event_write(&evInEventIters[fEventsIn.ctrlIndex], mtime, 0, kUridMidiEvent, 3, midiData);
  3436. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  3437. lv2midi_put_event(&evInMidiStates[fEventsIn.ctrlIndex], mtime, 3, midiData);
  3438. }
  3439. break;
  3440. case kEngineControlEventTypeAllNotesOff:
  3441. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  3442. {
  3443. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  3444. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  3445. {
  3446. allNotesOffSent = true;
  3447. postponeRtAllNotesOff();
  3448. }
  3449. #endif
  3450. const uint32_t mtime(isSampleAccurate ? startTime : eventTime);
  3451. uint8_t midiData[3];
  3452. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  3453. midiData[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  3454. midiData[2] = 0;
  3455. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  3456. lv2_atom_buffer_write(&evInAtomIters[fEventsIn.ctrlIndex], mtime, 0, kUridMidiEvent, 3, midiData);
  3457. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  3458. lv2_event_write(&evInEventIters[fEventsIn.ctrlIndex], mtime, 0, kUridMidiEvent, 3, midiData);
  3459. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  3460. lv2midi_put_event(&evInMidiStates[fEventsIn.ctrlIndex], mtime, 3, midiData);
  3461. }
  3462. break;
  3463. } // switch (ctrlEvent.type)
  3464. break;
  3465. } // case kEngineEventTypeControl
  3466. case kEngineEventTypeMidi: {
  3467. const EngineMidiEvent& midiEvent(event.midi);
  3468. const uint8_t* const midiData(midiEvent.size > EngineMidiEvent::kDataSize ? midiEvent.dataExt : midiEvent.data);
  3469. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiData));
  3470. if ((status == MIDI_STATUS_NOTE_OFF || status == MIDI_STATUS_NOTE_ON) && (pData->options & PLUGIN_OPTION_SKIP_SENDING_NOTES))
  3471. continue;
  3472. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  3473. continue;
  3474. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  3475. continue;
  3476. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  3477. continue;
  3478. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  3479. continue;
  3480. // Fix bad note-off (per LV2 spec)
  3481. if (status == MIDI_STATUS_NOTE_ON && midiData[2] == 0)
  3482. status = MIDI_STATUS_NOTE_OFF;
  3483. const uint32_t j = fEventsIn.ctrlIndex;
  3484. const uint32_t mtime = isSampleAccurate ? startTime : eventTime;
  3485. // put back channel in data
  3486. uint8_t midiData2[midiEvent.size];
  3487. midiData2[0] = uint8_t(status | (event.channel & MIDI_CHANNEL_BIT));
  3488. std::memcpy(midiData2+1, midiData+1, static_cast<std::size_t>(midiEvent.size-1));
  3489. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  3490. lv2_atom_buffer_write(&evInAtomIters[j], mtime, 0, kUridMidiEvent, midiEvent.size, midiData2);
  3491. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  3492. lv2_event_write(&evInEventIters[j], mtime, 0, kUridMidiEvent, midiEvent.size, midiData2);
  3493. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  3494. lv2midi_put_event(&evInMidiStates[j], mtime, midiEvent.size, midiData2);
  3495. if (status == MIDI_STATUS_NOTE_ON)
  3496. {
  3497. pData->postponeNoteOnRtEvent(true, event.channel, midiData[1], midiData[2]);
  3498. }
  3499. else if (status == MIDI_STATUS_NOTE_OFF)
  3500. {
  3501. pData->postponeNoteOffRtEvent(true, event.channel, midiData[1]);
  3502. }
  3503. } break;
  3504. } // switch (event.type)
  3505. }
  3506. pData->postRtEvents.trySplice();
  3507. if (frames > timeOffset)
  3508. processSingle(audioIn, audioOut, cvIn, cvOut, frames - timeOffset, timeOffset);
  3509. } // End of Event Input and Processing
  3510. // --------------------------------------------------------------------------------------------------------
  3511. // Plugin processing (no events)
  3512. else
  3513. {
  3514. processSingle(audioIn, audioOut, cvIn, cvOut, frames, 0);
  3515. } // End of Plugin processing (no events)
  3516. // --------------------------------------------------------------------------------------------------------
  3517. // Final work
  3518. if (fEventsIn.ctrl != nullptr && fExt.worker != nullptr && fAtomBufferWorkerResp.tryLock())
  3519. {
  3520. if (fAtomBufferWorkerResp.isDataAvailableForReading())
  3521. {
  3522. const LV2_Atom* atom;
  3523. uint32_t portIndex;
  3524. for (; fAtomBufferWorkerResp.get(atom, portIndex);)
  3525. {
  3526. CARLA_SAFE_ASSERT_CONTINUE(atom->type == kUridCarlaAtomWorkerResp);
  3527. fExt.worker->work_response(fHandle, atom->size, LV2_ATOM_BODY_CONST(atom));
  3528. }
  3529. }
  3530. fAtomBufferWorkerResp.unlock();
  3531. }
  3532. if (fExt.worker != nullptr && fExt.worker->end_run != nullptr)
  3533. {
  3534. fExt.worker->end_run(fHandle);
  3535. if (fHandle2 != nullptr)
  3536. fExt.worker->end_run(fHandle2);
  3537. }
  3538. // --------------------------------------------------------------------------------------------------------
  3539. // Events/MIDI Output
  3540. for (uint32_t i=0; i < fEventsOut.count; ++i)
  3541. {
  3542. uint32_t lastFrame = 0;
  3543. Lv2EventData& evData(fEventsOut.data[i]);
  3544. if (evData.type & CARLA_EVENT_DATA_ATOM)
  3545. {
  3546. const LV2_Atom_Event* ev;
  3547. LV2_Atom_Buffer_Iterator iter;
  3548. uint8_t* data;
  3549. lv2_atom_buffer_begin(&iter, evData.atom);
  3550. for (;;)
  3551. {
  3552. data = nullptr;
  3553. ev = lv2_atom_buffer_get(&iter, &data);
  3554. if (ev == nullptr || ev->body.size == 0 || data == nullptr)
  3555. break;
  3556. if (ev->body.type == kUridMidiEvent)
  3557. {
  3558. if (evData.port != nullptr)
  3559. {
  3560. CARLA_SAFE_ASSERT_CONTINUE(ev->time.frames >= 0);
  3561. CARLA_SAFE_ASSERT_CONTINUE(ev->body.size < 0xFF);
  3562. uint32_t currentFrame = static_cast<uint32_t>(ev->time.frames);
  3563. if (currentFrame < lastFrame)
  3564. currentFrame = lastFrame;
  3565. else if (currentFrame >= frames)
  3566. currentFrame = frames - 1;
  3567. evData.port->writeMidiEvent(currentFrame, static_cast<uint8_t>(ev->body.size), data);
  3568. }
  3569. }
  3570. else if (fAtomBufferUiOutTmpData != nullptr)
  3571. {
  3572. fAtomBufferUiOut.put(&ev->body, evData.rindex);
  3573. }
  3574. lv2_atom_buffer_increment(&iter);
  3575. }
  3576. }
  3577. else if ((evData.type & CARLA_EVENT_DATA_EVENT) != 0 && evData.port != nullptr)
  3578. {
  3579. const LV2_Event* ev;
  3580. LV2_Event_Iterator iter;
  3581. uint8_t* data;
  3582. lv2_event_begin(&iter, evData.event);
  3583. for (;;)
  3584. {
  3585. data = nullptr;
  3586. ev = lv2_event_get(&iter, &data);
  3587. if (ev == nullptr || data == nullptr)
  3588. break;
  3589. uint32_t currentFrame = ev->frames;
  3590. if (currentFrame < lastFrame)
  3591. currentFrame = lastFrame;
  3592. else if (currentFrame >= frames)
  3593. currentFrame = frames - 1;
  3594. if (ev->type == kUridMidiEvent)
  3595. {
  3596. CARLA_SAFE_ASSERT_CONTINUE(ev->size < 0xFF);
  3597. evData.port->writeMidiEvent(currentFrame, static_cast<uint8_t>(ev->size), data);
  3598. }
  3599. lv2_event_increment(&iter);
  3600. }
  3601. }
  3602. else if ((evData.type & CARLA_EVENT_DATA_MIDI_LL) != 0 && evData.port != nullptr)
  3603. {
  3604. LV2_MIDIState state = { &evData.midi, frames, 0 };
  3605. uint32_t eventSize;
  3606. double eventTime;
  3607. uchar* eventData;
  3608. for (;;)
  3609. {
  3610. eventSize = 0;
  3611. eventTime = 0.0;
  3612. eventData = nullptr;
  3613. lv2midi_get_event(&state, &eventTime, &eventSize, &eventData);
  3614. if (eventData == nullptr || eventSize == 0)
  3615. break;
  3616. CARLA_SAFE_ASSERT_CONTINUE(eventSize < 0xFF);
  3617. CARLA_SAFE_ASSERT_CONTINUE(eventTime >= 0.0);
  3618. evData.port->writeMidiEvent(static_cast<uint32_t>(eventTime), static_cast<uint8_t>(eventSize), eventData);
  3619. lv2midi_step(&state);
  3620. }
  3621. }
  3622. }
  3623. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  3624. // --------------------------------------------------------------------------------------------------------
  3625. // Control Output
  3626. if (pData->event.portOut != nullptr)
  3627. {
  3628. uint8_t channel;
  3629. uint16_t param;
  3630. float value;
  3631. for (uint32_t k=0; k < pData->param.count; ++k)
  3632. {
  3633. if (pData->param.data[k].type != PARAMETER_OUTPUT)
  3634. continue;
  3635. if (fStrictBounds >= 0 && (pData->param.data[k].hints & PARAMETER_IS_STRICT_BOUNDS) != 0)
  3636. // plugin is responsible to ensure correct bounds
  3637. pData->param.ranges[k].fixValue(fParamBuffers[k]);
  3638. if (pData->param.data[k].mappedControlIndex > 0)
  3639. {
  3640. channel = pData->param.data[k].midiChannel;
  3641. param = static_cast<uint16_t>(pData->param.data[k].mappedControlIndex);
  3642. value = pData->param.ranges[k].getNormalizedValue(fParamBuffers[k]);
  3643. pData->event.portOut->writeControlEvent(0, channel, kEngineControlEventTypeParameter,
  3644. param, -1, value);
  3645. }
  3646. }
  3647. } // End of Control Output
  3648. #endif
  3649. fFirstActive = false;
  3650. // --------------------------------------------------------------------------------------------------------
  3651. }
  3652. bool processSingle(const float* const* const audioIn, float** const audioOut,
  3653. const float* const* const cvIn, float** const cvOut,
  3654. const uint32_t frames, const uint32_t timeOffset)
  3655. {
  3656. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  3657. if (pData->audioIn.count > 0)
  3658. {
  3659. CARLA_SAFE_ASSERT_RETURN(audioIn != nullptr, false);
  3660. CARLA_SAFE_ASSERT_RETURN(fAudioInBuffers != nullptr, false);
  3661. }
  3662. if (pData->audioOut.count > 0)
  3663. {
  3664. CARLA_SAFE_ASSERT_RETURN(audioOut != nullptr, false);
  3665. CARLA_SAFE_ASSERT_RETURN(fAudioOutBuffers != nullptr, false);
  3666. }
  3667. if (pData->cvIn.count > 0)
  3668. {
  3669. CARLA_SAFE_ASSERT_RETURN(cvIn != nullptr, false);
  3670. }
  3671. if (pData->cvOut.count > 0)
  3672. {
  3673. CARLA_SAFE_ASSERT_RETURN(cvOut != nullptr, false);
  3674. }
  3675. // --------------------------------------------------------------------------------------------------------
  3676. // Try lock, silence otherwise
  3677. #ifndef STOAT_TEST_BUILD
  3678. if (pData->engine->isOffline())
  3679. {
  3680. pData->singleMutex.lock();
  3681. }
  3682. else
  3683. #endif
  3684. if (! pData->singleMutex.tryLock())
  3685. {
  3686. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  3687. {
  3688. for (uint32_t k=0; k < frames; ++k)
  3689. audioOut[i][k+timeOffset] = 0.0f;
  3690. }
  3691. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  3692. {
  3693. for (uint32_t k=0; k < frames; ++k)
  3694. cvOut[i][k+timeOffset] = 0.0f;
  3695. }
  3696. return false;
  3697. }
  3698. // --------------------------------------------------------------------------------------------------------
  3699. // Set audio buffers
  3700. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  3701. carla_copyFloats(fAudioInBuffers[i], audioIn[i]+timeOffset, frames);
  3702. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  3703. carla_zeroFloats(fAudioOutBuffers[i], frames);
  3704. // --------------------------------------------------------------------------------------------------------
  3705. // Set CV buffers
  3706. for (uint32_t i=0; i < pData->cvIn.count; ++i)
  3707. carla_copyFloats(fCvInBuffers[i], cvIn[i]+timeOffset, frames);
  3708. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  3709. carla_zeroFloats(fCvOutBuffers[i], frames);
  3710. // --------------------------------------------------------------------------------------------------------
  3711. // Run plugin
  3712. fDescriptor->run(fHandle, frames);
  3713. if (fHandle2 != nullptr)
  3714. fDescriptor->run(fHandle2, frames);
  3715. // --------------------------------------------------------------------------------------------------------
  3716. // Handle trigger parameters
  3717. for (uint32_t k=0; k < pData->param.count; ++k)
  3718. {
  3719. if (pData->param.data[k].type != PARAMETER_INPUT)
  3720. continue;
  3721. if (pData->param.data[k].hints & PARAMETER_IS_TRIGGER)
  3722. {
  3723. if (carla_isNotEqual(fParamBuffers[k], pData->param.ranges[k].def))
  3724. {
  3725. fParamBuffers[k] = pData->param.ranges[k].def;
  3726. pData->postponeParameterChangeRtEvent(true, static_cast<int32_t>(k), fParamBuffers[k]);
  3727. }
  3728. }
  3729. }
  3730. pData->postRtEvents.trySplice();
  3731. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  3732. // --------------------------------------------------------------------------------------------------------
  3733. // Post-processing (dry/wet, volume and balance)
  3734. {
  3735. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  3736. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  3737. const bool isMono = (pData->audioIn.count == 1);
  3738. bool isPair;
  3739. float bufValue, oldBufLeft[doBalance ? frames : 1];
  3740. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  3741. {
  3742. // Dry/Wet
  3743. if (doDryWet)
  3744. {
  3745. const uint32_t c = isMono ? 0 : i;
  3746. for (uint32_t k=0; k < frames; ++k)
  3747. {
  3748. # ifndef BUILD_BRIDGE
  3749. if (k < pData->latency.frames && pData->latency.buffers != nullptr)
  3750. bufValue = pData->latency.buffers[c][k];
  3751. else if (pData->latency.frames < frames)
  3752. bufValue = fAudioInBuffers[c][k-pData->latency.frames];
  3753. else
  3754. # endif
  3755. bufValue = fAudioInBuffers[c][k];
  3756. fAudioOutBuffers[i][k] = (fAudioOutBuffers[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  3757. }
  3758. }
  3759. // Balance
  3760. if (doBalance)
  3761. {
  3762. isPair = (i % 2 == 0);
  3763. if (isPair)
  3764. {
  3765. CARLA_ASSERT(i+1 < pData->audioOut.count);
  3766. carla_copyFloats(oldBufLeft, fAudioOutBuffers[i], frames);
  3767. }
  3768. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  3769. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  3770. for (uint32_t k=0; k < frames; ++k)
  3771. {
  3772. if (isPair)
  3773. {
  3774. // left
  3775. fAudioOutBuffers[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  3776. fAudioOutBuffers[i][k] += fAudioOutBuffers[i+1][k] * (1.0f - balRangeR);
  3777. }
  3778. else
  3779. {
  3780. // right
  3781. fAudioOutBuffers[i][k] = fAudioOutBuffers[i][k] * balRangeR;
  3782. fAudioOutBuffers[i][k] += oldBufLeft[k] * balRangeL;
  3783. }
  3784. }
  3785. }
  3786. // Volume (and buffer copy)
  3787. {
  3788. for (uint32_t k=0; k < frames; ++k)
  3789. audioOut[i][k+timeOffset] = fAudioOutBuffers[i][k] * pData->postProc.volume;
  3790. }
  3791. }
  3792. } // End of Post-processing
  3793. # ifndef BUILD_BRIDGE
  3794. // --------------------------------------------------------------------------------------------------------
  3795. // Save latency values for next callback
  3796. if (pData->latency.frames != 0 && pData->latency.buffers != nullptr)
  3797. {
  3798. CARLA_SAFE_ASSERT(timeOffset == 0);
  3799. const uint32_t latframes = pData->latency.frames;
  3800. if (latframes <= frames)
  3801. {
  3802. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  3803. carla_copyFloats(pData->latency.buffers[i], audioIn[i]+(frames-latframes), latframes);
  3804. }
  3805. else
  3806. {
  3807. const uint32_t diff = latframes - frames;
  3808. for (uint32_t i=0, k; i<pData->audioIn.count; ++i)
  3809. {
  3810. // push back buffer by 'frames'
  3811. for (k=0; k < diff; ++k)
  3812. pData->latency.buffers[i][k] = pData->latency.buffers[i][k+frames];
  3813. // put current input at the end
  3814. for (uint32_t j=0; k < latframes; ++j, ++k)
  3815. pData->latency.buffers[i][k] = audioIn[i][j];
  3816. }
  3817. }
  3818. }
  3819. # endif
  3820. #else // BUILD_BRIDGE_ALTERNATIVE_ARCH
  3821. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  3822. {
  3823. for (uint32_t k=0; k < frames; ++k)
  3824. audioOut[i][k+timeOffset] = fAudioOutBuffers[i][k];
  3825. }
  3826. #endif
  3827. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  3828. {
  3829. for (uint32_t k=0; k < frames; ++k)
  3830. cvOut[i][k+timeOffset] = fCvOutBuffers[i][k];
  3831. }
  3832. // --------------------------------------------------------------------------------------------------------
  3833. pData->singleMutex.unlock();
  3834. return true;
  3835. }
  3836. void bufferSizeChanged(const uint32_t newBufferSize) override
  3837. {
  3838. CARLA_ASSERT_INT(newBufferSize > 0, newBufferSize);
  3839. carla_debug("CarlaPluginLV2::bufferSizeChanged(%i) - start", newBufferSize);
  3840. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  3841. {
  3842. if (fAudioInBuffers[i] != nullptr)
  3843. delete[] fAudioInBuffers[i];
  3844. fAudioInBuffers[i] = new float[newBufferSize];
  3845. }
  3846. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  3847. {
  3848. if (fAudioOutBuffers[i] != nullptr)
  3849. delete[] fAudioOutBuffers[i];
  3850. fAudioOutBuffers[i] = new float[newBufferSize];
  3851. }
  3852. if (fHandle2 == nullptr)
  3853. {
  3854. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  3855. {
  3856. CARLA_ASSERT(fAudioInBuffers[i] != nullptr);
  3857. fDescriptor->connect_port(fHandle, pData->audioIn.ports[i].rindex, fAudioInBuffers[i]);
  3858. }
  3859. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  3860. {
  3861. CARLA_ASSERT(fAudioOutBuffers[i] != nullptr);
  3862. fDescriptor->connect_port(fHandle, pData->audioOut.ports[i].rindex, fAudioOutBuffers[i]);
  3863. }
  3864. }
  3865. else
  3866. {
  3867. if (pData->audioIn.count > 0)
  3868. {
  3869. CARLA_ASSERT(pData->audioIn.count == 2);
  3870. CARLA_ASSERT(fAudioInBuffers[0] != nullptr);
  3871. CARLA_ASSERT(fAudioInBuffers[1] != nullptr);
  3872. fDescriptor->connect_port(fHandle, pData->audioIn.ports[0].rindex, fAudioInBuffers[0]);
  3873. fDescriptor->connect_port(fHandle2, pData->audioIn.ports[1].rindex, fAudioInBuffers[1]);
  3874. }
  3875. if (pData->audioOut.count > 0)
  3876. {
  3877. CARLA_ASSERT(pData->audioOut.count == 2);
  3878. CARLA_ASSERT(fAudioOutBuffers[0] != nullptr);
  3879. CARLA_ASSERT(fAudioOutBuffers[1] != nullptr);
  3880. fDescriptor->connect_port(fHandle, pData->audioOut.ports[0].rindex, fAudioOutBuffers[0]);
  3881. fDescriptor->connect_port(fHandle2, pData->audioOut.ports[1].rindex, fAudioOutBuffers[1]);
  3882. }
  3883. }
  3884. for (uint32_t i=0; i < pData->cvIn.count; ++i)
  3885. {
  3886. if (fCvInBuffers[i] != nullptr)
  3887. delete[] fCvInBuffers[i];
  3888. fCvInBuffers[i] = new float[newBufferSize];
  3889. fDescriptor->connect_port(fHandle, pData->cvIn.ports[i].rindex, fCvInBuffers[i]);
  3890. if (fHandle2 != nullptr)
  3891. fDescriptor->connect_port(fHandle2, pData->cvIn.ports[i].rindex, fCvInBuffers[i]);
  3892. }
  3893. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  3894. {
  3895. if (fCvOutBuffers[i] != nullptr)
  3896. delete[] fCvOutBuffers[i];
  3897. fCvOutBuffers[i] = new float[newBufferSize];
  3898. fDescriptor->connect_port(fHandle, pData->cvOut.ports[i].rindex, fCvOutBuffers[i]);
  3899. if (fHandle2 != nullptr)
  3900. fDescriptor->connect_port(fHandle2, pData->cvOut.ports[i].rindex, fCvOutBuffers[i]);
  3901. }
  3902. const int newBufferSizeInt(static_cast<int>(newBufferSize));
  3903. if (fLv2Options.maxBufferSize != newBufferSizeInt || (fLv2Options.minBufferSize != 1 && fLv2Options.minBufferSize != newBufferSizeInt))
  3904. {
  3905. fLv2Options.maxBufferSize = fLv2Options.nominalBufferSize = newBufferSizeInt;
  3906. if (fLv2Options.minBufferSize != 1)
  3907. fLv2Options.minBufferSize = newBufferSizeInt;
  3908. if (fExt.options != nullptr && fExt.options->set != nullptr)
  3909. {
  3910. LV2_Options_Option options[4];
  3911. carla_zeroStructs(options, 4);
  3912. carla_copyStruct(options[0], fLv2Options.opts[CarlaPluginLV2Options::MaxBlockLenth]);
  3913. carla_copyStruct(options[1], fLv2Options.opts[CarlaPluginLV2Options::NominalBlockLenth]);
  3914. if (fLv2Options.minBufferSize != 1)
  3915. carla_copyStruct(options[2], fLv2Options.opts[CarlaPluginLV2Options::MinBlockLenth]);
  3916. fExt.options->set(fHandle, options);
  3917. }
  3918. }
  3919. carla_debug("CarlaPluginLV2::bufferSizeChanged(%i) - end", newBufferSize);
  3920. }
  3921. void sampleRateChanged(const double newSampleRate) override
  3922. {
  3923. CARLA_ASSERT_INT(newSampleRate > 0.0, newSampleRate);
  3924. carla_debug("CarlaPluginLV2::sampleRateChanged(%g) - start", newSampleRate);
  3925. const float sampleRatef = static_cast<float>(newSampleRate);
  3926. if (carla_isNotEqual(fLv2Options.sampleRate, sampleRatef))
  3927. {
  3928. fLv2Options.sampleRate = sampleRatef;
  3929. if (fExt.options != nullptr && fExt.options->set != nullptr)
  3930. {
  3931. LV2_Options_Option options[2];
  3932. carla_copyStruct(options[0], fLv2Options.opts[CarlaPluginLV2Options::SampleRate]);
  3933. carla_zeroStruct(options[1]);
  3934. fExt.options->set(fHandle, options);
  3935. }
  3936. }
  3937. for (uint32_t k=0; k < pData->param.count; ++k)
  3938. {
  3939. if (pData->param.data[k].type != PARAMETER_INPUT)
  3940. continue;
  3941. if (pData->param.special[k] != PARAMETER_SPECIAL_SAMPLE_RATE)
  3942. continue;
  3943. fParamBuffers[k] = sampleRatef;
  3944. pData->postponeParameterChangeRtEvent(true, static_cast<int32_t>(k), fParamBuffers[k]);
  3945. break;
  3946. }
  3947. carla_debug("CarlaPluginLV2::sampleRateChanged(%g) - end", newSampleRate);
  3948. }
  3949. void offlineModeChanged(const bool isOffline) override
  3950. {
  3951. for (uint32_t k=0; k < pData->param.count; ++k)
  3952. {
  3953. if (pData->param.data[k].type == PARAMETER_INPUT && pData->param.special[k] == PARAMETER_SPECIAL_FREEWHEEL)
  3954. {
  3955. fParamBuffers[k] = isOffline ? pData->param.ranges[k].max : pData->param.ranges[k].min;
  3956. pData->postponeParameterChangeRtEvent(true, static_cast<int32_t>(k), fParamBuffers[k]);
  3957. break;
  3958. }
  3959. }
  3960. }
  3961. // -------------------------------------------------------------------
  3962. // Plugin buffers
  3963. void initBuffers() const noexcept override
  3964. {
  3965. fEventsIn.initBuffers();
  3966. fEventsOut.initBuffers();
  3967. CarlaPlugin::initBuffers();
  3968. }
  3969. void clearBuffers() noexcept override
  3970. {
  3971. carla_debug("CarlaPluginLV2::clearBuffers() - start");
  3972. if (fAudioInBuffers != nullptr)
  3973. {
  3974. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  3975. {
  3976. if (fAudioInBuffers[i] != nullptr)
  3977. {
  3978. delete[] fAudioInBuffers[i];
  3979. fAudioInBuffers[i] = nullptr;
  3980. }
  3981. }
  3982. delete[] fAudioInBuffers;
  3983. fAudioInBuffers = nullptr;
  3984. }
  3985. if (fAudioOutBuffers != nullptr)
  3986. {
  3987. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  3988. {
  3989. if (fAudioOutBuffers[i] != nullptr)
  3990. {
  3991. delete[] fAudioOutBuffers[i];
  3992. fAudioOutBuffers[i] = nullptr;
  3993. }
  3994. }
  3995. delete[] fAudioOutBuffers;
  3996. fAudioOutBuffers = nullptr;
  3997. }
  3998. if (fCvInBuffers != nullptr)
  3999. {
  4000. for (uint32_t i=0; i < pData->cvIn.count; ++i)
  4001. {
  4002. if (fCvInBuffers[i] != nullptr)
  4003. {
  4004. delete[] fCvInBuffers[i];
  4005. fCvInBuffers[i] = nullptr;
  4006. }
  4007. }
  4008. delete[] fCvInBuffers;
  4009. fCvInBuffers = nullptr;
  4010. }
  4011. if (fCvOutBuffers != nullptr)
  4012. {
  4013. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  4014. {
  4015. if (fCvOutBuffers[i] != nullptr)
  4016. {
  4017. delete[] fCvOutBuffers[i];
  4018. fCvOutBuffers[i] = nullptr;
  4019. }
  4020. }
  4021. delete[] fCvOutBuffers;
  4022. fCvOutBuffers = nullptr;
  4023. }
  4024. if (fParamBuffers != nullptr)
  4025. {
  4026. delete[] fParamBuffers;
  4027. fParamBuffers = nullptr;
  4028. }
  4029. fEventsIn.clear(pData->event.portIn);
  4030. fEventsOut.clear(pData->event.portOut);
  4031. CarlaPlugin::clearBuffers();
  4032. carla_debug("CarlaPluginLV2::clearBuffers() - end");
  4033. }
  4034. // -------------------------------------------------------------------
  4035. // Post-poned UI Stuff
  4036. void uiParameterChange(const uint32_t index, const float value) noexcept override
  4037. {
  4038. CARLA_SAFE_ASSERT_RETURN(fUI.type != UI::TYPE_NULL || fFilePathURI.isNotEmpty(),);
  4039. CARLA_SAFE_ASSERT_RETURN(index < pData->param.count,);
  4040. CARLA_SAFE_ASSERT_RETURN(pData->param.data[index].rindex >= 0,);
  4041. if (fUI.type == UI::TYPE_BRIDGE)
  4042. {
  4043. if (! fPipeServer.isPipeRunning())
  4044. return;
  4045. }
  4046. else
  4047. {
  4048. if (fUI.handle == nullptr)
  4049. return;
  4050. if (fUI.descriptor == nullptr || fUI.descriptor->port_event == nullptr)
  4051. return;
  4052. if (fNeedsUiClose)
  4053. return;
  4054. }
  4055. ParameterData& pdata(pData->param.data[index]);
  4056. if (pdata.hints & PARAMETER_IS_NOT_SAVED)
  4057. {
  4058. int32_t rindex = pdata.rindex;
  4059. CARLA_SAFE_ASSERT_RETURN(rindex - static_cast<int32_t>(fRdfDescriptor->PortCount) >= 0,);
  4060. rindex -= static_cast<int32_t>(fRdfDescriptor->PortCount);
  4061. CARLA_SAFE_ASSERT_RETURN(rindex < static_cast<int32_t>(fRdfDescriptor->ParameterCount),);
  4062. const char* const uri = fRdfDescriptor->Parameters[rindex].URI;
  4063. if (fUI.type == UI::TYPE_BRIDGE)
  4064. {
  4065. fPipeServer.writeLv2ParameterMessage(uri, value);
  4066. }
  4067. else if (fEventsIn.ctrl != nullptr)
  4068. {
  4069. uint8_t atomBuf[256];
  4070. LV2_Atom_Forge atomForge;
  4071. initAtomForge(atomForge);
  4072. lv2_atom_forge_set_buffer(&atomForge, atomBuf, sizeof(atomBuf));
  4073. LV2_Atom_Forge_Frame forgeFrame;
  4074. lv2_atom_forge_object(&atomForge, &forgeFrame, kUridNull, kUridPatchSet);
  4075. lv2_atom_forge_key(&atomForge, kUridCarlaParameterChange);
  4076. lv2_atom_forge_bool(&atomForge, true);
  4077. lv2_atom_forge_key(&atomForge, kUridPatchProperty);
  4078. lv2_atom_forge_urid(&atomForge, getCustomURID(uri));
  4079. lv2_atom_forge_key(&atomForge, kUridPatchValue);
  4080. switch (fRdfDescriptor->Parameters[rindex].Type)
  4081. {
  4082. case LV2_PARAMETER_TYPE_BOOL:
  4083. lv2_atom_forge_bool(&atomForge, value > 0.5f);
  4084. break;
  4085. case LV2_PARAMETER_TYPE_INT:
  4086. lv2_atom_forge_int(&atomForge, static_cast<int32_t>(value + 0.5f));
  4087. break;
  4088. case LV2_PARAMETER_TYPE_LONG:
  4089. lv2_atom_forge_long(&atomForge, static_cast<int64_t>(value + 0.5f));
  4090. break;
  4091. case LV2_PARAMETER_TYPE_FLOAT:
  4092. lv2_atom_forge_float(&atomForge, value);
  4093. break;
  4094. case LV2_PARAMETER_TYPE_DOUBLE:
  4095. lv2_atom_forge_double(&atomForge, value);
  4096. break;
  4097. default:
  4098. carla_stderr2("uiParameterChange called for invalid parameter, abort!");
  4099. return;
  4100. }
  4101. lv2_atom_forge_pop(&atomForge, &forgeFrame);
  4102. LV2_Atom* const atom((LV2_Atom*)atomBuf);
  4103. CARLA_SAFE_ASSERT(atom->size < sizeof(atomBuf));
  4104. fUI.descriptor->port_event(fUI.handle,
  4105. fEventsIn.ctrl->rindex,
  4106. lv2_atom_total_size(atom),
  4107. kUridAtomTransferEvent,
  4108. atom);
  4109. }
  4110. }
  4111. else
  4112. {
  4113. if (fUI.type == UI::TYPE_BRIDGE)
  4114. {
  4115. fPipeServer.writeControlMessage(static_cast<uint32_t>(pData->param.data[index].rindex), value);
  4116. }
  4117. else
  4118. {
  4119. fUI.descriptor->port_event(fUI.handle,
  4120. static_cast<uint32_t>(pData->param.data[index].rindex),
  4121. sizeof(float), kUridNull, &value);
  4122. }
  4123. }
  4124. }
  4125. void uiMidiProgramChange(const uint32_t index) noexcept override
  4126. {
  4127. CARLA_SAFE_ASSERT_RETURN(fUI.type != UI::TYPE_NULL || fFilePathURI.isNotEmpty(),);
  4128. CARLA_SAFE_ASSERT_RETURN(index < pData->midiprog.count,);
  4129. if (fUI.type == UI::TYPE_BRIDGE)
  4130. {
  4131. if (fPipeServer.isPipeRunning())
  4132. fPipeServer.writeMidiProgramMessage(pData->midiprog.data[index].bank, pData->midiprog.data[index].program);
  4133. }
  4134. else
  4135. {
  4136. if (fExt.uiprograms != nullptr && fExt.uiprograms->select_program != nullptr && ! fNeedsUiClose)
  4137. fExt.uiprograms->select_program(fUI.handle, pData->midiprog.data[index].bank, pData->midiprog.data[index].program);
  4138. }
  4139. }
  4140. void uiNoteOn(const uint8_t channel, const uint8_t note, const uint8_t velo) noexcept override
  4141. {
  4142. CARLA_SAFE_ASSERT_RETURN(fUI.type != UI::TYPE_NULL || fFilePathURI.isNotEmpty(),);
  4143. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  4144. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  4145. CARLA_SAFE_ASSERT_RETURN(velo > 0 && velo < MAX_MIDI_VALUE,);
  4146. #if 0
  4147. if (fUI.type == UI::TYPE_BRIDGE)
  4148. {
  4149. if (fPipeServer.isPipeRunning())
  4150. fPipeServer.writeMidiNoteMessage(false, channel, note, velo);
  4151. }
  4152. else
  4153. {
  4154. if (fUI.handle != nullptr && fUI.descriptor != nullptr && fUI.descriptor->port_event != nullptr && fEventsIn.ctrl != nullptr && ! fNeedsUiClose)
  4155. {
  4156. LV2_Atom_MidiEvent midiEv;
  4157. midiEv.atom.type = kUridMidiEvent;
  4158. midiEv.atom.size = 3;
  4159. midiEv.data[0] = uint8_t(MIDI_STATUS_NOTE_ON | (channel & MIDI_CHANNEL_BIT));
  4160. midiEv.data[1] = note;
  4161. midiEv.data[2] = velo;
  4162. fUI.descriptor->port_event(fUI.handle, fEventsIn.ctrl->rindex, lv2_atom_total_size(midiEv), kUridAtomTransferEvent, &midiEv);
  4163. }
  4164. }
  4165. #endif
  4166. }
  4167. void uiNoteOff(const uint8_t channel, const uint8_t note) noexcept override
  4168. {
  4169. CARLA_SAFE_ASSERT_RETURN(fUI.type != UI::TYPE_NULL || fFilePathURI.isNotEmpty(),);
  4170. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  4171. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  4172. #if 0
  4173. if (fUI.type == UI::TYPE_BRIDGE)
  4174. {
  4175. if (fPipeServer.isPipeRunning())
  4176. fPipeServer.writeMidiNoteMessage(false, channel, note, 0);
  4177. }
  4178. else
  4179. {
  4180. if (fUI.handle != nullptr && fUI.descriptor != nullptr && fUI.descriptor->port_event != nullptr && fEventsIn.ctrl != nullptr && ! fNeedsUiClose)
  4181. {
  4182. LV2_Atom_MidiEvent midiEv;
  4183. midiEv.atom.type = kUridMidiEvent;
  4184. midiEv.atom.size = 3;
  4185. midiEv.data[0] = uint8_t(MIDI_STATUS_NOTE_OFF | (channel & MIDI_CHANNEL_BIT));
  4186. midiEv.data[1] = note;
  4187. midiEv.data[2] = 0;
  4188. fUI.descriptor->port_event(fUI.handle, fEventsIn.ctrl->rindex, lv2_atom_total_size(midiEv), kUridAtomTransferEvent, &midiEv);
  4189. }
  4190. }
  4191. #endif
  4192. }
  4193. // -------------------------------------------------------------------
  4194. // Internal helper functions
  4195. void cloneLV2Files(const CarlaPlugin& other) override
  4196. {
  4197. CARLA_SAFE_ASSERT_RETURN(other.getType() == PLUGIN_LV2,);
  4198. const CarlaPluginLV2& otherLV2((const CarlaPluginLV2&)other);
  4199. const File tmpDir(handleStateMapToAbsolutePath(false, false, true, "."));
  4200. if (tmpDir.exists())
  4201. tmpDir.deleteRecursively();
  4202. const File otherStateDir(otherLV2.handleStateMapToAbsolutePath(false, false, false, "."));
  4203. if (otherStateDir.exists())
  4204. otherStateDir.copyDirectoryTo(tmpDir);
  4205. const File otherTmpDir(otherLV2.handleStateMapToAbsolutePath(false, false, true, "."));
  4206. if (otherTmpDir.exists())
  4207. otherTmpDir.copyDirectoryTo(tmpDir);
  4208. }
  4209. void restoreLV2State(const bool temporary) noexcept override
  4210. {
  4211. if (fExt.state == nullptr || fExt.state->restore == nullptr)
  4212. return;
  4213. if (! temporary)
  4214. {
  4215. const File tmpDir(handleStateMapToAbsolutePath(false, false, true, "."));
  4216. if (tmpDir.exists())
  4217. tmpDir.deleteRecursively();
  4218. }
  4219. LV2_State_Status status = LV2_STATE_ERR_UNKNOWN;
  4220. {
  4221. const ScopedSingleProcessLocker spl(this, !fHasThreadSafeRestore);
  4222. try {
  4223. status = fExt.state->restore(fHandle,
  4224. carla_lv2_state_retrieve,
  4225. this,
  4226. LV2_STATE_IS_POD,
  4227. temporary ? fFeatures : fStateFeatures);
  4228. } catch(...) {}
  4229. if (fHandle2 != nullptr)
  4230. {
  4231. try {
  4232. fExt.state->restore(fHandle,
  4233. carla_lv2_state_retrieve,
  4234. this,
  4235. LV2_STATE_IS_POD,
  4236. temporary ? fFeatures : fStateFeatures);
  4237. } catch(...) {}
  4238. }
  4239. }
  4240. switch (status)
  4241. {
  4242. case LV2_STATE_SUCCESS:
  4243. carla_debug("CarlaPluginLV2::updateLV2State() - success");
  4244. break;
  4245. case LV2_STATE_ERR_UNKNOWN:
  4246. carla_stderr("CarlaPluginLV2::updateLV2State() - unknown error");
  4247. break;
  4248. case LV2_STATE_ERR_BAD_TYPE:
  4249. carla_stderr("CarlaPluginLV2::updateLV2State() - error, bad type");
  4250. break;
  4251. case LV2_STATE_ERR_BAD_FLAGS:
  4252. carla_stderr("CarlaPluginLV2::updateLV2State() - error, bad flags");
  4253. break;
  4254. case LV2_STATE_ERR_NO_FEATURE:
  4255. carla_stderr("CarlaPluginLV2::updateLV2State() - error, missing feature");
  4256. break;
  4257. case LV2_STATE_ERR_NO_PROPERTY:
  4258. carla_stderr("CarlaPluginLV2::updateLV2State() - error, missing property");
  4259. break;
  4260. case LV2_STATE_ERR_NO_SPACE:
  4261. carla_stderr("CarlaPluginLV2::updateLV2State() - error, insufficient space");
  4262. break;
  4263. }
  4264. }
  4265. // -------------------------------------------------------------------
  4266. bool isRealtimeSafe() const noexcept
  4267. {
  4268. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr, false);
  4269. for (uint32_t i=0; i < fRdfDescriptor->FeatureCount; ++i)
  4270. {
  4271. if (std::strcmp(fRdfDescriptor->Features[i].URI, LV2_CORE__hardRTCapable) == 0)
  4272. return true;
  4273. }
  4274. return false;
  4275. }
  4276. // -------------------------------------------------------------------
  4277. bool isUiBridgeable(const uint32_t uiId) const noexcept
  4278. {
  4279. CARLA_SAFE_ASSERT_RETURN(uiId < fRdfDescriptor->UICount, false);
  4280. #ifndef LV2_UIS_ONLY_INPROCESS
  4281. const LV2_RDF_UI* const rdfUI(&fRdfDescriptor->UIs[uiId]);
  4282. for (uint32_t i=0; i < rdfUI->FeatureCount; ++i)
  4283. {
  4284. const LV2_RDF_Feature& feat(rdfUI->Features[i]);
  4285. if (! feat.Required)
  4286. continue;
  4287. if (std::strcmp(feat.URI, LV2_INSTANCE_ACCESS_URI) == 0)
  4288. return false;
  4289. if (std::strcmp(feat.URI, LV2_DATA_ACCESS_URI) == 0)
  4290. return false;
  4291. }
  4292. // Calf UIs are mostly useless without their special graphs
  4293. // but they can be crashy under certain conditions, so follow user preferences
  4294. if (std::strstr(rdfUI->URI, "http://calf.sourceforge.net/plugins/gui/") != nullptr)
  4295. return pData->engine->getOptions().preferUiBridges;
  4296. // LSP-Plugins UIs make heavy use of URIDs, for which carla right now is very slow
  4297. // FIXME after some optimization, remove this
  4298. if (std::strstr(rdfUI->URI, "http://lsp-plug.in/ui/lv2/") != nullptr)
  4299. return false;
  4300. return true;
  4301. #else
  4302. return false;
  4303. #endif
  4304. }
  4305. bool isUiResizable() const noexcept
  4306. {
  4307. CARLA_SAFE_ASSERT_RETURN(fUI.rdfDescriptor != nullptr, false);
  4308. for (uint32_t i=0; i < fUI.rdfDescriptor->FeatureCount; ++i)
  4309. {
  4310. if (std::strcmp(fUI.rdfDescriptor->Features[i].URI, LV2_UI__fixedSize) == 0)
  4311. return false;
  4312. if (std::strcmp(fUI.rdfDescriptor->Features[i].URI, LV2_UI__noUserResize) == 0)
  4313. return false;
  4314. }
  4315. return true;
  4316. }
  4317. const char* getUiBridgeBinary(const LV2_Property type) const
  4318. {
  4319. CarlaString bridgeBinary(pData->engine->getOptions().binaryDir);
  4320. if (bridgeBinary.isEmpty())
  4321. return nullptr;
  4322. switch (type)
  4323. {
  4324. case LV2_UI_GTK2:
  4325. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-gtk2";
  4326. break;
  4327. case LV2_UI_GTK3:
  4328. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-gtk3";
  4329. break;
  4330. case LV2_UI_QT4:
  4331. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-qt4";
  4332. break;
  4333. case LV2_UI_QT5:
  4334. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-qt5";
  4335. break;
  4336. case LV2_UI_COCOA:
  4337. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-cocoa";
  4338. break;
  4339. case LV2_UI_WINDOWS:
  4340. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-windows";
  4341. break;
  4342. case LV2_UI_X11:
  4343. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-x11";
  4344. break;
  4345. case LV2_UI_MOD:
  4346. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-modgui";
  4347. break;
  4348. #if 0
  4349. case LV2_UI_EXTERNAL:
  4350. case LV2_UI_OLD_EXTERNAL:
  4351. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-external";
  4352. break;
  4353. #endif
  4354. default:
  4355. return nullptr;
  4356. }
  4357. #ifdef CARLA_OS_WIN
  4358. bridgeBinary += ".exe";
  4359. #endif
  4360. if (! File(bridgeBinary.buffer()).existsAsFile())
  4361. return nullptr;
  4362. return bridgeBinary.dupSafe();
  4363. }
  4364. // -------------------------------------------------------------------
  4365. void recheckExtensions()
  4366. {
  4367. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr,);
  4368. carla_debug("CarlaPluginLV2::recheckExtensions()");
  4369. fExt.options = nullptr;
  4370. fExt.programs = nullptr;
  4371. fExt.state = nullptr;
  4372. fExt.worker = nullptr;
  4373. fExt.inlineDisplay = nullptr;
  4374. for (uint32_t i=0; i < fRdfDescriptor->ExtensionCount; ++i)
  4375. {
  4376. const char* const extension = fRdfDescriptor->Extensions[i];
  4377. CARLA_SAFE_ASSERT_CONTINUE(extension != nullptr);
  4378. /**/ if (std::strcmp(extension, LV2_OPTIONS__interface) == 0)
  4379. pData->hints |= PLUGIN_HAS_EXTENSION_OPTIONS;
  4380. else if (std::strcmp(extension, LV2_PROGRAMS__Interface) == 0)
  4381. pData->hints |= PLUGIN_HAS_EXTENSION_PROGRAMS;
  4382. else if (std::strcmp(extension, LV2_STATE__interface) == 0)
  4383. pData->hints |= PLUGIN_HAS_EXTENSION_STATE;
  4384. else if (std::strcmp(extension, LV2_WORKER__interface) == 0)
  4385. pData->hints |= PLUGIN_HAS_EXTENSION_WORKER;
  4386. else if (std::strcmp(extension, LV2_INLINEDISPLAY__interface) == 0)
  4387. pData->hints |= PLUGIN_HAS_EXTENSION_INLINE_DISPLAY;
  4388. else if (std::strcmp(extension, LV2_MIDNAM__interface) == 0)
  4389. pData->hints |= PLUGIN_HAS_EXTENSION_MIDNAM;
  4390. else
  4391. carla_stdout("Plugin '%s' has non-supported extension: '%s'", fRdfDescriptor->URI, extension);
  4392. }
  4393. // Fix for broken plugins, nasty!
  4394. for (uint32_t i=0; i < fRdfDescriptor->FeatureCount; ++i)
  4395. {
  4396. const LV2_RDF_Feature& feature(fRdfDescriptor->Features[i]);
  4397. if (std::strcmp(feature.URI, LV2_INLINEDISPLAY__queue_draw) == 0)
  4398. {
  4399. if (pData->hints & PLUGIN_HAS_EXTENSION_INLINE_DISPLAY)
  4400. break;
  4401. carla_stdout("Plugin '%s' uses inline-display but does not set extension data, nasty!", fRdfDescriptor->URI);
  4402. pData->hints |= PLUGIN_HAS_EXTENSION_INLINE_DISPLAY;
  4403. }
  4404. else if (std::strcmp(feature.URI, LV2_MIDNAM__update) == 0)
  4405. {
  4406. if (pData->hints & PLUGIN_HAS_EXTENSION_MIDNAM)
  4407. break;
  4408. carla_stdout("Plugin '%s' uses midnam but does not set extension data, nasty!", fRdfDescriptor->URI);
  4409. pData->hints |= PLUGIN_HAS_EXTENSION_MIDNAM;
  4410. }
  4411. }
  4412. if (fDescriptor->extension_data != nullptr)
  4413. {
  4414. if (pData->hints & PLUGIN_HAS_EXTENSION_OPTIONS)
  4415. fExt.options = (const LV2_Options_Interface*)fDescriptor->extension_data(LV2_OPTIONS__interface);
  4416. if (pData->hints & PLUGIN_HAS_EXTENSION_PROGRAMS)
  4417. fExt.programs = (const LV2_Programs_Interface*)fDescriptor->extension_data(LV2_PROGRAMS__Interface);
  4418. if (pData->hints & PLUGIN_HAS_EXTENSION_STATE)
  4419. fExt.state = (const LV2_State_Interface*)fDescriptor->extension_data(LV2_STATE__interface);
  4420. if (pData->hints & PLUGIN_HAS_EXTENSION_WORKER)
  4421. fExt.worker = (const LV2_Worker_Interface*)fDescriptor->extension_data(LV2_WORKER__interface);
  4422. if (pData->hints & PLUGIN_HAS_EXTENSION_INLINE_DISPLAY)
  4423. fExt.inlineDisplay = (const LV2_Inline_Display_Interface*)fDescriptor->extension_data(LV2_INLINEDISPLAY__interface);
  4424. if (pData->hints & PLUGIN_HAS_EXTENSION_MIDNAM)
  4425. fExt.midnam = (const LV2_Midnam_Interface*)fDescriptor->extension_data(LV2_MIDNAM__interface);
  4426. // check if invalid
  4427. if (fExt.options != nullptr && fExt.options->get == nullptr && fExt.options->set == nullptr)
  4428. fExt.options = nullptr;
  4429. if (fExt.programs != nullptr && (fExt.programs->get_program == nullptr || fExt.programs->select_program == nullptr))
  4430. fExt.programs = nullptr;
  4431. if (fExt.state != nullptr && (fExt.state->save == nullptr || fExt.state->restore == nullptr))
  4432. fExt.state = nullptr;
  4433. if (fExt.worker != nullptr && fExt.worker->work == nullptr)
  4434. fExt.worker = nullptr;
  4435. if (fExt.inlineDisplay != nullptr)
  4436. {
  4437. if (fExt.inlineDisplay->render != nullptr)
  4438. {
  4439. pData->hints |= PLUGIN_HAS_INLINE_DISPLAY;
  4440. pData->setCanDeleteLib(false);
  4441. }
  4442. else
  4443. {
  4444. fExt.inlineDisplay = nullptr;
  4445. }
  4446. }
  4447. if (fExt.midnam != nullptr && fExt.midnam->midnam == nullptr)
  4448. fExt.midnam = nullptr;
  4449. }
  4450. CARLA_SAFE_ASSERT_RETURN(fLatencyIndex == -1,);
  4451. int32_t iCtrl=0;
  4452. for (uint32_t i=0, count=fRdfDescriptor->PortCount; i<count; ++i)
  4453. {
  4454. const LV2_Property portTypes(fRdfDescriptor->Ports[i].Types);
  4455. if (! LV2_IS_PORT_CONTROL(portTypes))
  4456. continue;
  4457. const CarlaScopedValueSetter<int32_t> svs(iCtrl, iCtrl, iCtrl+1);
  4458. if (! LV2_IS_PORT_OUTPUT(portTypes))
  4459. continue;
  4460. const LV2_Property portDesignation(fRdfDescriptor->Ports[i].Designation);
  4461. if (! LV2_IS_PORT_DESIGNATION_LATENCY(portDesignation))
  4462. continue;
  4463. fLatencyIndex = iCtrl;
  4464. break;
  4465. }
  4466. }
  4467. // -------------------------------------------------------------------
  4468. void updateUi()
  4469. {
  4470. CARLA_SAFE_ASSERT_RETURN(fUI.handle != nullptr,);
  4471. CARLA_SAFE_ASSERT_RETURN(fUI.descriptor != nullptr,);
  4472. carla_debug("CarlaPluginLV2::updateUi()");
  4473. // update midi program
  4474. if (fExt.uiprograms != nullptr && pData->midiprog.count > 0 && pData->midiprog.current >= 0)
  4475. {
  4476. const MidiProgramData& curData(pData->midiprog.getCurrent());
  4477. fExt.uiprograms->select_program(fUI.handle, curData.bank, curData.program);
  4478. }
  4479. // update control ports
  4480. if (fUI.descriptor->port_event != nullptr)
  4481. {
  4482. float value;
  4483. for (uint32_t i=0; i < pData->param.count; ++i)
  4484. {
  4485. value = getParameterValue(i);
  4486. fUI.descriptor->port_event(fUI.handle, static_cast<uint32_t>(pData->param.data[i].rindex), sizeof(float), kUridNull, &value);
  4487. }
  4488. }
  4489. }
  4490. void inspectAtomForParameterChange(const LV2_Atom* const atom)
  4491. {
  4492. if (atom->type != kUridAtomBlank && atom->type != kUridAtomObject)
  4493. return;
  4494. const LV2_Atom_Object_Body* const objbody = (const LV2_Atom_Object_Body*)(atom + 1);
  4495. if (objbody->otype != kUridPatchSet)
  4496. return;
  4497. const LV2_Atom_URID *property = NULL;
  4498. const LV2_Atom_Bool *carlaParam = NULL;
  4499. const LV2_Atom *value = NULL;
  4500. lv2_atom_object_body_get(atom->size, objbody,
  4501. kUridCarlaParameterChange, (const LV2_Atom**)&carlaParam,
  4502. kUridPatchProperty, (const LV2_Atom**)&property,
  4503. kUridPatchValue, &value,
  4504. 0);
  4505. if (carlaParam != nullptr && carlaParam->body != 0)
  4506. return;
  4507. if (property == nullptr || value == nullptr)
  4508. return;
  4509. switch (value->type)
  4510. {
  4511. case kUridAtomBool:
  4512. case kUridAtomInt:
  4513. //case kUridAtomLong:
  4514. case kUridAtomFloat:
  4515. case kUridAtomDouble:
  4516. break;
  4517. default:
  4518. return;
  4519. }
  4520. uint32_t parameterId;
  4521. if (! getParameterIndexForURID(property->body, parameterId))
  4522. return;
  4523. const uint8_t* const vbody = (const uint8_t*)(value + 1);
  4524. float rvalue;
  4525. switch (value->type)
  4526. {
  4527. case kUridAtomBool:
  4528. rvalue = *(const int32_t*)vbody != 0 ? 1.0f : 0.0f;
  4529. break;
  4530. case kUridAtomInt:
  4531. rvalue = static_cast<float>(*(const int32_t*)vbody);
  4532. break;
  4533. /*
  4534. case kUridAtomLong:
  4535. rvalue = *(int64_t*)vbody;
  4536. break;
  4537. */
  4538. case kUridAtomFloat:
  4539. rvalue = *(const float*)vbody;
  4540. break;
  4541. case kUridAtomDouble:
  4542. rvalue = static_cast<float>(*(const double*)vbody);
  4543. break;
  4544. default:
  4545. rvalue = 0.0f;
  4546. break;
  4547. }
  4548. rvalue = pData->param.getFixedValue(parameterId, rvalue);
  4549. fParamBuffers[parameterId] = rvalue;
  4550. CarlaPlugin::setParameterValue(parameterId, rvalue, false, true, true);
  4551. }
  4552. bool getParameterIndexForURI(const char* const uri, uint32_t& parameterId) noexcept
  4553. {
  4554. parameterId = UINT32_MAX;
  4555. for (uint32_t i=0; i < fRdfDescriptor->ParameterCount; ++i)
  4556. {
  4557. const LV2_RDF_Parameter& rdfParam(fRdfDescriptor->Parameters[i]);
  4558. switch (rdfParam.Type)
  4559. {
  4560. case LV2_PARAMETER_TYPE_BOOL:
  4561. case LV2_PARAMETER_TYPE_INT:
  4562. // case LV2_PARAMETER_TYPE_LONG:
  4563. case LV2_PARAMETER_TYPE_FLOAT:
  4564. case LV2_PARAMETER_TYPE_DOUBLE:
  4565. break;
  4566. default:
  4567. continue;
  4568. }
  4569. if (std::strcmp(rdfParam.URI, uri) == 0)
  4570. {
  4571. const int32_t rindex = static_cast<int32_t>(fRdfDescriptor->PortCount + i);
  4572. for (uint32_t j=0; j < pData->param.count; ++j)
  4573. {
  4574. if (pData->param.data[j].rindex == rindex)
  4575. {
  4576. parameterId = j;
  4577. break;
  4578. }
  4579. }
  4580. break;
  4581. }
  4582. }
  4583. return (parameterId != UINT32_MAX);
  4584. }
  4585. bool getParameterIndexForURID(const LV2_URID urid, uint32_t& parameterId) noexcept
  4586. {
  4587. parameterId = UINT32_MAX;
  4588. if (urid >= fCustomURIDs.size())
  4589. return false;
  4590. for (uint32_t i=0; i < fRdfDescriptor->ParameterCount; ++i)
  4591. {
  4592. const LV2_RDF_Parameter& rdfParam(fRdfDescriptor->Parameters[i]);
  4593. switch (rdfParam.Type)
  4594. {
  4595. case LV2_PARAMETER_TYPE_BOOL:
  4596. case LV2_PARAMETER_TYPE_INT:
  4597. // case LV2_PARAMETER_TYPE_LONG:
  4598. case LV2_PARAMETER_TYPE_FLOAT:
  4599. case LV2_PARAMETER_TYPE_DOUBLE:
  4600. break;
  4601. default:
  4602. continue;
  4603. }
  4604. const std::string& uri(fCustomURIDs[urid]);
  4605. if (uri != rdfParam.URI)
  4606. continue;
  4607. const int32_t rindex = static_cast<int32_t>(fRdfDescriptor->PortCount + i);
  4608. for (uint32_t j=0; j < pData->param.count; ++j)
  4609. {
  4610. if (pData->param.data[j].rindex == rindex)
  4611. {
  4612. parameterId = j;
  4613. break;
  4614. }
  4615. }
  4616. break;
  4617. }
  4618. return (parameterId != UINT32_MAX);
  4619. }
  4620. // -------------------------------------------------------------------
  4621. LV2_URID getCustomURID(const char* const uri)
  4622. {
  4623. CARLA_SAFE_ASSERT_RETURN(uri != nullptr && uri[0] != '\0', kUridNull);
  4624. carla_debug("CarlaPluginLV2::getCustomURID(\"%s\")", uri);
  4625. const std::string s_uri(uri);
  4626. const std::ptrdiff_t s_pos(std::find(fCustomURIDs.begin(), fCustomURIDs.end(), s_uri) - fCustomURIDs.begin());
  4627. if (s_pos <= 0 || s_pos >= INT32_MAX)
  4628. return kUridNull;
  4629. const LV2_URID urid = static_cast<LV2_URID>(s_pos);
  4630. const LV2_URID uriCount = static_cast<LV2_URID>(fCustomURIDs.size());
  4631. if (urid < uriCount)
  4632. return urid;
  4633. CARLA_SAFE_ASSERT(urid == uriCount);
  4634. fCustomURIDs.push_back(uri);
  4635. if (fUI.type == UI::TYPE_BRIDGE && fPipeServer.isPipeRunning())
  4636. fPipeServer.writeLv2UridMessage(urid, uri);
  4637. return urid;
  4638. }
  4639. const char* getCustomURIDString(const LV2_URID urid) const noexcept
  4640. {
  4641. CARLA_SAFE_ASSERT_RETURN(urid != kUridNull, kUnmapFallback);
  4642. CARLA_SAFE_ASSERT_RETURN(urid < fCustomURIDs.size(), kUnmapFallback);
  4643. carla_debug("CarlaPluginLV2::getCustomURIString(%i)", urid);
  4644. return fCustomURIDs[urid].c_str();
  4645. }
  4646. // -------------------------------------------------------------------
  4647. void handleProgramChanged(const int32_t index)
  4648. {
  4649. CARLA_SAFE_ASSERT_RETURN(index >= -1,);
  4650. carla_debug("CarlaPluginLV2::handleProgramChanged(%i)", index);
  4651. if (index == -1)
  4652. {
  4653. const ScopedSingleProcessLocker spl(this, true);
  4654. return reloadPrograms(false);
  4655. }
  4656. if (index < static_cast<int32_t>(pData->midiprog.count) && fExt.programs != nullptr && fExt.programs->get_program != nullptr)
  4657. {
  4658. if (const LV2_Program_Descriptor* const progDesc = fExt.programs->get_program(fHandle, static_cast<uint32_t>(index)))
  4659. {
  4660. CARLA_SAFE_ASSERT_RETURN(progDesc->name != nullptr,);
  4661. if (pData->midiprog.data[index].name != nullptr)
  4662. delete[] pData->midiprog.data[index].name;
  4663. pData->midiprog.data[index].name = carla_strdup(progDesc->name);
  4664. if (index == pData->midiprog.current)
  4665. pData->engine->callback(true, true, ENGINE_CALLBACK_UPDATE, pData->id, 0, 0, 0, 0.0, nullptr);
  4666. else
  4667. pData->engine->callback(true, true, ENGINE_CALLBACK_RELOAD_PROGRAMS, pData->id, 0, 0, 0, 0.0, nullptr);
  4668. }
  4669. }
  4670. }
  4671. // -------------------------------------------------------------------
  4672. LV2_Resize_Port_Status handleResizePort(const uint32_t index, const size_t size)
  4673. {
  4674. CARLA_SAFE_ASSERT_RETURN(size > 0, LV2_RESIZE_PORT_ERR_UNKNOWN);
  4675. carla_debug("CarlaPluginLV2::handleResizePort(%i, " P_SIZE ")", index, size);
  4676. // TODO
  4677. return LV2_RESIZE_PORT_ERR_NO_SPACE;
  4678. (void)index;
  4679. }
  4680. // -------------------------------------------------------------------
  4681. char* handleStateMapToAbstractPath(const bool temporary, const char* const absolutePath) const
  4682. {
  4683. // may already be an abstract path
  4684. if (! File::isAbsolutePath(absolutePath))
  4685. return strdup(absolutePath);
  4686. File projectDir, targetDir;
  4687. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  4688. if (const char* const projFolder = pData->engine->getCurrentProjectFolder())
  4689. projectDir = projFolder;
  4690. else
  4691. #endif
  4692. projectDir = File::getCurrentWorkingDirectory();
  4693. if (projectDir.isNull())
  4694. {
  4695. carla_stdout("Project directory not set, cannot map absolutePath %s", absolutePath);
  4696. return nullptr;
  4697. }
  4698. water::String basedir(pData->engine->getName());
  4699. if (temporary)
  4700. basedir += ".tmp";
  4701. targetDir = projectDir.getChildFile(basedir)
  4702. .getChildFile(getName());
  4703. if (! targetDir.exists())
  4704. targetDir.createDirectory();
  4705. const File wabsolutePath(absolutePath);
  4706. // we may be saving to non-tmp path, let's check
  4707. if (! temporary)
  4708. {
  4709. const File tmpDir = projectDir.getChildFile(basedir + ".tmp")
  4710. .getChildFile(getName());
  4711. if (wabsolutePath.getFullPathName().startsWith(tmpDir.getFullPathName()))
  4712. {
  4713. // gotcha, the temporary path is now the real one
  4714. targetDir = tmpDir;
  4715. }
  4716. else if (! wabsolutePath.getFullPathName().startsWith(targetDir.getFullPathName()))
  4717. {
  4718. // seems like a normal save, let's be nice and put a symlink
  4719. const water::String abstractFilename(wabsolutePath.getFileName());
  4720. const File targetPath(targetDir.getChildFile(abstractFilename));
  4721. wabsolutePath.createSymbolicLink(targetPath, true);
  4722. carla_stdout("Creating symlink for '%s' in '%s'", absolutePath, targetDir.getFullPathName().toRawUTF8());
  4723. return strdup(abstractFilename.toRawUTF8());
  4724. }
  4725. }
  4726. carla_stdout("Mapping absolutePath '%s' relative to targetDir '%s'",
  4727. absolutePath, targetDir.getFullPathName().toRawUTF8());
  4728. return strdup(wabsolutePath.getRelativePathFrom(targetDir).toRawUTF8());
  4729. }
  4730. File handleStateMapToAbsolutePath(const bool createDirIfNeeded,
  4731. const bool symlinkIfNeeded,
  4732. const bool temporary,
  4733. const char* const abstractPath) const
  4734. {
  4735. File targetDir, targetPath;
  4736. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  4737. if (const char* const projFolder = pData->engine->getCurrentProjectFolder())
  4738. targetDir = projFolder;
  4739. else
  4740. #endif
  4741. targetDir = File::getCurrentWorkingDirectory();
  4742. if (targetDir.isNull())
  4743. {
  4744. carla_stdout("Project directory not set, cannot map abstractPath '%s'", abstractPath);
  4745. return File();
  4746. }
  4747. water::String basedir(pData->engine->getName());
  4748. if (temporary)
  4749. basedir += ".tmp";
  4750. targetDir = targetDir.getChildFile(basedir)
  4751. .getChildFile(getName());
  4752. if (createDirIfNeeded && ! targetDir.exists())
  4753. targetDir.createDirectory();
  4754. if (File::isAbsolutePath(abstractPath))
  4755. {
  4756. File wabstractPath(abstractPath);
  4757. targetPath = targetDir.getChildFile(wabstractPath.getFileName());
  4758. if (symlinkIfNeeded)
  4759. {
  4760. carla_stdout("Creating symlink for '%s' in '%s'",
  4761. abstractPath, targetDir.getFullPathName().toRawUTF8());
  4762. wabstractPath.createSymbolicLink(targetPath, true);
  4763. }
  4764. }
  4765. else
  4766. {
  4767. targetPath = targetDir.getChildFile(abstractPath);
  4768. targetDir = targetPath.getParentDirectory();
  4769. if (createDirIfNeeded && ! targetDir.exists())
  4770. targetDir.createDirectory();
  4771. }
  4772. if (std::strcmp(abstractPath, ".") != 0)
  4773. carla_stdout("Mapping abstractPath '%s' relative to targetDir '%s'",
  4774. abstractPath, targetDir.getFullPathName().toRawUTF8());
  4775. return targetPath;
  4776. }
  4777. LV2_State_Status handleStateStore(const uint32_t key, const void* const value, const size_t size, const uint32_t type, const uint32_t flags)
  4778. {
  4779. CARLA_SAFE_ASSERT_RETURN(key != kUridNull, LV2_STATE_ERR_NO_PROPERTY);
  4780. CARLA_SAFE_ASSERT_RETURN(value != nullptr, LV2_STATE_ERR_NO_PROPERTY);
  4781. CARLA_SAFE_ASSERT_RETURN(size > 0, LV2_STATE_ERR_NO_PROPERTY);
  4782. CARLA_SAFE_ASSERT_RETURN(type != kUridNull, LV2_STATE_ERR_BAD_TYPE);
  4783. // FIXME linuxsampler does not set POD flag
  4784. // CARLA_SAFE_ASSERT_RETURN(flags & LV2_STATE_IS_POD, LV2_STATE_ERR_BAD_FLAGS);
  4785. carla_debug("CarlaPluginLV2::handleStateStore(%i:\"%s\", %p, " P_SIZE ", %i:\"%s\", %i)",
  4786. key, carla_lv2_urid_unmap(this, key), value, size, type, carla_lv2_urid_unmap(this, type), flags);
  4787. const char* const skey(carla_lv2_urid_unmap(this, key));
  4788. const char* const stype(carla_lv2_urid_unmap(this, type));
  4789. CARLA_SAFE_ASSERT_RETURN(skey != nullptr && skey != kUnmapFallback, LV2_STATE_ERR_BAD_TYPE);
  4790. CARLA_SAFE_ASSERT_RETURN(stype != nullptr && stype != kUnmapFallback, LV2_STATE_ERR_BAD_TYPE);
  4791. // Check if we already have this key
  4792. for (LinkedList<CustomData>::Itenerator it = pData->custom.begin2(); it.valid(); it.next())
  4793. {
  4794. CustomData& cData(it.getValue(kCustomDataFallbackNC));
  4795. CARLA_SAFE_ASSERT_CONTINUE(cData.isValid());
  4796. if (std::strcmp(cData.key, skey) == 0)
  4797. {
  4798. // found it
  4799. delete[] cData.value;
  4800. if (type == kUridAtomString || type == kUridAtomPath)
  4801. cData.value = carla_strdup((const char*)value);
  4802. else
  4803. cData.value = CarlaString::asBase64(value, size).dup();
  4804. return LV2_STATE_SUCCESS;
  4805. }
  4806. }
  4807. // Otherwise store it
  4808. CustomData newData;
  4809. newData.type = carla_strdup(stype);
  4810. newData.key = carla_strdup(skey);
  4811. if (type == kUridAtomString || type == kUridAtomPath)
  4812. newData.value = carla_strdup((const char*)value);
  4813. else
  4814. newData.value = CarlaString::asBase64(value, size).dup();
  4815. pData->custom.append(newData);
  4816. return LV2_STATE_SUCCESS;
  4817. // unused
  4818. (void)flags;
  4819. }
  4820. const void* handleStateRetrieve(const uint32_t key, size_t* const size, uint32_t* const type, uint32_t* const flags)
  4821. {
  4822. CARLA_SAFE_ASSERT_RETURN(key != kUridNull, nullptr);
  4823. CARLA_SAFE_ASSERT_RETURN(size != nullptr, nullptr);
  4824. CARLA_SAFE_ASSERT_RETURN(type != nullptr, nullptr);
  4825. CARLA_SAFE_ASSERT_RETURN(flags != nullptr, nullptr);
  4826. carla_debug("CarlaPluginLV2::handleStateRetrieve(%i, %p, %p, %p)", key, size, type, flags);
  4827. const char* const skey(carla_lv2_urid_unmap(this, key));
  4828. CARLA_SAFE_ASSERT_RETURN(skey != nullptr && skey != kUnmapFallback, nullptr);
  4829. const char* stype = nullptr;
  4830. const char* stringData = nullptr;
  4831. for (LinkedList<CustomData>::Itenerator it = pData->custom.begin2(); it.valid(); it.next())
  4832. {
  4833. const CustomData& cData(it.getValue(kCustomDataFallback));
  4834. CARLA_SAFE_ASSERT_CONTINUE(cData.isValid());
  4835. if (std::strcmp(cData.key, skey) == 0)
  4836. {
  4837. stype = cData.type;
  4838. stringData = cData.value;
  4839. break;
  4840. }
  4841. }
  4842. if (stype == nullptr || stringData == nullptr)
  4843. {
  4844. carla_stderr("Plugin requested value for '%s' which is not available", skey);
  4845. *size = *type = *flags = 0;
  4846. return nullptr;
  4847. }
  4848. *type = carla_lv2_urid_map(this, stype);
  4849. *flags = LV2_STATE_IS_POD;
  4850. if (*type == kUridAtomString || *type == kUridAtomPath)
  4851. {
  4852. *size = std::strlen(stringData);
  4853. return stringData;
  4854. }
  4855. if (fLastStateChunk != nullptr)
  4856. {
  4857. std::free(fLastStateChunk);
  4858. fLastStateChunk = nullptr;
  4859. }
  4860. std::vector<uint8_t> chunk(carla_getChunkFromBase64String(stringData));
  4861. CARLA_SAFE_ASSERT_RETURN(chunk.size() > 0, nullptr);
  4862. fLastStateChunk = std::malloc(chunk.size());
  4863. CARLA_SAFE_ASSERT_RETURN(fLastStateChunk != nullptr, nullptr);
  4864. #ifdef CARLA_PROPER_CPP11_SUPPORT
  4865. std::memcpy(fLastStateChunk, chunk.data(), chunk.size());
  4866. #else
  4867. std::memcpy(fLastStateChunk, &chunk.front(), chunk.size());
  4868. #endif
  4869. *size = chunk.size();
  4870. return fLastStateChunk;
  4871. }
  4872. // -------------------------------------------------------------------
  4873. LV2_Worker_Status handleWorkerSchedule(const uint32_t size, const void* const data)
  4874. {
  4875. CARLA_SAFE_ASSERT_RETURN(fExt.worker != nullptr && fExt.worker->work != nullptr, LV2_WORKER_ERR_UNKNOWN);
  4876. CARLA_SAFE_ASSERT_RETURN(fEventsIn.ctrl != nullptr, LV2_WORKER_ERR_UNKNOWN);
  4877. carla_debug("CarlaPluginLV2::handleWorkerSchedule(%i, %p)", size, data);
  4878. if (pData->engine->isOffline())
  4879. {
  4880. fExt.worker->work(fHandle, carla_lv2_worker_respond, this, size, data);
  4881. return LV2_WORKER_SUCCESS;
  4882. }
  4883. LV2_Atom atom;
  4884. atom.size = size;
  4885. atom.type = kUridCarlaAtomWorkerIn;
  4886. return fAtomBufferWorkerIn.putChunk(&atom, data, fEventsOut.ctrlIndex) ? LV2_WORKER_SUCCESS : LV2_WORKER_ERR_NO_SPACE;
  4887. }
  4888. LV2_Worker_Status handleWorkerRespond(const uint32_t size, const void* const data)
  4889. {
  4890. CARLA_SAFE_ASSERT_RETURN(fExt.worker != nullptr && fExt.worker->work_response != nullptr, LV2_WORKER_ERR_UNKNOWN);
  4891. carla_debug("CarlaPluginLV2::handleWorkerRespond(%i, %p)", size, data);
  4892. LV2_Atom atom;
  4893. atom.size = size;
  4894. atom.type = kUridCarlaAtomWorkerResp;
  4895. return fAtomBufferWorkerResp.putChunk(&atom, data, fEventsIn.ctrlIndex) ? LV2_WORKER_SUCCESS : LV2_WORKER_ERR_NO_SPACE;
  4896. }
  4897. // -------------------------------------------------------------------
  4898. void handleInlineDisplayQueueRedraw()
  4899. {
  4900. switch (pData->engine->getProccessMode())
  4901. {
  4902. case ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS:
  4903. case ENGINE_PROCESS_MODE_PATCHBAY:
  4904. fInlineDisplayNeedsRedraw = true;
  4905. break;
  4906. default:
  4907. break;
  4908. }
  4909. }
  4910. const LV2_Inline_Display_Image_Surface* renderInlineDisplay(const uint32_t width, const uint32_t height) const
  4911. {
  4912. CARLA_SAFE_ASSERT_RETURN(fExt.inlineDisplay != nullptr && fExt.inlineDisplay->render != nullptr, nullptr);
  4913. CARLA_SAFE_ASSERT_RETURN(width > 0, nullptr);
  4914. CARLA_SAFE_ASSERT_RETURN(height > 0, nullptr);
  4915. return fExt.inlineDisplay->render(fHandle, width, height);
  4916. }
  4917. // -------------------------------------------------------------------
  4918. void handleMidnamUpdate()
  4919. {
  4920. CARLA_SAFE_ASSERT_RETURN(fExt.midnam != nullptr,);
  4921. if (fEventsIn.ctrl == nullptr)
  4922. return;
  4923. char* const midnam = fExt.midnam->midnam(fHandle);
  4924. CARLA_SAFE_ASSERT_RETURN(midnam != nullptr,);
  4925. fEventsIn.ctrl->port->setMetaData("http://www.midi.org/dtds/MIDINameDocument10.dtd", midnam, "text/xml");
  4926. if (fExt.midnam->free != nullptr)
  4927. fExt.midnam->free(midnam);
  4928. }
  4929. // -------------------------------------------------------------------
  4930. void handleExternalUIClosed()
  4931. {
  4932. CARLA_SAFE_ASSERT_RETURN(fUI.type == UI::TYPE_EXTERNAL,);
  4933. carla_debug("CarlaPluginLV2::handleExternalUIClosed()");
  4934. fNeedsUiClose = true;
  4935. }
  4936. void handlePluginUIClosed() override
  4937. {
  4938. CARLA_SAFE_ASSERT_RETURN(fUI.type == UI::TYPE_EMBED,);
  4939. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  4940. carla_debug("CarlaPluginLV2::handlePluginUIClosed()");
  4941. fNeedsUiClose = true;
  4942. }
  4943. void handlePluginUIResized(const uint width, const uint height) override
  4944. {
  4945. CARLA_SAFE_ASSERT_RETURN(fUI.type == UI::TYPE_EMBED,);
  4946. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  4947. carla_debug("CarlaPluginLV2::handlePluginUIResized(%u, %u)", width, height);
  4948. if (fUI.handle != nullptr && fExt.uiresize != nullptr)
  4949. fExt.uiresize->ui_resize(fUI.handle, static_cast<int>(width), static_cast<int>(height));
  4950. }
  4951. // -------------------------------------------------------------------
  4952. uint32_t handleUIPortMap(const char* const symbol) const noexcept
  4953. {
  4954. CARLA_SAFE_ASSERT_RETURN(symbol != nullptr && symbol[0] != '\0', LV2UI_INVALID_PORT_INDEX);
  4955. carla_debug("CarlaPluginLV2::handleUIPortMap(\"%s\")", symbol);
  4956. for (uint32_t i=0; i < fRdfDescriptor->PortCount; ++i)
  4957. {
  4958. if (std::strcmp(fRdfDescriptor->Ports[i].Symbol, symbol) == 0)
  4959. return i;
  4960. }
  4961. return LV2UI_INVALID_PORT_INDEX;
  4962. }
  4963. LV2UI_Request_Value_Status handleUIRequestValue(const LV2_URID key,
  4964. const LV2_URID type,
  4965. const LV2_Feature* const* features)
  4966. {
  4967. CARLA_SAFE_ASSERT_RETURN(fUI.type != UI::TYPE_NULL, LV2UI_REQUEST_VALUE_ERR_UNKNOWN);
  4968. carla_debug("CarlaPluginLV2::handleUIRequestValue(%u, %u, %p)", key, type, features);
  4969. if (type != kUridAtomPath)
  4970. return LV2UI_REQUEST_VALUE_ERR_UNSUPPORTED;
  4971. const char* const uri = getCustomURIDString(key);
  4972. CARLA_SAFE_ASSERT_RETURN(uri != nullptr && uri != kUnmapFallback, LV2UI_REQUEST_VALUE_ERR_UNKNOWN);
  4973. // check if a file browser is already open
  4974. if (fUI.fileNeededForURI != nullptr || fUI.fileBrowserOpen)
  4975. return LV2UI_REQUEST_VALUE_BUSY;
  4976. for (uint32_t i=0; i < fRdfDescriptor->ParameterCount; ++i)
  4977. {
  4978. if (fRdfDescriptor->Parameters[i].Type != LV2_PARAMETER_TYPE_PATH)
  4979. continue;
  4980. if (std::strcmp(fRdfDescriptor->Parameters[i].URI, uri) != 0)
  4981. continue;
  4982. // TODO file browser filters, also store label to use for title
  4983. fUI.fileNeededForURI = uri;
  4984. return LV2UI_REQUEST_VALUE_SUCCESS;
  4985. }
  4986. return LV2UI_REQUEST_VALUE_ERR_UNSUPPORTED;
  4987. // may be unused
  4988. (void)features;
  4989. }
  4990. int handleUIResize(const int width, const int height)
  4991. {
  4992. CARLA_SAFE_ASSERT_RETURN(width > 0, 1);
  4993. CARLA_SAFE_ASSERT_RETURN(height > 0, 1);
  4994. carla_debug("CarlaPluginLV2::handleUIResize(%i, %i)", width, height);
  4995. if (fUI.embedded)
  4996. {
  4997. pData->engine->callback(true, true,
  4998. ENGINE_CALLBACK_EMBED_UI_RESIZED,
  4999. pData->id, width, height,
  5000. 0, 0.0f, nullptr);
  5001. }
  5002. else
  5003. {
  5004. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr, 1);
  5005. fUI.window->setSize(static_cast<uint>(width), static_cast<uint>(height), true);
  5006. }
  5007. return 0;
  5008. }
  5009. void handleUITouch(const uint32_t rindex, const bool touch)
  5010. {
  5011. carla_debug("CarlaPluginLV2::handleUITouch(%u, %s)", rindex, bool2str(touch));
  5012. uint32_t index = LV2UI_INVALID_PORT_INDEX;
  5013. for (uint32_t i=0; i < pData->param.count; ++i)
  5014. {
  5015. if (pData->param.data[i].rindex != static_cast<int32_t>(rindex))
  5016. continue;
  5017. index = i;
  5018. break;
  5019. }
  5020. CARLA_SAFE_ASSERT_RETURN(index != LV2UI_INVALID_PORT_INDEX,);
  5021. pData->engine->touchPluginParameter(pData->id, index, touch);
  5022. }
  5023. void handleUIWrite(const uint32_t rindex, const uint32_t bufferSize, const uint32_t format, const void* const buffer)
  5024. {
  5025. CARLA_SAFE_ASSERT_RETURN(buffer != nullptr,);
  5026. CARLA_SAFE_ASSERT_RETURN(bufferSize > 0,);
  5027. carla_debug("CarlaPluginLV2::handleUIWrite(%i, %i, %i, %p)", rindex, bufferSize, format, buffer);
  5028. uint32_t index = LV2UI_INVALID_PORT_INDEX;
  5029. switch (format)
  5030. {
  5031. case kUridNull: {
  5032. CARLA_SAFE_ASSERT_RETURN(rindex < fRdfDescriptor->PortCount,);
  5033. CARLA_SAFE_ASSERT_RETURN(bufferSize == sizeof(float),);
  5034. for (uint32_t i=0; i < pData->param.count; ++i)
  5035. {
  5036. if (pData->param.data[i].rindex != static_cast<int32_t>(rindex))
  5037. continue;
  5038. index = i;
  5039. break;
  5040. }
  5041. CARLA_SAFE_ASSERT_RETURN(index != LV2UI_INVALID_PORT_INDEX,);
  5042. const float value(*(const float*)buffer);
  5043. // check if we should feedback message back to UI
  5044. bool sendGui = false;
  5045. if (const uint32_t notifCount = fUI.rdfDescriptor->PortNotificationCount)
  5046. {
  5047. const char* const portSymbol = fRdfDescriptor->Ports[rindex].Symbol;
  5048. for (uint32_t i=0; i < notifCount; ++i)
  5049. {
  5050. const LV2_RDF_UI_PortNotification& portNotif(fUI.rdfDescriptor->PortNotifications[i]);
  5051. if (portNotif.Protocol != LV2_UI_PORT_PROTOCOL_FLOAT)
  5052. continue;
  5053. if (portNotif.Symbol != nullptr)
  5054. {
  5055. if (std::strcmp(portNotif.Symbol, portSymbol) != 0)
  5056. continue;
  5057. }
  5058. else if (portNotif.Index != rindex)
  5059. {
  5060. continue;
  5061. }
  5062. sendGui = true;
  5063. break;
  5064. }
  5065. }
  5066. setParameterValue(index, value, sendGui, true, true);
  5067. } break;
  5068. case kUridAtomTransferAtom:
  5069. case kUridAtomTransferEvent: {
  5070. CARLA_SAFE_ASSERT_RETURN(bufferSize >= sizeof(LV2_Atom),);
  5071. const LV2_Atom* const atom((const LV2_Atom*)buffer);
  5072. // plugins sometimes fail on this, not good...
  5073. const uint32_t totalSize = lv2_atom_total_size(atom);
  5074. const uint32_t paddedSize = lv2_atom_pad_size(totalSize);
  5075. if (bufferSize != totalSize && bufferSize != paddedSize)
  5076. carla_stderr2("Warning: LV2 UI sending atom with invalid size %u! size: %u, padded-size: %u",
  5077. bufferSize, totalSize, paddedSize);
  5078. for (uint32_t i=0; i < fEventsIn.count; ++i)
  5079. {
  5080. if (fEventsIn.data[i].rindex != rindex)
  5081. continue;
  5082. index = i;
  5083. break;
  5084. }
  5085. // for bad plugins
  5086. if (index == LV2UI_INVALID_PORT_INDEX)
  5087. {
  5088. CARLA_SAFE_ASSERT(index != LV2UI_INVALID_PORT_INDEX); // FIXME
  5089. index = fEventsIn.ctrlIndex;
  5090. }
  5091. fAtomBufferEvIn.put(atom, index);
  5092. } break;
  5093. default:
  5094. carla_stdout("CarlaPluginLV2::handleUIWrite(%i, %i, %i:\"%s\", %p) - unknown format",
  5095. rindex, bufferSize, format, carla_lv2_urid_unmap(this, format), buffer);
  5096. break;
  5097. }
  5098. }
  5099. void handleUIBridgeParameter(const char* const uri, const float value)
  5100. {
  5101. CARLA_SAFE_ASSERT_RETURN(uri != nullptr,);
  5102. carla_debug("CarlaPluginLV2::handleUIBridgeParameter(%s, %f)", uri, static_cast<double>(value));
  5103. uint32_t parameterId;
  5104. if (getParameterIndexForURI(uri, parameterId))
  5105. setParameterValue(parameterId, value, false, true, true);
  5106. }
  5107. // -------------------------------------------------------------------
  5108. void handleLilvSetPortValue(const char* const portSymbol, const void* const value, const uint32_t size, const uint32_t type)
  5109. {
  5110. CARLA_SAFE_ASSERT_RETURN(portSymbol != nullptr && portSymbol[0] != '\0',);
  5111. CARLA_SAFE_ASSERT_RETURN(value != nullptr,);
  5112. CARLA_SAFE_ASSERT_RETURN(size > 0,);
  5113. CARLA_SAFE_ASSERT_RETURN(type != kUridNull,);
  5114. carla_debug("CarlaPluginLV2::handleLilvSetPortValue(\"%s\", %p, %i, %i)", portSymbol, value, size, type);
  5115. int32_t rindex = -1;
  5116. for (uint32_t i=0; i < fRdfDescriptor->PortCount; ++i)
  5117. {
  5118. if (std::strcmp(fRdfDescriptor->Ports[i].Symbol, portSymbol) == 0)
  5119. {
  5120. rindex = static_cast<int32_t>(i);
  5121. break;
  5122. }
  5123. }
  5124. CARLA_SAFE_ASSERT_RETURN(rindex >= 0,);
  5125. float paramValue;
  5126. switch (type)
  5127. {
  5128. case kUridAtomBool:
  5129. CARLA_SAFE_ASSERT_RETURN(size == sizeof(int32_t),);
  5130. paramValue = *(const int32_t*)value != 0 ? 1.0f : 0.0f;
  5131. break;
  5132. case kUridAtomDouble:
  5133. CARLA_SAFE_ASSERT_RETURN(size == sizeof(double),);
  5134. paramValue = static_cast<float>((*(const double*)value));
  5135. break;
  5136. case kUridAtomFloat:
  5137. CARLA_SAFE_ASSERT_RETURN(size == sizeof(float),);
  5138. paramValue = *(const float*)value;
  5139. break;
  5140. case kUridAtomInt:
  5141. CARLA_SAFE_ASSERT_RETURN(size == sizeof(int32_t),);
  5142. paramValue = static_cast<float>(*(const int32_t*)value);
  5143. break;
  5144. case kUridAtomLong:
  5145. CARLA_SAFE_ASSERT_RETURN(size == sizeof(int64_t),);
  5146. paramValue = static_cast<float>(*(const int64_t*)value);
  5147. break;
  5148. default:
  5149. carla_stdout("CarlaPluginLV2::handleLilvSetPortValue(\"%s\", %p, %i, %i:\"%s\") - unknown type",
  5150. portSymbol, value, size, type, carla_lv2_urid_unmap(this, type));
  5151. return;
  5152. }
  5153. for (uint32_t i=0; i < pData->param.count; ++i)
  5154. {
  5155. if (pData->param.data[i].rindex == rindex)
  5156. {
  5157. setParameterValueRT(i, paramValue, true);
  5158. break;
  5159. }
  5160. }
  5161. }
  5162. // -------------------------------------------------------------------
  5163. void* getNativeHandle() const noexcept override
  5164. {
  5165. return fHandle;
  5166. }
  5167. const void* getNativeDescriptor() const noexcept override
  5168. {
  5169. return fDescriptor;
  5170. }
  5171. uintptr_t getUiBridgeProcessId() const noexcept override
  5172. {
  5173. return fPipeServer.isPipeRunning() ? fPipeServer.getPID() : 0;
  5174. }
  5175. // -------------------------------------------------------------------
  5176. public:
  5177. bool init(const CarlaPluginPtr plugin,
  5178. const char* const name, const char* const uri, const uint options,
  5179. const char*& needsArchBridge)
  5180. {
  5181. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  5182. // ---------------------------------------------------------------
  5183. // first checks
  5184. if (pData->client != nullptr)
  5185. {
  5186. pData->engine->setLastError("Plugin client is already registered");
  5187. return false;
  5188. }
  5189. if (uri == nullptr || uri[0] == '\0')
  5190. {
  5191. pData->engine->setLastError("null uri");
  5192. return false;
  5193. }
  5194. const EngineOptions& opts(pData->engine->getOptions());
  5195. // ---------------------------------------------------------------
  5196. // Init LV2 World if needed, sets LV2_PATH for lilv
  5197. Lv2WorldClass& lv2World(Lv2WorldClass::getInstance());
  5198. if (opts.pathLV2 != nullptr && opts.pathLV2[0] != '\0')
  5199. lv2World.initIfNeeded(opts.pathLV2);
  5200. else if (const char* const LV2_PATH = std::getenv("LV2_PATH"))
  5201. lv2World.initIfNeeded(LV2_PATH);
  5202. else
  5203. lv2World.initIfNeeded(LILV_DEFAULT_LV2_PATH);
  5204. // ---------------------------------------------------------------
  5205. // get plugin from lv2_rdf (lilv)
  5206. fRdfDescriptor = lv2_rdf_new(uri, true);
  5207. if (fRdfDescriptor == nullptr)
  5208. {
  5209. pData->engine->setLastError("Failed to find the requested plugin");
  5210. return false;
  5211. }
  5212. #ifdef ADAPT_FOR_APPLE_SILLICON
  5213. // ---------------------------------------------------------------
  5214. // check if we can open this binary, might need a bridge
  5215. {
  5216. const CarlaMagic magic;
  5217. if (const char* const output = magic.getFileDescription(fRdfDescriptor->Binary))
  5218. {
  5219. # ifdef __aarch64__
  5220. if (std::strstr(output, "arm64") == nullptr && std::strstr(output, "x86_64") != nullptr)
  5221. needsArchBridge = "x86_64";
  5222. # else
  5223. if (std::strstr(output, "x86_64") == nullptr && std::strstr(output, "arm64") != nullptr)
  5224. needsArchBridge = "arm64";
  5225. # endif
  5226. if (needsArchBridge != nullptr)
  5227. return false;
  5228. }
  5229. }
  5230. #endif // ADAPT_FOR_APPLE_SILLICON
  5231. // ---------------------------------------------------------------
  5232. // open DLL
  5233. #ifdef CARLA_OS_MAC
  5234. // Binary might be in quarentine due to Apple stupid notarization rules, let's remove that if possible
  5235. removeFileFromQuarantine(fRdfDescriptor->Binary);
  5236. #endif
  5237. if (! pData->libOpen(fRdfDescriptor->Binary))
  5238. {
  5239. pData->engine->setLastError(pData->libError(fRdfDescriptor->Binary));
  5240. return false;
  5241. }
  5242. // ---------------------------------------------------------------
  5243. // try to get DLL main entry via new mode
  5244. if (const LV2_Lib_Descriptor_Function libDescFn = pData->libSymbol<LV2_Lib_Descriptor_Function>("lv2_lib_descriptor"))
  5245. {
  5246. // -----------------------------------------------------------
  5247. // all ok, get lib descriptor
  5248. const LV2_Lib_Descriptor* const libDesc = libDescFn(fRdfDescriptor->Bundle, nullptr);
  5249. if (libDesc == nullptr)
  5250. {
  5251. pData->engine->setLastError("Could not find the LV2 Descriptor");
  5252. return false;
  5253. }
  5254. // -----------------------------------------------------------
  5255. // get descriptor that matches URI (new mode)
  5256. uint32_t i = 0;
  5257. while ((fDescriptor = libDesc->get_plugin(libDesc->handle, i++)))
  5258. {
  5259. if (std::strcmp(fDescriptor->URI, uri) == 0)
  5260. break;
  5261. }
  5262. }
  5263. else
  5264. {
  5265. // -----------------------------------------------------------
  5266. // get DLL main entry (old mode)
  5267. const LV2_Descriptor_Function descFn = pData->libSymbol<LV2_Descriptor_Function>("lv2_descriptor");
  5268. if (descFn == nullptr)
  5269. {
  5270. pData->engine->setLastError("Could not find the LV2 Descriptor in the plugin library");
  5271. return false;
  5272. }
  5273. // -----------------------------------------------------------
  5274. // get descriptor that matches URI (old mode)
  5275. uint32_t i = 0;
  5276. while ((fDescriptor = descFn(i++)))
  5277. {
  5278. if (std::strcmp(fDescriptor->URI, uri) == 0)
  5279. break;
  5280. }
  5281. }
  5282. if (fDescriptor == nullptr)
  5283. {
  5284. pData->engine->setLastError("Could not find the requested plugin URI in the plugin library");
  5285. return false;
  5286. }
  5287. // ---------------------------------------------------------------
  5288. // check supported port-types and features
  5289. bool canContinue = true;
  5290. // Check supported ports
  5291. for (uint32_t j=0; j < fRdfDescriptor->PortCount; ++j)
  5292. {
  5293. const LV2_Property portTypes(fRdfDescriptor->Ports[j].Types);
  5294. if (! is_lv2_port_supported(portTypes))
  5295. {
  5296. if (! LV2_IS_PORT_OPTIONAL(fRdfDescriptor->Ports[j].Properties))
  5297. {
  5298. pData->engine->setLastError("Plugin requires a port type that is not currently supported");
  5299. canContinue = false;
  5300. break;
  5301. }
  5302. }
  5303. }
  5304. // Check supported features
  5305. for (uint32_t j=0; j < fRdfDescriptor->FeatureCount && canContinue; ++j)
  5306. {
  5307. const LV2_RDF_Feature& feature(fRdfDescriptor->Features[j]);
  5308. if (std::strcmp(feature.URI, LV2_DATA_ACCESS_URI) == 0 || std::strcmp(feature.URI, LV2_INSTANCE_ACCESS_URI) == 0)
  5309. {
  5310. carla_stderr("Plugin DSP wants UI feature '%s', ignoring this", feature.URI);
  5311. }
  5312. else if (std::strcmp(feature.URI, LV2_BUF_SIZE__fixedBlockLength) == 0)
  5313. {
  5314. fNeedsFixedBuffers = true;
  5315. }
  5316. else if (std::strcmp(feature.URI, LV2_PORT_PROPS__supportsStrictBounds) == 0)
  5317. {
  5318. fStrictBounds = feature.Required ? 1 : 0;
  5319. }
  5320. else if (std::strcmp(feature.URI, LV2_STATE__loadDefaultState) == 0)
  5321. {
  5322. fHasLoadDefaultState = true;
  5323. }
  5324. else if (std::strcmp(feature.URI, LV2_STATE__threadSafeRestore) == 0)
  5325. {
  5326. fHasThreadSafeRestore = true;
  5327. }
  5328. else if (feature.Required && ! is_lv2_feature_supported(feature.URI))
  5329. {
  5330. CarlaString msg("Plugin wants a feature that is not supported:\n");
  5331. msg += feature.URI;
  5332. canContinue = false;
  5333. pData->engine->setLastError(msg);
  5334. break;
  5335. }
  5336. }
  5337. if (! canContinue)
  5338. {
  5339. // error already set
  5340. return false;
  5341. }
  5342. if (fNeedsFixedBuffers && ! pData->engine->usesConstantBufferSize())
  5343. {
  5344. pData->engine->setLastError("Cannot use this plugin under the current engine.\n"
  5345. "The plugin requires a fixed block size which is not possible right now.");
  5346. return false;
  5347. }
  5348. // ---------------------------------------------------------------
  5349. // set icon
  5350. if (std::strncmp(fDescriptor->URI, "http://distrho.sf.net/", 22) == 0)
  5351. pData->iconName = carla_strdup_safe("distrho");
  5352. // ---------------------------------------------------------------
  5353. // set info
  5354. if (name != nullptr && name[0] != '\0')
  5355. pData->name = pData->engine->getUniquePluginName(name);
  5356. else
  5357. pData->name = pData->engine->getUniquePluginName(fRdfDescriptor->Name);
  5358. // ---------------------------------------------------------------
  5359. // register client
  5360. pData->client = pData->engine->addClient(plugin);
  5361. if (pData->client == nullptr || ! pData->client->isOk())
  5362. {
  5363. pData->engine->setLastError("Failed to register plugin client");
  5364. return false;
  5365. }
  5366. // ---------------------------------------------------------------
  5367. // initialize options
  5368. const int bufferSize = static_cast<int>(pData->engine->getBufferSize());
  5369. fLv2Options.minBufferSize = fNeedsFixedBuffers ? bufferSize : 1;
  5370. fLv2Options.maxBufferSize = bufferSize;
  5371. fLv2Options.nominalBufferSize = bufferSize;
  5372. fLv2Options.sampleRate = static_cast<float>(pData->engine->getSampleRate());
  5373. fLv2Options.transientWinId = static_cast<int64_t>(opts.frontendWinId);
  5374. uint32_t eventBufferSize = MAX_DEFAULT_BUFFER_SIZE;
  5375. for (uint32_t j=0; j < fRdfDescriptor->PortCount; ++j)
  5376. {
  5377. const LV2_Property portTypes(fRdfDescriptor->Ports[j].Types);
  5378. if (LV2_IS_PORT_ATOM_SEQUENCE(portTypes) || LV2_IS_PORT_EVENT(portTypes) || LV2_IS_PORT_MIDI_LL(portTypes))
  5379. {
  5380. if (fRdfDescriptor->Ports[j].MinimumSize > eventBufferSize)
  5381. eventBufferSize = fRdfDescriptor->Ports[j].MinimumSize;
  5382. }
  5383. }
  5384. fLv2Options.sequenceSize = static_cast<int>(eventBufferSize);
  5385. fLv2Options.bgColor = opts.bgColor;
  5386. fLv2Options.fgColor = opts.fgColor;
  5387. fLv2Options.uiScale = opts.uiScale;
  5388. // ---------------------------------------------------------------
  5389. // initialize features (part 1)
  5390. LV2_Event_Feature* const eventFt = new LV2_Event_Feature;
  5391. eventFt->callback_data = this;
  5392. eventFt->lv2_event_ref = carla_lv2_event_ref;
  5393. eventFt->lv2_event_unref = carla_lv2_event_unref;
  5394. LV2_Log_Log* const logFt = new LV2_Log_Log;
  5395. logFt->handle = this;
  5396. logFt->printf = carla_lv2_log_printf;
  5397. logFt->vprintf = carla_lv2_log_vprintf;
  5398. LV2_State_Free_Path* const stateFreePathFt = new LV2_State_Free_Path;
  5399. stateFreePathFt->handle = this;
  5400. stateFreePathFt->free_path = carla_lv2_state_free_path;
  5401. LV2_State_Make_Path* const stateMakePathFt = new LV2_State_Make_Path;
  5402. stateMakePathFt->handle = this;
  5403. stateMakePathFt->path = carla_lv2_state_make_path_tmp;
  5404. LV2_State_Map_Path* const stateMapPathFt = new LV2_State_Map_Path;
  5405. stateMapPathFt->handle = this;
  5406. stateMapPathFt->abstract_path = carla_lv2_state_map_to_abstract_path_tmp;
  5407. stateMapPathFt->absolute_path = carla_lv2_state_map_to_absolute_path_tmp;
  5408. LV2_Programs_Host* const programsFt = new LV2_Programs_Host;
  5409. programsFt->handle = this;
  5410. programsFt->program_changed = carla_lv2_program_changed;
  5411. LV2_Resize_Port_Resize* const rsPortFt = new LV2_Resize_Port_Resize;
  5412. rsPortFt->data = this;
  5413. rsPortFt->resize = carla_lv2_resize_port;
  5414. LV2_RtMemPool_Pool* const rtMemPoolFt = new LV2_RtMemPool_Pool;
  5415. lv2_rtmempool_init(rtMemPoolFt);
  5416. LV2_RtMemPool_Pool_Deprecated* const rtMemPoolOldFt = new LV2_RtMemPool_Pool_Deprecated;
  5417. lv2_rtmempool_init_deprecated(rtMemPoolOldFt);
  5418. LV2_URI_Map_Feature* const uriMapFt = new LV2_URI_Map_Feature;
  5419. uriMapFt->callback_data = this;
  5420. uriMapFt->uri_to_id = carla_lv2_uri_to_id;
  5421. LV2_URID_Map* const uridMapFt = new LV2_URID_Map;
  5422. uridMapFt->handle = this;
  5423. uridMapFt->map = carla_lv2_urid_map;
  5424. LV2_URID_Unmap* const uridUnmapFt = new LV2_URID_Unmap;
  5425. uridUnmapFt->handle = this;
  5426. uridUnmapFt->unmap = carla_lv2_urid_unmap;
  5427. LV2_Worker_Schedule* const workerFt = new LV2_Worker_Schedule;
  5428. workerFt->handle = this;
  5429. workerFt->schedule_work = carla_lv2_worker_schedule;
  5430. LV2_Inline_Display* const inlineDisplay = new LV2_Inline_Display;
  5431. inlineDisplay->handle = this;
  5432. inlineDisplay->queue_draw = carla_lv2_inline_display_queue_draw;
  5433. LV2_Midnam* const midnam = new LV2_Midnam;
  5434. midnam->handle = this;
  5435. midnam->update = carla_lv2_midnam_update;
  5436. // ---------------------------------------------------------------
  5437. // initialize features (part 2)
  5438. for (uint32_t j=0; j < kFeatureCountPlugin; ++j)
  5439. fFeatures[j] = new LV2_Feature;
  5440. fFeatures[kFeatureIdBufSizeBounded]->URI = LV2_BUF_SIZE__boundedBlockLength;
  5441. fFeatures[kFeatureIdBufSizeBounded]->data = nullptr;
  5442. fFeatures[kFeatureIdBufSizeFixed]->URI = fNeedsFixedBuffers
  5443. ? LV2_BUF_SIZE__fixedBlockLength
  5444. : LV2_BUF_SIZE__boundedBlockLength;
  5445. fFeatures[kFeatureIdBufSizeFixed]->data = nullptr;
  5446. fFeatures[kFeatureIdBufSizePowerOf2]->URI = LV2_BUF_SIZE__powerOf2BlockLength;
  5447. fFeatures[kFeatureIdBufSizePowerOf2]->data = nullptr;
  5448. fFeatures[kFeatureIdEvent]->URI = LV2_EVENT_URI;
  5449. fFeatures[kFeatureIdEvent]->data = eventFt;
  5450. fFeatures[kFeatureIdHardRtCapable]->URI = LV2_CORE__hardRTCapable;
  5451. fFeatures[kFeatureIdHardRtCapable]->data = nullptr;
  5452. fFeatures[kFeatureIdInPlaceBroken]->URI = LV2_CORE__inPlaceBroken;
  5453. fFeatures[kFeatureIdInPlaceBroken]->data = nullptr;
  5454. fFeatures[kFeatureIdIsLive]->URI = LV2_CORE__isLive;
  5455. fFeatures[kFeatureIdIsLive]->data = nullptr;
  5456. fFeatures[kFeatureIdLogs]->URI = LV2_LOG__log;
  5457. fFeatures[kFeatureIdLogs]->data = logFt;
  5458. fFeatures[kFeatureIdOptions]->URI = LV2_OPTIONS__options;
  5459. fFeatures[kFeatureIdOptions]->data = fLv2Options.opts;
  5460. fFeatures[kFeatureIdPrograms]->URI = LV2_PROGRAMS__Host;
  5461. fFeatures[kFeatureIdPrograms]->data = programsFt;
  5462. fFeatures[kFeatureIdResizePort]->URI = LV2_RESIZE_PORT__resize;
  5463. fFeatures[kFeatureIdResizePort]->data = rsPortFt;
  5464. fFeatures[kFeatureIdRtMemPool]->URI = LV2_RTSAFE_MEMORY_POOL__Pool;
  5465. fFeatures[kFeatureIdRtMemPool]->data = rtMemPoolFt;
  5466. fFeatures[kFeatureIdRtMemPoolOld]->URI = LV2_RTSAFE_MEMORY_POOL_DEPRECATED_URI;
  5467. fFeatures[kFeatureIdRtMemPoolOld]->data = rtMemPoolOldFt;
  5468. fFeatures[kFeatureIdStateFreePath]->URI = LV2_STATE__freePath;
  5469. fFeatures[kFeatureIdStateFreePath]->data = stateFreePathFt;
  5470. fFeatures[kFeatureIdStateMakePath]->URI = LV2_STATE__makePath;
  5471. fFeatures[kFeatureIdStateMakePath]->data = stateMakePathFt;
  5472. fFeatures[kFeatureIdStateMapPath]->URI = LV2_STATE__mapPath;
  5473. fFeatures[kFeatureIdStateMapPath]->data = stateMapPathFt;
  5474. fFeatures[kFeatureIdStrictBounds]->URI = LV2_PORT_PROPS__supportsStrictBounds;
  5475. fFeatures[kFeatureIdStrictBounds]->data = nullptr;
  5476. fFeatures[kFeatureIdUriMap]->URI = LV2_URI_MAP_URI;
  5477. fFeatures[kFeatureIdUriMap]->data = uriMapFt;
  5478. fFeatures[kFeatureIdUridMap]->URI = LV2_URID__map;
  5479. fFeatures[kFeatureIdUridMap]->data = uridMapFt;
  5480. fFeatures[kFeatureIdUridUnmap]->URI = LV2_URID__unmap;
  5481. fFeatures[kFeatureIdUridUnmap]->data = uridUnmapFt;
  5482. fFeatures[kFeatureIdWorker]->URI = LV2_WORKER__schedule;
  5483. fFeatures[kFeatureIdWorker]->data = workerFt;
  5484. fFeatures[kFeatureIdInlineDisplay]->URI = LV2_INLINEDISPLAY__queue_draw;
  5485. fFeatures[kFeatureIdInlineDisplay]->data = inlineDisplay;
  5486. fFeatures[kFeatureIdMidnam]->URI = LV2_MIDNAM__update;
  5487. fFeatures[kFeatureIdMidnam]->data = midnam;
  5488. // ---------------------------------------------------------------
  5489. // initialize features (part 3)
  5490. LV2_State_Make_Path* const stateMakePathFt2 = new LV2_State_Make_Path;
  5491. stateMakePathFt2->handle = this;
  5492. stateMakePathFt2->path = carla_lv2_state_make_path_real;
  5493. LV2_State_Map_Path* const stateMapPathFt2 = new LV2_State_Map_Path;
  5494. stateMapPathFt2->handle = this;
  5495. stateMapPathFt2->abstract_path = carla_lv2_state_map_to_abstract_path_real;
  5496. stateMapPathFt2->absolute_path = carla_lv2_state_map_to_absolute_path_real;
  5497. for (uint32_t j=0; j < kStateFeatureCountAll; ++j)
  5498. fStateFeatures[j] = new LV2_Feature;
  5499. fStateFeatures[kStateFeatureIdFreePath]->URI = LV2_STATE__freePath;
  5500. fStateFeatures[kStateFeatureIdFreePath]->data = stateFreePathFt;
  5501. fStateFeatures[kStateFeatureIdMakePath]->URI = LV2_STATE__makePath;
  5502. fStateFeatures[kStateFeatureIdMakePath]->data = stateMakePathFt2;
  5503. fStateFeatures[kStateFeatureIdMapPath]->URI = LV2_STATE__mapPath;
  5504. fStateFeatures[kStateFeatureIdMapPath]->data = stateMapPathFt2;
  5505. fStateFeatures[kStateFeatureIdWorker]->URI = LV2_WORKER__schedule;
  5506. fStateFeatures[kStateFeatureIdWorker]->data = workerFt;
  5507. // ---------------------------------------------------------------
  5508. // initialize plugin
  5509. try {
  5510. fHandle = fDescriptor->instantiate(fDescriptor, pData->engine->getSampleRate(), fRdfDescriptor->Bundle, fFeatures);
  5511. } catch(...) {}
  5512. if (fHandle == nullptr)
  5513. {
  5514. pData->engine->setLastError("Plugin failed to initialize");
  5515. return false;
  5516. }
  5517. recheckExtensions();
  5518. // ---------------------------------------------------------------
  5519. // set options
  5520. pData->options = 0x0;
  5521. if (fLatencyIndex >= 0 || getMidiOutCount() != 0 || fNeedsFixedBuffers)
  5522. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  5523. else if (options & PLUGIN_OPTION_FIXED_BUFFERS)
  5524. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  5525. if (opts.forceStereo)
  5526. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  5527. else if (options & PLUGIN_OPTION_FORCE_STEREO)
  5528. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  5529. if (getMidiInCount() != 0)
  5530. {
  5531. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CONTROL_CHANGES))
  5532. pData->options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  5533. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CHANNEL_PRESSURE))
  5534. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  5535. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH))
  5536. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  5537. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PITCHBEND))
  5538. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  5539. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_ALL_SOUND_OFF))
  5540. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  5541. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PROGRAM_CHANGES))
  5542. pData->options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  5543. if (isPluginOptionInverseEnabled(options, PLUGIN_OPTION_SKIP_SENDING_NOTES))
  5544. pData->options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  5545. }
  5546. if (fExt.programs != nullptr && (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) == 0)
  5547. {
  5548. if (isPluginOptionEnabled(options, PLUGIN_OPTION_MAP_PROGRAM_CHANGES))
  5549. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  5550. }
  5551. // ---------------------------------------------------------------
  5552. // gui stuff
  5553. if (fRdfDescriptor->UICount != 0)
  5554. initUi();
  5555. return true;
  5556. // might be unused
  5557. (void)needsArchBridge;
  5558. }
  5559. // -------------------------------------------------------------------
  5560. void initUi()
  5561. {
  5562. // ---------------------------------------------------------------
  5563. // find the most appropriate ui
  5564. int eQt4, eQt5, eGtk2, eGtk3, eCocoa, eWindows, eX11, eMod, iCocoa, iWindows, iX11, iExt, iFinal;
  5565. eQt4 = eQt5 = eGtk2 = eGtk3 = eCocoa = eWindows = eX11 = eMod = iCocoa = iWindows = iX11 = iExt = iFinal = -1;
  5566. #if defined(LV2_UIS_ONLY_BRIDGES)
  5567. const bool preferUiBridges = true;
  5568. #elif defined(BUILD_BRIDGE)
  5569. const bool preferUiBridges = false;
  5570. #else
  5571. const bool preferUiBridges = pData->engine->getOptions().preferUiBridges;
  5572. #endif
  5573. bool hasShowInterface = false;
  5574. for (uint32_t i=0; i < fRdfDescriptor->UICount; ++i)
  5575. {
  5576. CARLA_SAFE_ASSERT_CONTINUE(fRdfDescriptor->UIs[i].URI != nullptr);
  5577. const int ii(static_cast<int>(i));
  5578. switch (fRdfDescriptor->UIs[i].Type)
  5579. {
  5580. case LV2_UI_QT4:
  5581. if (isUiBridgeable(i))
  5582. eQt4 = ii;
  5583. break;
  5584. case LV2_UI_QT5:
  5585. if (isUiBridgeable(i))
  5586. eQt5 = ii;
  5587. break;
  5588. case LV2_UI_GTK2:
  5589. if (isUiBridgeable(i))
  5590. eGtk2 = ii;
  5591. break;
  5592. case LV2_UI_GTK3:
  5593. if (isUiBridgeable(i))
  5594. eGtk3 = ii;
  5595. break;
  5596. #ifdef CARLA_OS_MAC
  5597. case LV2_UI_COCOA:
  5598. if (isUiBridgeable(i) && preferUiBridges)
  5599. eCocoa = ii;
  5600. iCocoa = ii;
  5601. break;
  5602. #endif
  5603. #ifdef CARLA_OS_WIN
  5604. case LV2_UI_WINDOWS:
  5605. if (isUiBridgeable(i) && preferUiBridges)
  5606. eWindows = ii;
  5607. iWindows = ii;
  5608. break;
  5609. #endif
  5610. case LV2_UI_X11:
  5611. if (isUiBridgeable(i) && preferUiBridges)
  5612. eX11 = ii;
  5613. iX11 = ii;
  5614. break;
  5615. case LV2_UI_EXTERNAL:
  5616. case LV2_UI_OLD_EXTERNAL:
  5617. iExt = ii;
  5618. break;
  5619. case LV2_UI_MOD:
  5620. eMod = ii;
  5621. break;
  5622. default:
  5623. break;
  5624. }
  5625. }
  5626. /**/ if (eQt4 >= 0)
  5627. iFinal = eQt4;
  5628. else if (eQt5 >= 0)
  5629. iFinal = eQt5;
  5630. else if (eGtk2 >= 0)
  5631. iFinal = eGtk2;
  5632. else if (eGtk3 >= 0)
  5633. iFinal = eGtk3;
  5634. #ifdef CARLA_OS_MAC
  5635. else if (eCocoa >= 0)
  5636. iFinal = eCocoa;
  5637. #endif
  5638. #ifdef CARLA_OS_WIN
  5639. else if (eWindows >= 0)
  5640. iFinal = eWindows;
  5641. #endif
  5642. #ifdef HAVE_X11
  5643. else if (eX11 >= 0)
  5644. iFinal = eX11;
  5645. #endif
  5646. #ifndef LV2_UIS_ONLY_BRIDGES
  5647. # ifdef CARLA_OS_MAC
  5648. else if (iCocoa >= 0)
  5649. iFinal = iCocoa;
  5650. # endif
  5651. # ifdef CARLA_OS_WIN
  5652. else if (iWindows >= 0)
  5653. iFinal = iWindows;
  5654. # endif
  5655. # ifdef HAVE_X11
  5656. else if (iX11 >= 0)
  5657. iFinal = iX11;
  5658. # endif
  5659. #endif
  5660. else if (iExt >= 0)
  5661. iFinal = iExt;
  5662. #ifndef BUILD_BRIDGE
  5663. if (iFinal < 0)
  5664. #endif
  5665. {
  5666. // no suitable UI found, see if there's one which supports ui:showInterface
  5667. for (uint32_t i=0; i < fRdfDescriptor->UICount && ! hasShowInterface; ++i)
  5668. {
  5669. LV2_RDF_UI* const ui(&fRdfDescriptor->UIs[i]);
  5670. for (uint32_t j=0; j < ui->ExtensionCount; ++j)
  5671. {
  5672. CARLA_SAFE_ASSERT_CONTINUE(ui->Extensions[j] != nullptr);
  5673. if (std::strcmp(ui->Extensions[j], LV2_UI__showInterface) != 0)
  5674. continue;
  5675. iFinal = static_cast<int>(i);
  5676. hasShowInterface = true;
  5677. break;
  5678. }
  5679. }
  5680. if (iFinal < 0)
  5681. {
  5682. if (eMod < 0)
  5683. {
  5684. carla_stderr("Failed to find an appropriate LV2 UI for this plugin");
  5685. return;
  5686. }
  5687. // use MODGUI as last resort
  5688. iFinal = eMod;
  5689. }
  5690. }
  5691. fUI.rdfDescriptor = &fRdfDescriptor->UIs[iFinal];
  5692. // ---------------------------------------------------------------
  5693. // check supported ui features
  5694. bool canContinue = true;
  5695. bool canDelete = true;
  5696. for (uint32_t i=0; i < fUI.rdfDescriptor->FeatureCount; ++i)
  5697. {
  5698. const char* const uri(fUI.rdfDescriptor->Features[i].URI);
  5699. CARLA_SAFE_ASSERT_CONTINUE(uri != nullptr && uri[0] != '\0');
  5700. if (! is_lv2_ui_feature_supported(uri))
  5701. {
  5702. if (fUI.rdfDescriptor->Features[i].Required)
  5703. {
  5704. carla_stderr("Plugin UI requires a feature that is not supported:\n%s", uri);
  5705. canContinue = false;
  5706. break;
  5707. }
  5708. carla_stderr("Plugin UI wants a feature that is not supported (ignored):\n%s", uri);
  5709. }
  5710. if (std::strcmp(uri, LV2_UI__makeResident) == 0 || std::strcmp(uri, LV2_UI__makeSONameResident) == 0)
  5711. canDelete = false;
  5712. else if (std::strcmp(uri, LV2_UI__requestValue) == 0)
  5713. pData->hints |= PLUGIN_NEEDS_UI_MAIN_THREAD;
  5714. }
  5715. if (! canContinue)
  5716. {
  5717. fUI.rdfDescriptor = nullptr;
  5718. return;
  5719. }
  5720. // ---------------------------------------------------------------
  5721. // initialize ui according to type
  5722. const LV2_Property uiType(fUI.rdfDescriptor->Type);
  5723. if (
  5724. (iFinal == eQt4 ||
  5725. iFinal == eQt5 ||
  5726. iFinal == eGtk2 ||
  5727. iFinal == eGtk3 ||
  5728. iFinal == eCocoa ||
  5729. iFinal == eWindows ||
  5730. iFinal == eX11 ||
  5731. iFinal == eMod)
  5732. #ifdef BUILD_BRIDGE
  5733. && ! hasShowInterface
  5734. #endif
  5735. )
  5736. {
  5737. // -----------------------------------------------------------
  5738. // initialize ui-bridge
  5739. if (const char* const bridgeBinary = getUiBridgeBinary(uiType))
  5740. {
  5741. carla_stdout("Will use UI-Bridge for '%s', binary: \"%s\"", pData->name, bridgeBinary);
  5742. CarlaString uiTitle;
  5743. if (pData->uiTitle.isNotEmpty())
  5744. {
  5745. uiTitle = pData->uiTitle;
  5746. }
  5747. else
  5748. {
  5749. uiTitle = pData->name;
  5750. uiTitle += " (GUI)";
  5751. }
  5752. fLv2Options.windowTitle = uiTitle.releaseBufferPointer();
  5753. fUI.type = UI::TYPE_BRIDGE;
  5754. fPipeServer.setData(bridgeBinary, fRdfDescriptor->URI, fUI.rdfDescriptor->URI);
  5755. delete[] bridgeBinary;
  5756. return;
  5757. }
  5758. if (iFinal == eQt4 || iFinal == eQt5 || iFinal == eGtk2 || iFinal == eGtk3 || iFinal == eMod)
  5759. {
  5760. carla_stderr2("Failed to find UI bridge binary for '%s', cannot use UI", pData->name);
  5761. fUI.rdfDescriptor = nullptr;
  5762. return;
  5763. }
  5764. }
  5765. #ifdef LV2_UIS_ONLY_BRIDGES
  5766. carla_stderr2("Failed to get an UI working, canBridge:%s", bool2str(isUiBridgeable(static_cast<uint32_t>(iFinal))));
  5767. fUI.rdfDescriptor = nullptr;
  5768. return;
  5769. #endif
  5770. // ---------------------------------------------------------------
  5771. // open UI DLL
  5772. #ifdef CARLA_OS_MAC
  5773. // Binary might be in quarentine due to Apple stupid notarization rules, let's remove that if possible
  5774. removeFileFromQuarantine(fUI.rdfDescriptor->Binary);
  5775. #endif
  5776. if (! pData->uiLibOpen(fUI.rdfDescriptor->Binary, canDelete))
  5777. {
  5778. carla_stderr2("Could not load UI library, error was:\n%s", pData->libError(fUI.rdfDescriptor->Binary));
  5779. fUI.rdfDescriptor = nullptr;
  5780. return;
  5781. }
  5782. // ---------------------------------------------------------------
  5783. // get UI DLL main entry
  5784. LV2UI_DescriptorFunction uiDescFn = pData->uiLibSymbol<LV2UI_DescriptorFunction>("lv2ui_descriptor");
  5785. if (uiDescFn == nullptr)
  5786. {
  5787. carla_stderr2("Could not find the LV2UI Descriptor in the UI library");
  5788. pData->uiLibClose();
  5789. fUI.rdfDescriptor = nullptr;
  5790. return;
  5791. }
  5792. // ---------------------------------------------------------------
  5793. // get UI descriptor that matches UI URI
  5794. uint32_t i = 0;
  5795. while ((fUI.descriptor = uiDescFn(i++)))
  5796. {
  5797. if (std::strcmp(fUI.descriptor->URI, fUI.rdfDescriptor->URI) == 0)
  5798. break;
  5799. }
  5800. if (fUI.descriptor == nullptr)
  5801. {
  5802. carla_stderr2("Could not find the requested GUI in the plugin UI library");
  5803. pData->uiLibClose();
  5804. fUI.rdfDescriptor = nullptr;
  5805. return;
  5806. }
  5807. // ---------------------------------------------------------------
  5808. // check if ui is usable
  5809. switch (uiType)
  5810. {
  5811. case LV2_UI_NONE:
  5812. carla_stdout("Will use LV2 Show Interface for '%s'", pData->name);
  5813. fUI.type = UI::TYPE_EMBED;
  5814. break;
  5815. case LV2_UI_QT4:
  5816. carla_stdout("Will use LV2 Qt4 UI for '%s', NOT!", pData->name);
  5817. fUI.type = UI::TYPE_EMBED;
  5818. break;
  5819. case LV2_UI_QT5:
  5820. carla_stdout("Will use LV2 Qt5 UI for '%s', NOT!", pData->name);
  5821. fUI.type = UI::TYPE_EMBED;
  5822. break;
  5823. case LV2_UI_GTK2:
  5824. carla_stdout("Will use LV2 Gtk2 UI for '%s', NOT!", pData->name);
  5825. fUI.type = UI::TYPE_EMBED;
  5826. break;
  5827. case LV2_UI_GTK3:
  5828. carla_stdout("Will use LV2 Gtk3 UI for '%s', NOT!", pData->name);
  5829. fUI.type = UI::TYPE_EMBED;
  5830. break;
  5831. #ifdef CARLA_OS_MAC
  5832. case LV2_UI_COCOA:
  5833. carla_stdout("Will use LV2 Cocoa UI for '%s'", pData->name);
  5834. fUI.type = UI::TYPE_EMBED;
  5835. break;
  5836. #endif
  5837. #ifdef CARLA_OS_WIN
  5838. case LV2_UI_WINDOWS:
  5839. carla_stdout("Will use LV2 Windows UI for '%s'", pData->name);
  5840. fUI.type = UI::TYPE_EMBED;
  5841. break;
  5842. #endif
  5843. case LV2_UI_X11:
  5844. #ifdef HAVE_X11
  5845. carla_stdout("Will use LV2 X11 UI for '%s'", pData->name);
  5846. #else
  5847. carla_stdout("Will use LV2 X11 UI for '%s', NOT!", pData->name);
  5848. #endif
  5849. fUI.type = UI::TYPE_EMBED;
  5850. break;
  5851. case LV2_UI_EXTERNAL:
  5852. case LV2_UI_OLD_EXTERNAL:
  5853. carla_stdout("Will use LV2 External UI for '%s'", pData->name);
  5854. fUI.type = UI::TYPE_EXTERNAL;
  5855. break;
  5856. }
  5857. if (fUI.type == UI::TYPE_NULL)
  5858. {
  5859. pData->uiLibClose();
  5860. fUI.descriptor = nullptr;
  5861. fUI.rdfDescriptor = nullptr;
  5862. return;
  5863. }
  5864. // ---------------------------------------------------------------
  5865. // initialize ui data
  5866. {
  5867. CarlaString uiTitle;
  5868. if (pData->uiTitle.isNotEmpty())
  5869. {
  5870. uiTitle = pData->uiTitle;
  5871. }
  5872. else
  5873. {
  5874. uiTitle = pData->name;
  5875. uiTitle += " (GUI)";
  5876. }
  5877. fLv2Options.windowTitle = uiTitle.releaseBufferPointer();
  5878. }
  5879. fLv2Options.opts[CarlaPluginLV2Options::WindowTitle].size = (uint32_t)std::strlen(fLv2Options.windowTitle);
  5880. fLv2Options.opts[CarlaPluginLV2Options::WindowTitle].value = fLv2Options.windowTitle;
  5881. // ---------------------------------------------------------------
  5882. // initialize ui features (part 1)
  5883. LV2_Extension_Data_Feature* const uiDataFt = new LV2_Extension_Data_Feature;
  5884. uiDataFt->data_access = fDescriptor->extension_data;
  5885. LV2UI_Port_Map* const uiPortMapFt = new LV2UI_Port_Map;
  5886. uiPortMapFt->handle = this;
  5887. uiPortMapFt->port_index = carla_lv2_ui_port_map;
  5888. LV2UI_Request_Value* const uiRequestValueFt = new LV2UI_Request_Value;
  5889. uiRequestValueFt->handle = this;
  5890. uiRequestValueFt->request = carla_lv2_ui_request_value;
  5891. LV2UI_Resize* const uiResizeFt = new LV2UI_Resize;
  5892. uiResizeFt->handle = this;
  5893. uiResizeFt->ui_resize = carla_lv2_ui_resize;
  5894. LV2UI_Touch* const uiTouchFt = new LV2UI_Touch;
  5895. uiTouchFt->handle = this;
  5896. uiTouchFt->touch = carla_lv2_ui_touch;
  5897. LV2_External_UI_Host* const uiExternalHostFt = new LV2_External_UI_Host;
  5898. uiExternalHostFt->ui_closed = carla_lv2_external_ui_closed;
  5899. uiExternalHostFt->plugin_human_id = fLv2Options.windowTitle;
  5900. // ---------------------------------------------------------------
  5901. // initialize ui features (part 2)
  5902. for (uint32_t j=kFeatureCountPlugin; j < kFeatureCountAll; ++j)
  5903. fFeatures[j] = new LV2_Feature;
  5904. fFeatures[kFeatureIdUiDataAccess]->URI = LV2_DATA_ACCESS_URI;
  5905. fFeatures[kFeatureIdUiDataAccess]->data = uiDataFt;
  5906. fFeatures[kFeatureIdUiInstanceAccess]->URI = LV2_INSTANCE_ACCESS_URI;
  5907. fFeatures[kFeatureIdUiInstanceAccess]->data = fHandle;
  5908. fFeatures[kFeatureIdUiIdleInterface]->URI = LV2_UI__idleInterface;
  5909. fFeatures[kFeatureIdUiIdleInterface]->data = nullptr;
  5910. fFeatures[kFeatureIdUiFixedSize]->URI = LV2_UI__fixedSize;
  5911. fFeatures[kFeatureIdUiFixedSize]->data = nullptr;
  5912. fFeatures[kFeatureIdUiMakeResident]->URI = LV2_UI__makeResident;
  5913. fFeatures[kFeatureIdUiMakeResident]->data = nullptr;
  5914. fFeatures[kFeatureIdUiMakeResident2]->URI = LV2_UI__makeSONameResident;
  5915. fFeatures[kFeatureIdUiMakeResident2]->data = nullptr;
  5916. fFeatures[kFeatureIdUiNoUserResize]->URI = LV2_UI__noUserResize;
  5917. fFeatures[kFeatureIdUiNoUserResize]->data = nullptr;
  5918. fFeatures[kFeatureIdUiParent]->URI = LV2_UI__parent;
  5919. fFeatures[kFeatureIdUiParent]->data = nullptr;
  5920. fFeatures[kFeatureIdUiPortMap]->URI = LV2_UI__portMap;
  5921. fFeatures[kFeatureIdUiPortMap]->data = uiPortMapFt;
  5922. fFeatures[kFeatureIdUiPortSubscribe]->URI = LV2_UI__portSubscribe;
  5923. fFeatures[kFeatureIdUiPortSubscribe]->data = nullptr;
  5924. fFeatures[kFeatureIdUiRequestValue]->URI = LV2_UI__requestValue;
  5925. fFeatures[kFeatureIdUiRequestValue]->data = uiRequestValueFt;
  5926. fFeatures[kFeatureIdUiResize]->URI = LV2_UI__resize;
  5927. fFeatures[kFeatureIdUiResize]->data = uiResizeFt;
  5928. fFeatures[kFeatureIdUiTouch]->URI = LV2_UI__touch;
  5929. fFeatures[kFeatureIdUiTouch]->data = uiTouchFt;
  5930. fFeatures[kFeatureIdExternalUi]->URI = LV2_EXTERNAL_UI__Host;
  5931. fFeatures[kFeatureIdExternalUi]->data = uiExternalHostFt;
  5932. fFeatures[kFeatureIdExternalUiOld]->URI = LV2_EXTERNAL_UI_DEPRECATED_URI;
  5933. fFeatures[kFeatureIdExternalUiOld]->data = uiExternalHostFt;
  5934. // ---------------------------------------------------------------
  5935. // initialize ui extensions
  5936. if (fUI.descriptor->extension_data == nullptr)
  5937. return;
  5938. fExt.uiidle = (const LV2UI_Idle_Interface*)fUI.descriptor->extension_data(LV2_UI__idleInterface);
  5939. fExt.uishow = (const LV2UI_Show_Interface*)fUI.descriptor->extension_data(LV2_UI__showInterface);
  5940. fExt.uiresize = (const LV2UI_Resize*)fUI.descriptor->extension_data(LV2_UI__resize);
  5941. fExt.uiprograms = (const LV2_Programs_UI_Interface*)fUI.descriptor->extension_data(LV2_PROGRAMS__UIInterface);
  5942. // check if invalid
  5943. if (fExt.uiidle != nullptr && fExt.uiidle->idle == nullptr)
  5944. fExt.uiidle = nullptr;
  5945. if (fExt.uishow != nullptr && (fExt.uishow->show == nullptr || fExt.uishow->hide == nullptr))
  5946. fExt.uishow = nullptr;
  5947. if (fExt.uiresize != nullptr && fExt.uiresize->ui_resize == nullptr)
  5948. fExt.uiresize = nullptr;
  5949. if (fExt.uiprograms != nullptr && fExt.uiprograms->select_program == nullptr)
  5950. fExt.uiprograms = nullptr;
  5951. // don't use uiidle if external
  5952. if (fUI.type == UI::TYPE_EXTERNAL)
  5953. fExt.uiidle = nullptr;
  5954. }
  5955. // -------------------------------------------------------------------
  5956. void handleTransferAtom(const uint32_t portIndex, const LV2_Atom* const atom)
  5957. {
  5958. CARLA_SAFE_ASSERT_RETURN(atom != nullptr,);
  5959. carla_debug("CarlaPluginLV2::handleTransferAtom(%i, %p)", portIndex, atom);
  5960. fAtomBufferEvIn.put(atom, portIndex);
  5961. }
  5962. void handleUridMap(const LV2_URID urid, const char* const uri)
  5963. {
  5964. CARLA_SAFE_ASSERT_RETURN(urid != kUridNull,);
  5965. CARLA_SAFE_ASSERT_RETURN(uri != nullptr && uri[0] != '\0',);
  5966. carla_debug("CarlaPluginLV2::handleUridMap(%i v " P_SIZE ", \"%s\")", urid, fCustomURIDs.size()-1, uri);
  5967. const std::size_t uriCount(fCustomURIDs.size());
  5968. if (urid < uriCount)
  5969. {
  5970. const char* const ourURI(carla_lv2_urid_unmap(this, urid));
  5971. CARLA_SAFE_ASSERT_RETURN(ourURI != nullptr && ourURI != kUnmapFallback,);
  5972. if (std::strcmp(ourURI, uri) != 0)
  5973. {
  5974. carla_stderr2("PLUGIN :: wrong URI '%s' vs '%s'", ourURI, uri);
  5975. }
  5976. }
  5977. else
  5978. {
  5979. CARLA_SAFE_ASSERT_RETURN(urid == uriCount,);
  5980. fCustomURIDs.push_back(uri);
  5981. }
  5982. }
  5983. // -------------------------------------------------------------------
  5984. void writeAtomPath(const char* const path, const LV2_URID urid)
  5985. {
  5986. uint8_t atomBuf[4096];
  5987. LV2_Atom_Forge atomForge;
  5988. initAtomForge(atomForge);
  5989. lv2_atom_forge_set_buffer(&atomForge, atomBuf, sizeof(atomBuf));
  5990. LV2_Atom_Forge_Frame forgeFrame;
  5991. lv2_atom_forge_object(&atomForge, &forgeFrame, kUridNull, kUridPatchSet);
  5992. lv2_atom_forge_key(&atomForge, kUridCarlaParameterChange);
  5993. lv2_atom_forge_bool(&atomForge, true);
  5994. lv2_atom_forge_key(&atomForge, kUridPatchProperty);
  5995. lv2_atom_forge_urid(&atomForge, urid);
  5996. lv2_atom_forge_key(&atomForge, kUridPatchValue);
  5997. lv2_atom_forge_path(&atomForge, path, static_cast<uint32_t>(std::strlen(path))+1);
  5998. lv2_atom_forge_pop(&atomForge, &forgeFrame);
  5999. LV2_Atom* const atom((LV2_Atom*)atomBuf);
  6000. CARLA_SAFE_ASSERT(atom->size < sizeof(atomBuf));
  6001. fAtomBufferEvIn.put(atom, fEventsIn.ctrlIndex);
  6002. }
  6003. // -------------------------------------------------------------------
  6004. private:
  6005. LV2_Handle fHandle;
  6006. LV2_Handle fHandle2;
  6007. LV2_Feature* fFeatures[kFeatureCountAll+1];
  6008. LV2_Feature* fStateFeatures[kStateFeatureCountAll+1];
  6009. const LV2_Descriptor* fDescriptor;
  6010. const LV2_RDF_Descriptor* fRdfDescriptor;
  6011. float** fAudioInBuffers;
  6012. float** fAudioOutBuffers;
  6013. float** fCvInBuffers;
  6014. float** fCvOutBuffers;
  6015. float* fParamBuffers;
  6016. bool fHasLoadDefaultState : 1;
  6017. bool fHasThreadSafeRestore : 1;
  6018. bool fNeedsFixedBuffers : 1;
  6019. bool fNeedsUiClose : 1;
  6020. bool fInlineDisplayNeedsRedraw : 1;
  6021. int64_t fInlineDisplayLastRedrawTime;
  6022. int32_t fLatencyIndex; // -1 if invalid
  6023. int fStrictBounds; // -1 unsupported, 0 optional, 1 required
  6024. Lv2AtomRingBuffer fAtomBufferEvIn;
  6025. Lv2AtomRingBuffer fAtomBufferUiOut;
  6026. Lv2AtomRingBuffer fAtomBufferWorkerIn;
  6027. Lv2AtomRingBuffer fAtomBufferWorkerResp;
  6028. uint8_t* fAtomBufferUiOutTmpData;
  6029. uint8_t* fAtomBufferWorkerInTmpData;
  6030. CarlaPluginLV2EventData fEventsIn;
  6031. CarlaPluginLV2EventData fEventsOut;
  6032. CarlaPluginLV2Options fLv2Options;
  6033. CarlaPipeServerLV2 fPipeServer;
  6034. std::vector<std::string> fCustomURIDs;
  6035. bool fFirstActive; // first process() call after activate()
  6036. void* fLastStateChunk;
  6037. EngineTimeInfo fLastTimeInfo;
  6038. // if plugin provides path parameter, use it as fake "gui"
  6039. CarlaString fFilePathURI;
  6040. struct Extensions {
  6041. const LV2_Options_Interface* options;
  6042. const LV2_State_Interface* state;
  6043. const LV2_Worker_Interface* worker;
  6044. const LV2_Inline_Display_Interface* inlineDisplay;
  6045. const LV2_Midnam_Interface* midnam;
  6046. const LV2_Programs_Interface* programs;
  6047. const LV2UI_Idle_Interface* uiidle;
  6048. const LV2UI_Show_Interface* uishow;
  6049. const LV2UI_Resize* uiresize;
  6050. const LV2_Programs_UI_Interface* uiprograms;
  6051. Extensions()
  6052. : options(nullptr),
  6053. state(nullptr),
  6054. worker(nullptr),
  6055. inlineDisplay(nullptr),
  6056. midnam(nullptr),
  6057. programs(nullptr),
  6058. uiidle(nullptr),
  6059. uishow(nullptr),
  6060. uiresize(nullptr),
  6061. uiprograms(nullptr) {}
  6062. CARLA_DECLARE_NON_COPY_STRUCT(Extensions);
  6063. } fExt;
  6064. struct UI {
  6065. enum Type {
  6066. TYPE_NULL = 0,
  6067. TYPE_BRIDGE,
  6068. TYPE_EMBED,
  6069. TYPE_EXTERNAL
  6070. };
  6071. Type type;
  6072. LV2UI_Handle handle;
  6073. LV2UI_Widget widget;
  6074. const LV2UI_Descriptor* descriptor;
  6075. const LV2_RDF_UI* rdfDescriptor;
  6076. bool embedded;
  6077. bool fileBrowserOpen;
  6078. const char* fileNeededForURI;
  6079. CarlaPluginUI* window;
  6080. UI()
  6081. : type(TYPE_NULL),
  6082. handle(nullptr),
  6083. widget(nullptr),
  6084. descriptor(nullptr),
  6085. rdfDescriptor(nullptr),
  6086. embedded(false),
  6087. fileBrowserOpen(false),
  6088. fileNeededForURI(nullptr),
  6089. window(nullptr) {}
  6090. ~UI()
  6091. {
  6092. CARLA_SAFE_ASSERT(handle == nullptr);
  6093. CARLA_SAFE_ASSERT(widget == nullptr);
  6094. CARLA_SAFE_ASSERT(descriptor == nullptr);
  6095. CARLA_SAFE_ASSERT(rdfDescriptor == nullptr);
  6096. CARLA_SAFE_ASSERT(! fileBrowserOpen);
  6097. CARLA_SAFE_ASSERT(fileNeededForURI == nullptr);
  6098. CARLA_SAFE_ASSERT(window == nullptr);
  6099. }
  6100. CARLA_DECLARE_NON_COPY_STRUCT(UI);
  6101. } fUI;
  6102. // -------------------------------------------------------------------
  6103. // Event Feature
  6104. static uint32_t carla_lv2_event_ref(LV2_Event_Callback_Data callback_data, LV2_Event* event)
  6105. {
  6106. CARLA_SAFE_ASSERT_RETURN(callback_data != nullptr, 0);
  6107. CARLA_SAFE_ASSERT_RETURN(event != nullptr, 0);
  6108. carla_debug("carla_lv2_event_ref(%p, %p)", callback_data, event);
  6109. return 0;
  6110. }
  6111. static uint32_t carla_lv2_event_unref(LV2_Event_Callback_Data callback_data, LV2_Event* event)
  6112. {
  6113. CARLA_SAFE_ASSERT_RETURN(callback_data != nullptr, 0);
  6114. CARLA_SAFE_ASSERT_RETURN(event != nullptr, 0);
  6115. carla_debug("carla_lv2_event_unref(%p, %p)", callback_data, event);
  6116. return 0;
  6117. }
  6118. // -------------------------------------------------------------------
  6119. // Logs Feature
  6120. static int carla_lv2_log_printf(LV2_Log_Handle handle, LV2_URID type, const char* fmt, ...)
  6121. {
  6122. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, 0);
  6123. CARLA_SAFE_ASSERT_RETURN(type != kUridNull, 0);
  6124. CARLA_SAFE_ASSERT_RETURN(fmt != nullptr, 0);
  6125. #ifndef DEBUG
  6126. if (type == kUridLogTrace)
  6127. return 0;
  6128. #endif
  6129. va_list args;
  6130. va_start(args, fmt);
  6131. const int ret(carla_lv2_log_vprintf(handle, type, fmt, args));
  6132. va_end(args);
  6133. return ret;
  6134. }
  6135. static int carla_lv2_log_vprintf(LV2_Log_Handle handle, LV2_URID type, const char* fmt, va_list ap)
  6136. {
  6137. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, 0);
  6138. CARLA_SAFE_ASSERT_RETURN(type != kUridNull, 0);
  6139. CARLA_SAFE_ASSERT_RETURN(fmt != nullptr, 0);
  6140. int ret = 0;
  6141. switch (type)
  6142. {
  6143. case kUridLogError:
  6144. std::fprintf(stderr, "\x1b[31m");
  6145. ret = std::vfprintf(stderr, fmt, ap);
  6146. std::fprintf(stderr, "\x1b[0m");
  6147. break;
  6148. case kUridLogNote:
  6149. ret = std::vfprintf(stdout, fmt, ap);
  6150. break;
  6151. case kUridLogTrace:
  6152. #ifdef DEBUG
  6153. std::fprintf(stdout, "\x1b[30;1m");
  6154. ret = std::vfprintf(stdout, fmt, ap);
  6155. std::fprintf(stdout, "\x1b[0m");
  6156. #endif
  6157. break;
  6158. case kUridLogWarning:
  6159. ret = std::vfprintf(stderr, fmt, ap);
  6160. break;
  6161. default:
  6162. break;
  6163. }
  6164. return ret;
  6165. }
  6166. // -------------------------------------------------------------------
  6167. // Programs Feature
  6168. static void carla_lv2_program_changed(LV2_Programs_Handle handle, int32_t index)
  6169. {
  6170. CARLA_SAFE_ASSERT_RETURN(handle != nullptr,);
  6171. carla_debug("carla_lv2_program_changed(%p, %i)", handle, index);
  6172. ((CarlaPluginLV2*)handle)->handleProgramChanged(index);
  6173. }
  6174. // -------------------------------------------------------------------
  6175. // Resize Port Feature
  6176. static LV2_Resize_Port_Status carla_lv2_resize_port(LV2_Resize_Port_Feature_Data data, uint32_t index, size_t size)
  6177. {
  6178. CARLA_SAFE_ASSERT_RETURN(data != nullptr, LV2_RESIZE_PORT_ERR_UNKNOWN);
  6179. carla_debug("carla_lv2_program_changed(%p, %i, " P_SIZE ")", data, index, size);
  6180. return ((CarlaPluginLV2*)data)->handleResizePort(index, size);
  6181. }
  6182. // -------------------------------------------------------------------
  6183. // State Feature
  6184. static void carla_lv2_state_free_path(LV2_State_Free_Path_Handle handle, char* const path)
  6185. {
  6186. CARLA_SAFE_ASSERT_RETURN(handle != nullptr,);
  6187. carla_debug("carla_lv2_state_free_path(%p, \"%s\")", handle, path);
  6188. std::free(path);
  6189. }
  6190. static char* carla_lv2_state_make_path_real(LV2_State_Make_Path_Handle handle, const char* const path)
  6191. {
  6192. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, nullptr);
  6193. CARLA_SAFE_ASSERT_RETURN(path != nullptr && path[0] != '\0', nullptr);
  6194. carla_debug("carla_lv2_state_make_path_real(%p, \"%s\")", handle, path);
  6195. const File file(((CarlaPluginLV2*)handle)->handleStateMapToAbsolutePath(true, false, false, path));
  6196. return file.isNotNull() ? strdup(file.getFullPathName().toRawUTF8()) : nullptr;
  6197. }
  6198. static char* carla_lv2_state_make_path_tmp(LV2_State_Make_Path_Handle handle, const char* const path)
  6199. {
  6200. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, nullptr);
  6201. CARLA_SAFE_ASSERT_RETURN(path != nullptr && path[0] != '\0', nullptr);
  6202. carla_debug("carla_lv2_state_make_path_tmp(%p, \"%s\")", handle, path);
  6203. const File file(((CarlaPluginLV2*)handle)->handleStateMapToAbsolutePath(true, false, true, path));
  6204. return file.isNotNull() ? strdup(file.getFullPathName().toRawUTF8()) : nullptr;
  6205. }
  6206. static char* carla_lv2_state_map_to_abstract_path_real(LV2_State_Map_Path_Handle handle, const char* const absolute_path)
  6207. {
  6208. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, nullptr);
  6209. CARLA_SAFE_ASSERT_RETURN(absolute_path != nullptr && absolute_path[0] != '\0', nullptr);
  6210. carla_debug("carla_lv2_state_map_to_abstract_path_real(%p, \"%s\")", handle, absolute_path);
  6211. return ((CarlaPluginLV2*)handle)->handleStateMapToAbstractPath(false, absolute_path);
  6212. }
  6213. static char* carla_lv2_state_map_to_abstract_path_tmp(LV2_State_Map_Path_Handle handle, const char* const absolute_path)
  6214. {
  6215. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, nullptr);
  6216. CARLA_SAFE_ASSERT_RETURN(absolute_path != nullptr && absolute_path[0] != '\0', nullptr);
  6217. carla_debug("carla_lv2_state_map_to_abstract_path_tmp(%p, \"%s\")", handle, absolute_path);
  6218. return ((CarlaPluginLV2*)handle)->handleStateMapToAbstractPath(true, absolute_path);
  6219. }
  6220. static char* carla_lv2_state_map_to_absolute_path_real(LV2_State_Map_Path_Handle handle, const char* const abstract_path)
  6221. {
  6222. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, nullptr);
  6223. CARLA_SAFE_ASSERT_RETURN(abstract_path != nullptr && abstract_path[0] != '\0', nullptr);
  6224. carla_debug("carla_lv2_state_map_to_absolute_path_real(%p, \"%s\")", handle, abstract_path);
  6225. const File file(((CarlaPluginLV2*)handle)->handleStateMapToAbsolutePath(true, true, false, abstract_path));
  6226. return file.isNotNull() ? strdup(file.getFullPathName().toRawUTF8()) : nullptr;
  6227. }
  6228. static char* carla_lv2_state_map_to_absolute_path_tmp(LV2_State_Map_Path_Handle handle, const char* const abstract_path)
  6229. {
  6230. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, nullptr);
  6231. CARLA_SAFE_ASSERT_RETURN(abstract_path != nullptr && abstract_path[0] != '\0', nullptr);
  6232. carla_debug("carla_lv2_state_map_to_absolute_path_tmp(%p, \"%s\")", handle, abstract_path);
  6233. const File file(((CarlaPluginLV2*)handle)->handleStateMapToAbsolutePath(true, true, true, abstract_path));
  6234. return file.isNotNull() ? strdup(file.getFullPathName().toRawUTF8()) : nullptr;
  6235. }
  6236. 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)
  6237. {
  6238. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, LV2_STATE_ERR_UNKNOWN);
  6239. carla_debug("carla_lv2_state_store(%p, %i, %p, " P_SIZE ", %i, %i)", handle, key, value, size, type, flags);
  6240. return ((CarlaPluginLV2*)handle)->handleStateStore(key, value, size, type, flags);
  6241. }
  6242. static const void* carla_lv2_state_retrieve(LV2_State_Handle handle, uint32_t key, size_t* size, uint32_t* type, uint32_t* flags)
  6243. {
  6244. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, nullptr);
  6245. carla_debug("carla_lv2_state_retrieve(%p, %i, %p, %p, %p)", handle, key, size, type, flags);
  6246. return ((CarlaPluginLV2*)handle)->handleStateRetrieve(key, size, type, flags);
  6247. }
  6248. // -------------------------------------------------------------------
  6249. // URI-Map Feature
  6250. static uint32_t carla_lv2_uri_to_id(LV2_URI_Map_Callback_Data data, const char* map, const char* uri)
  6251. {
  6252. carla_debug("carla_lv2_uri_to_id(%p, \"%s\", \"%s\")", data, map, uri);
  6253. return carla_lv2_urid_map((LV2_URID_Map_Handle*)data, uri);
  6254. // unused
  6255. (void)map;
  6256. }
  6257. // -------------------------------------------------------------------
  6258. // URID Feature
  6259. static LV2_URID carla_lv2_urid_map(LV2_URID_Map_Handle handle, const char* uri)
  6260. {
  6261. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, kUridNull);
  6262. CARLA_SAFE_ASSERT_RETURN(uri != nullptr && uri[0] != '\0', kUridNull);
  6263. carla_debug("carla_lv2_urid_map(%p, \"%s\")", handle, uri);
  6264. // Atom types
  6265. if (std::strcmp(uri, LV2_ATOM__Blank) == 0)
  6266. return kUridAtomBlank;
  6267. if (std::strcmp(uri, LV2_ATOM__Bool) == 0)
  6268. return kUridAtomBool;
  6269. if (std::strcmp(uri, LV2_ATOM__Chunk) == 0)
  6270. return kUridAtomChunk;
  6271. if (std::strcmp(uri, LV2_ATOM__Double) == 0)
  6272. return kUridAtomDouble;
  6273. if (std::strcmp(uri, LV2_ATOM__Event) == 0)
  6274. return kUridAtomEvent;
  6275. if (std::strcmp(uri, LV2_ATOM__Float) == 0)
  6276. return kUridAtomFloat;
  6277. if (std::strcmp(uri, LV2_ATOM__Int) == 0)
  6278. return kUridAtomInt;
  6279. if (std::strcmp(uri, LV2_ATOM__Literal) == 0)
  6280. return kUridAtomLiteral;
  6281. if (std::strcmp(uri, LV2_ATOM__Long) == 0)
  6282. return kUridAtomLong;
  6283. if (std::strcmp(uri, LV2_ATOM__Number) == 0)
  6284. return kUridAtomNumber;
  6285. if (std::strcmp(uri, LV2_ATOM__Object) == 0)
  6286. return kUridAtomObject;
  6287. if (std::strcmp(uri, LV2_ATOM__Path) == 0)
  6288. return kUridAtomPath;
  6289. if (std::strcmp(uri, LV2_ATOM__Property) == 0)
  6290. return kUridAtomProperty;
  6291. if (std::strcmp(uri, LV2_ATOM__Resource) == 0)
  6292. return kUridAtomResource;
  6293. if (std::strcmp(uri, LV2_ATOM__Sequence) == 0)
  6294. return kUridAtomSequence;
  6295. if (std::strcmp(uri, LV2_ATOM__Sound) == 0)
  6296. return kUridAtomSound;
  6297. if (std::strcmp(uri, LV2_ATOM__String) == 0)
  6298. return kUridAtomString;
  6299. if (std::strcmp(uri, LV2_ATOM__Tuple) == 0)
  6300. return kUridAtomTuple;
  6301. if (std::strcmp(uri, LV2_ATOM__URI) == 0)
  6302. return kUridAtomURI;
  6303. if (std::strcmp(uri, LV2_ATOM__URID) == 0)
  6304. return kUridAtomURID;
  6305. if (std::strcmp(uri, LV2_ATOM__Vector) == 0)
  6306. return kUridAtomVector;
  6307. if (std::strcmp(uri, LV2_ATOM__atomTransfer) == 0)
  6308. return kUridAtomTransferAtom;
  6309. if (std::strcmp(uri, LV2_ATOM__eventTransfer) == 0)
  6310. return kUridAtomTransferEvent;
  6311. // BufSize types
  6312. if (std::strcmp(uri, LV2_BUF_SIZE__maxBlockLength) == 0)
  6313. return kUridBufMaxLength;
  6314. if (std::strcmp(uri, LV2_BUF_SIZE__minBlockLength) == 0)
  6315. return kUridBufMinLength;
  6316. if (std::strcmp(uri, LV2_BUF_SIZE__nominalBlockLength) == 0)
  6317. return kUridBufNominalLength;
  6318. if (std::strcmp(uri, LV2_BUF_SIZE__sequenceSize) == 0)
  6319. return kUridBufSequenceSize;
  6320. // Log types
  6321. if (std::strcmp(uri, LV2_LOG__Error) == 0)
  6322. return kUridLogError;
  6323. if (std::strcmp(uri, LV2_LOG__Note) == 0)
  6324. return kUridLogNote;
  6325. if (std::strcmp(uri, LV2_LOG__Trace) == 0)
  6326. return kUridLogTrace;
  6327. if (std::strcmp(uri, LV2_LOG__Warning) == 0)
  6328. return kUridLogWarning;
  6329. // Patch types
  6330. if (std::strcmp(uri, LV2_PATCH__Set) == 0)
  6331. return kUridPatchSet;
  6332. if (std::strcmp(uri, LV2_PATCH__property) == 0)
  6333. return kUridPatchProperty;
  6334. if (std::strcmp(uri, LV2_PATCH__subject) == 0)
  6335. return kUridPatchSubject;
  6336. if (std::strcmp(uri, LV2_PATCH__value) == 0)
  6337. return kUridPatchValue;
  6338. // Time types
  6339. if (std::strcmp(uri, LV2_TIME__Position) == 0)
  6340. return kUridTimePosition;
  6341. if (std::strcmp(uri, LV2_TIME__bar) == 0)
  6342. return kUridTimeBar;
  6343. if (std::strcmp(uri, LV2_TIME__barBeat) == 0)
  6344. return kUridTimeBarBeat;
  6345. if (std::strcmp(uri, LV2_TIME__beat) == 0)
  6346. return kUridTimeBeat;
  6347. if (std::strcmp(uri, LV2_TIME__beatUnit) == 0)
  6348. return kUridTimeBeatUnit;
  6349. if (std::strcmp(uri, LV2_TIME__beatsPerBar) == 0)
  6350. return kUridTimeBeatsPerBar;
  6351. if (std::strcmp(uri, LV2_TIME__beatsPerMinute) == 0)
  6352. return kUridTimeBeatsPerMinute;
  6353. if (std::strcmp(uri, LV2_TIME__frame) == 0)
  6354. return kUridTimeFrame;
  6355. if (std::strcmp(uri, LV2_TIME__framesPerSecond) == 0)
  6356. return kUridTimeFramesPerSecond;
  6357. if (std::strcmp(uri, LV2_TIME__speed) == 0)
  6358. return kUridTimeSpeed;
  6359. if (std::strcmp(uri, LV2_KXSTUDIO_PROPERTIES__TimePositionTicksPerBeat) == 0)
  6360. return kUridTimeTicksPerBeat;
  6361. // Others
  6362. if (std::strcmp(uri, LV2_MIDI__MidiEvent) == 0)
  6363. return kUridMidiEvent;
  6364. if (std::strcmp(uri, LV2_PARAMETERS__sampleRate) == 0)
  6365. return kUridParamSampleRate;
  6366. if (std::strcmp(uri, LV2_UI__backgroundColor) == 0)
  6367. return kUridBackgroundColor;
  6368. if (std::strcmp(uri, LV2_UI__foregroundColor) == 0)
  6369. return kUridForegroundColor;
  6370. if (std::strcmp(uri, LV2_UI__scaleFactor) == 0)
  6371. return kUridScaleFactor;
  6372. if (std::strcmp(uri, LV2_UI__windowTitle) == 0)
  6373. return kUridWindowTitle;
  6374. // Custom Carla types
  6375. if (std::strcmp(uri, URI_CARLA_ATOM_WORKER_IN) == 0)
  6376. return kUridCarlaAtomWorkerIn;
  6377. if (std::strcmp(uri, URI_CARLA_ATOM_WORKER_RESP) == 0)
  6378. return kUridCarlaAtomWorkerResp;
  6379. if (std::strcmp(uri, URI_CARLA_PARAMETER_CHANGE) == 0)
  6380. return kUridCarlaParameterChange;
  6381. if (std::strcmp(uri, LV2_KXSTUDIO_PROPERTIES__TransientWindowId) == 0)
  6382. return kUridCarlaTransientWindowId;
  6383. // Custom plugin types
  6384. return ((CarlaPluginLV2*)handle)->getCustomURID(uri);
  6385. }
  6386. static const char* carla_lv2_urid_unmap(LV2_URID_Map_Handle handle, LV2_URID urid)
  6387. {
  6388. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, nullptr);
  6389. CARLA_SAFE_ASSERT_RETURN(urid != kUridNull, nullptr);
  6390. carla_debug("carla_lv2_urid_unmap(%p, %i)", handle, urid);
  6391. switch (urid)
  6392. {
  6393. // Atom types
  6394. case kUridAtomBlank:
  6395. return LV2_ATOM__Blank;
  6396. case kUridAtomBool:
  6397. return LV2_ATOM__Bool;
  6398. case kUridAtomChunk:
  6399. return LV2_ATOM__Chunk;
  6400. case kUridAtomDouble:
  6401. return LV2_ATOM__Double;
  6402. case kUridAtomEvent:
  6403. return LV2_ATOM__Event;
  6404. case kUridAtomFloat:
  6405. return LV2_ATOM__Float;
  6406. case kUridAtomInt:
  6407. return LV2_ATOM__Int;
  6408. case kUridAtomLiteral:
  6409. return LV2_ATOM__Literal;
  6410. case kUridAtomLong:
  6411. return LV2_ATOM__Long;
  6412. case kUridAtomNumber:
  6413. return LV2_ATOM__Number;
  6414. case kUridAtomObject:
  6415. return LV2_ATOM__Object;
  6416. case kUridAtomPath:
  6417. return LV2_ATOM__Path;
  6418. case kUridAtomProperty:
  6419. return LV2_ATOM__Property;
  6420. case kUridAtomResource:
  6421. return LV2_ATOM__Resource;
  6422. case kUridAtomSequence:
  6423. return LV2_ATOM__Sequence;
  6424. case kUridAtomSound:
  6425. return LV2_ATOM__Sound;
  6426. case kUridAtomString:
  6427. return LV2_ATOM__String;
  6428. case kUridAtomTuple:
  6429. return LV2_ATOM__Tuple;
  6430. case kUridAtomURI:
  6431. return LV2_ATOM__URI;
  6432. case kUridAtomURID:
  6433. return LV2_ATOM__URID;
  6434. case kUridAtomVector:
  6435. return LV2_ATOM__Vector;
  6436. case kUridAtomTransferAtom:
  6437. return LV2_ATOM__atomTransfer;
  6438. case kUridAtomTransferEvent:
  6439. return LV2_ATOM__eventTransfer;
  6440. // BufSize types
  6441. case kUridBufMaxLength:
  6442. return LV2_BUF_SIZE__maxBlockLength;
  6443. case kUridBufMinLength:
  6444. return LV2_BUF_SIZE__minBlockLength;
  6445. case kUridBufNominalLength:
  6446. return LV2_BUF_SIZE__nominalBlockLength;
  6447. case kUridBufSequenceSize:
  6448. return LV2_BUF_SIZE__sequenceSize;
  6449. // Log types
  6450. case kUridLogError:
  6451. return LV2_LOG__Error;
  6452. case kUridLogNote:
  6453. return LV2_LOG__Note;
  6454. case kUridLogTrace:
  6455. return LV2_LOG__Trace;
  6456. case kUridLogWarning:
  6457. return LV2_LOG__Warning;
  6458. // Patch types
  6459. case kUridPatchSet:
  6460. return LV2_PATCH__Set;
  6461. case kUridPatchProperty:
  6462. return LV2_PATCH__property;
  6463. case kUridPatchSubject:
  6464. return LV2_PATCH__subject;
  6465. case kUridPatchValue:
  6466. return LV2_PATCH__value;
  6467. // Time types
  6468. case kUridTimePosition:
  6469. return LV2_TIME__Position;
  6470. case kUridTimeBar:
  6471. return LV2_TIME__bar;
  6472. case kUridTimeBarBeat:
  6473. return LV2_TIME__barBeat;
  6474. case kUridTimeBeat:
  6475. return LV2_TIME__beat;
  6476. case kUridTimeBeatUnit:
  6477. return LV2_TIME__beatUnit;
  6478. case kUridTimeBeatsPerBar:
  6479. return LV2_TIME__beatsPerBar;
  6480. case kUridTimeBeatsPerMinute:
  6481. return LV2_TIME__beatsPerMinute;
  6482. case kUridTimeFrame:
  6483. return LV2_TIME__frame;
  6484. case kUridTimeFramesPerSecond:
  6485. return LV2_TIME__framesPerSecond;
  6486. case kUridTimeSpeed:
  6487. return LV2_TIME__speed;
  6488. case kUridTimeTicksPerBeat:
  6489. return LV2_KXSTUDIO_PROPERTIES__TimePositionTicksPerBeat;
  6490. // Others
  6491. case kUridMidiEvent:
  6492. return LV2_MIDI__MidiEvent;
  6493. case kUridParamSampleRate:
  6494. return LV2_PARAMETERS__sampleRate;
  6495. case kUridBackgroundColor:
  6496. return LV2_UI__backgroundColor;
  6497. case kUridForegroundColor:
  6498. return LV2_UI__foregroundColor;
  6499. case kUridScaleFactor:
  6500. return LV2_UI__scaleFactor;
  6501. case kUridWindowTitle:
  6502. return LV2_UI__windowTitle;
  6503. // Custom Carla types
  6504. case kUridCarlaAtomWorkerIn:
  6505. return URI_CARLA_ATOM_WORKER_IN;
  6506. case kUridCarlaAtomWorkerResp:
  6507. return URI_CARLA_ATOM_WORKER_RESP;
  6508. case kUridCarlaParameterChange:
  6509. return URI_CARLA_PARAMETER_CHANGE;
  6510. case kUridCarlaTransientWindowId:
  6511. return LV2_KXSTUDIO_PROPERTIES__TransientWindowId;
  6512. }
  6513. // Custom plugin types
  6514. return ((CarlaPluginLV2*)handle)->getCustomURIDString(urid);
  6515. }
  6516. // -------------------------------------------------------------------
  6517. // Worker Feature
  6518. static LV2_Worker_Status carla_lv2_worker_schedule(LV2_Worker_Schedule_Handle handle, uint32_t size, const void* data)
  6519. {
  6520. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, LV2_WORKER_ERR_UNKNOWN);
  6521. carla_debug("carla_lv2_worker_schedule(%p, %i, %p)", handle, size, data);
  6522. return ((CarlaPluginLV2*)handle)->handleWorkerSchedule(size, data);
  6523. }
  6524. static LV2_Worker_Status carla_lv2_worker_respond(LV2_Worker_Respond_Handle handle, uint32_t size, const void* data)
  6525. {
  6526. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, LV2_WORKER_ERR_UNKNOWN);
  6527. carla_debug("carla_lv2_worker_respond(%p, %i, %p)", handle, size, data);
  6528. return ((CarlaPluginLV2*)handle)->handleWorkerRespond(size, data);
  6529. }
  6530. // -------------------------------------------------------------------
  6531. // Inline Display Feature
  6532. static void carla_lv2_inline_display_queue_draw(LV2_Inline_Display_Handle handle)
  6533. {
  6534. CARLA_SAFE_ASSERT_RETURN(handle != nullptr,);
  6535. // carla_debug("carla_lv2_inline_display_queue_draw(%p)", handle);
  6536. ((CarlaPluginLV2*)handle)->handleInlineDisplayQueueRedraw();
  6537. }
  6538. // -------------------------------------------------------------------
  6539. // Midnam Feature
  6540. static void carla_lv2_midnam_update(LV2_Midnam_Handle handle)
  6541. {
  6542. CARLA_SAFE_ASSERT_RETURN(handle != nullptr,);
  6543. carla_stdout("carla_lv2_midnam_update(%p)", handle);
  6544. ((CarlaPluginLV2*)handle)->handleMidnamUpdate();
  6545. }
  6546. // -------------------------------------------------------------------
  6547. // External UI Feature
  6548. static void carla_lv2_external_ui_closed(LV2UI_Controller controller)
  6549. {
  6550. CARLA_SAFE_ASSERT_RETURN(controller != nullptr,);
  6551. carla_debug("carla_lv2_external_ui_closed(%p)", controller);
  6552. ((CarlaPluginLV2*)controller)->handleExternalUIClosed();
  6553. }
  6554. // -------------------------------------------------------------------
  6555. // UI Port-Map Feature
  6556. static uint32_t carla_lv2_ui_port_map(LV2UI_Feature_Handle handle, const char* symbol)
  6557. {
  6558. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, LV2UI_INVALID_PORT_INDEX);
  6559. carla_debug("carla_lv2_ui_port_map(%p, \"%s\")", handle, symbol);
  6560. return ((CarlaPluginLV2*)handle)->handleUIPortMap(symbol);
  6561. }
  6562. // ----------------------------------------------------------------------------------------------------------------
  6563. // UI Request Parameter Feature
  6564. static LV2UI_Request_Value_Status carla_lv2_ui_request_value(LV2UI_Feature_Handle handle,
  6565. LV2_URID key,
  6566. LV2_URID type,
  6567. const LV2_Feature* const* features)
  6568. {
  6569. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, LV2UI_REQUEST_VALUE_ERR_UNKNOWN);
  6570. carla_debug("carla_lv2_ui_request_value(%p, %u, %u, %p)", handle, key, type, features);
  6571. return ((CarlaPluginLV2*)handle)->handleUIRequestValue(key, type, features);
  6572. }
  6573. // -------------------------------------------------------------------
  6574. // UI Resize Feature
  6575. static int carla_lv2_ui_resize(LV2UI_Feature_Handle handle, int width, int height)
  6576. {
  6577. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, 1);
  6578. carla_debug("carla_lv2_ui_resize(%p, %i, %i)", handle, width, height);
  6579. return ((CarlaPluginLV2*)handle)->handleUIResize(width, height);
  6580. }
  6581. // -------------------------------------------------------------------
  6582. // UI Touch Feature
  6583. static void carla_lv2_ui_touch(LV2UI_Feature_Handle handle, uint32_t port_index, bool touch)
  6584. {
  6585. CARLA_SAFE_ASSERT_RETURN(handle != nullptr,);
  6586. carla_debug("carla_lv2_ui_touch(%p, %u, %s)", handle, port_index, bool2str(touch));
  6587. ((CarlaPluginLV2*)handle)->handleUITouch(port_index, touch);
  6588. }
  6589. // -------------------------------------------------------------------
  6590. // UI Extension
  6591. static void carla_lv2_ui_write_function(LV2UI_Controller controller, uint32_t port_index, uint32_t buffer_size, uint32_t format, const void* buffer)
  6592. {
  6593. CARLA_SAFE_ASSERT_RETURN(controller != nullptr,);
  6594. carla_debug("carla_lv2_ui_write_function(%p, %i, %i, %i, %p)", controller, port_index, buffer_size, format, buffer);
  6595. ((CarlaPluginLV2*)controller)->handleUIWrite(port_index, buffer_size, format, buffer);
  6596. }
  6597. // -------------------------------------------------------------------
  6598. // Lilv State
  6599. static void carla_lilv_set_port_value(const char* port_symbol, void* user_data, const void* value, uint32_t size, uint32_t type)
  6600. {
  6601. CARLA_SAFE_ASSERT_RETURN(user_data != nullptr,);
  6602. carla_debug("carla_lilv_set_port_value(\"%s\", %p, %p, %i, %i", port_symbol, user_data, value, size, type);
  6603. ((CarlaPluginLV2*)user_data)->handleLilvSetPortValue(port_symbol, value, size, type);
  6604. }
  6605. // -------------------------------------------------------------------
  6606. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginLV2)
  6607. };
  6608. // -------------------------------------------------------------------------------------------------------------------
  6609. bool CarlaPipeServerLV2::msgReceived(const char* const msg) noexcept
  6610. {
  6611. if (std::strcmp(msg, "exiting") == 0)
  6612. {
  6613. closePipeServer();
  6614. fUiState = UiHide;
  6615. return true;
  6616. }
  6617. if (std::strcmp(msg, "control") == 0)
  6618. {
  6619. uint32_t index;
  6620. float value;
  6621. CARLA_SAFE_ASSERT_RETURN(readNextLineAsUInt(index), true);
  6622. CARLA_SAFE_ASSERT_RETURN(readNextLineAsFloat(value), true);
  6623. try {
  6624. kPlugin->handleUIWrite(index, sizeof(float), kUridNull, &value);
  6625. } CARLA_SAFE_EXCEPTION("magReceived control");
  6626. return true;
  6627. }
  6628. if (std::strcmp(msg, "pcontrol") == 0)
  6629. {
  6630. const char* uri;
  6631. float value;
  6632. CARLA_SAFE_ASSERT_RETURN(readNextLineAsString(uri, true), true);
  6633. CARLA_SAFE_ASSERT_RETURN(readNextLineAsFloat(value), true);
  6634. try {
  6635. kPlugin->handleUIBridgeParameter(uri, value);
  6636. } CARLA_SAFE_EXCEPTION("magReceived pcontrol");
  6637. return true;
  6638. }
  6639. if (std::strcmp(msg, "atom") == 0)
  6640. {
  6641. uint32_t index, atomTotalSize, base64Size;
  6642. const char* base64atom;
  6643. CARLA_SAFE_ASSERT_RETURN(readNextLineAsUInt(index), true);
  6644. CARLA_SAFE_ASSERT_RETURN(readNextLineAsUInt(atomTotalSize), true);
  6645. CARLA_SAFE_ASSERT_RETURN(readNextLineAsUInt(base64Size), true);
  6646. CARLA_SAFE_ASSERT_RETURN(readNextLineAsString(base64atom, false, base64Size), true);
  6647. std::vector<uint8_t> chunk(carla_getChunkFromBase64String(base64atom));
  6648. CARLA_SAFE_ASSERT_UINT2_RETURN(chunk.size() >= sizeof(LV2_Atom), chunk.size(), sizeof(LV2_Atom), true);
  6649. #ifdef CARLA_PROPER_CPP11_SUPPORT
  6650. const LV2_Atom* const atom((const LV2_Atom*)chunk.data());
  6651. #else
  6652. const LV2_Atom* const atom((const LV2_Atom*)&chunk.front());
  6653. #endif
  6654. CARLA_SAFE_ASSERT_RETURN(lv2_atom_total_size(atom) == chunk.size(), true);
  6655. try {
  6656. kPlugin->handleUIWrite(index, lv2_atom_total_size(atom), kUridAtomTransferEvent, atom);
  6657. } CARLA_SAFE_EXCEPTION("magReceived atom");
  6658. return true;
  6659. }
  6660. if (std::strcmp(msg, "program") == 0)
  6661. {
  6662. uint32_t index;
  6663. CARLA_SAFE_ASSERT_RETURN(readNextLineAsUInt(index), true);
  6664. try {
  6665. kPlugin->setMidiProgram(static_cast<int32_t>(index), false, true, true, false);
  6666. } CARLA_SAFE_EXCEPTION("msgReceived program");
  6667. return true;
  6668. }
  6669. if (std::strcmp(msg, "urid") == 0)
  6670. {
  6671. uint32_t urid, size;
  6672. const char* uri;
  6673. CARLA_SAFE_ASSERT_RETURN(readNextLineAsUInt(urid), true);
  6674. CARLA_SAFE_ASSERT_RETURN(readNextLineAsUInt(size), true);
  6675. CARLA_SAFE_ASSERT_RETURN(readNextLineAsString(uri, false, size), true);
  6676. if (urid != 0)
  6677. {
  6678. try {
  6679. kPlugin->handleUridMap(urid, uri);
  6680. } CARLA_SAFE_EXCEPTION("msgReceived urid");
  6681. }
  6682. return true;
  6683. }
  6684. if (std::strcmp(msg, "reloadprograms") == 0)
  6685. {
  6686. int32_t index;
  6687. CARLA_SAFE_ASSERT_RETURN(readNextLineAsInt(index), true);
  6688. try {
  6689. kPlugin->handleProgramChanged(index);
  6690. } CARLA_SAFE_EXCEPTION("handleProgramChanged");
  6691. return true;
  6692. }
  6693. if (std::strcmp(msg, "requestvalue") == 0)
  6694. {
  6695. uint32_t key, type;
  6696. CARLA_SAFE_ASSERT_RETURN(readNextLineAsUInt(key), true);
  6697. CARLA_SAFE_ASSERT_RETURN(readNextLineAsUInt(type), true);
  6698. if (key != 0)
  6699. {
  6700. try {
  6701. kPlugin->handleUIRequestValue(key, type, nullptr);
  6702. } CARLA_SAFE_EXCEPTION("msgReceived requestvalue");
  6703. }
  6704. return true;
  6705. }
  6706. return false;
  6707. }
  6708. // -------------------------------------------------------------------------------------------------------------------
  6709. CarlaPluginPtr CarlaPlugin::newLV2(const Initializer& init)
  6710. {
  6711. carla_debug("CarlaPlugin::newLV2({%p, \"%s\", \"%s\"})", init.engine, init.name, init.label);
  6712. std::shared_ptr<CarlaPluginLV2> plugin(new CarlaPluginLV2(init.engine, init.id));
  6713. const char* needsArchBridge = nullptr;
  6714. if (plugin->init(plugin, init.name, init.label, init.options, needsArchBridge))
  6715. return plugin;
  6716. if (needsArchBridge != nullptr)
  6717. {
  6718. CarlaString bridgeBinary(init.engine->getOptions().binaryDir);
  6719. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-native";
  6720. return CarlaPlugin::newBridge(init, BINARY_NATIVE, PLUGIN_LV2, needsArchBridge, bridgeBinary);
  6721. }
  6722. return nullptr;
  6723. }
  6724. // used in CarlaStandalone.cpp
  6725. const void* carla_render_inline_display_lv2(const CarlaPluginPtr& plugin, uint32_t width, uint32_t height);
  6726. const void* carla_render_inline_display_lv2(const CarlaPluginPtr& plugin, uint32_t width, uint32_t height)
  6727. {
  6728. const std::shared_ptr<CarlaPluginLV2>& lv2Plugin((const std::shared_ptr<CarlaPluginLV2>&)plugin);
  6729. return lv2Plugin->renderInlineDisplay(width, height);
  6730. }
  6731. // -------------------------------------------------------------------------------------------------------------------
  6732. CARLA_BACKEND_END_NAMESPACE