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.

8246 lines
302KB

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