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.

8454 lines
309KB

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