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.

8496 lines
311KB

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