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.

8505 lines
311KB

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