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.

8347 lines
305KB

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