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.

8372 lines
306KB

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