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.

8437 lines
308KB

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