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.

8337 lines
304KB

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