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.

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