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.

8465 lines
310KB

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