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.

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