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.

8294 lines
304KB

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