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.

8468 lines
310KB

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