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.

8482 lines
310KB

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