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.

8291 lines
303KB

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