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.

8259 lines
303KB

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