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.

8335 lines
304KB

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