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.

8380 lines
306KB

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