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.

6316 lines
239KB

  1. /*
  2. * Carla LV2 Plugin
  3. * Copyright (C) 2011-2017 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 "CarlaBase64Utils.hpp"
  24. #include "CarlaEngineUtils.hpp"
  25. #include "CarlaPipeUtils.hpp"
  26. #include "CarlaPluginUI.hpp"
  27. #include "Lv2AtomRingBuffer.hpp"
  28. #include "../engine/CarlaEngineOsc.hpp"
  29. #include "../modules/lilv/config/lilv_config.h"
  30. extern "C" {
  31. #include "rtmempool/rtmempool-lv2.h"
  32. }
  33. #include "juce_core/juce_core.h"
  34. #include <string>
  35. #include <vector>
  36. using juce::File;
  37. #define URI_CARLA_ATOM_WORKER "http://kxstudio.sf.net/ns/carla/atomWorker"
  38. CARLA_BACKEND_START_NAMESPACE
  39. // -------------------------------------------------------------------------------------------------------------------
  40. // Fallback data
  41. static const CustomData kCustomDataFallback = { nullptr, nullptr, nullptr };
  42. static /* */ CustomData kCustomDataFallbackNC = { nullptr, nullptr, nullptr };
  43. static const ExternalMidiNote kExternalMidiNoteFallback = { -1, 0, 0 };
  44. // -------------------------------------------------------------------------------------------------------------------
  45. // Maximum default buffer size
  46. const uint MAX_DEFAULT_BUFFER_SIZE = 8192; // 0x2000
  47. // Extra Plugin Hints
  48. const uint PLUGIN_HAS_EXTENSION_OPTIONS = 0x01000;
  49. const uint PLUGIN_HAS_EXTENSION_PROGRAMS = 0x02000;
  50. const uint PLUGIN_HAS_EXTENSION_STATE = 0x04000;
  51. const uint PLUGIN_HAS_EXTENSION_WORKER = 0x08000;
  52. const uint PLUGIN_HAS_EXTENSION_INLINE_DISPLAY = 0x10000;
  53. // Extra Parameter Hints
  54. const uint PARAMETER_IS_STRICT_BOUNDS = 0x1000;
  55. const uint PARAMETER_IS_TRIGGER = 0x2000;
  56. // LV2 Event Data/Types
  57. const uint CARLA_EVENT_DATA_ATOM = 0x01;
  58. const uint CARLA_EVENT_DATA_EVENT = 0x02;
  59. const uint CARLA_EVENT_DATA_MIDI_LL = 0x04;
  60. const uint CARLA_EVENT_TYPE_MESSAGE = 0x10; // unused
  61. const uint CARLA_EVENT_TYPE_MIDI = 0x20;
  62. const uint CARLA_EVENT_TYPE_TIME = 0x40;
  63. // LV2 URI Map Ids
  64. const uint32_t CARLA_URI_MAP_ID_NULL = 0;
  65. const uint32_t CARLA_URI_MAP_ID_ATOM_BLANK = 1;
  66. const uint32_t CARLA_URI_MAP_ID_ATOM_BOOL = 2;
  67. const uint32_t CARLA_URI_MAP_ID_ATOM_CHUNK = 3;
  68. const uint32_t CARLA_URI_MAP_ID_ATOM_DOUBLE = 4;
  69. const uint32_t CARLA_URI_MAP_ID_ATOM_EVENT = 5;
  70. const uint32_t CARLA_URI_MAP_ID_ATOM_FLOAT = 6;
  71. const uint32_t CARLA_URI_MAP_ID_ATOM_INT = 7;
  72. const uint32_t CARLA_URI_MAP_ID_ATOM_LITERAL = 8;
  73. const uint32_t CARLA_URI_MAP_ID_ATOM_LONG = 9;
  74. const uint32_t CARLA_URI_MAP_ID_ATOM_NUMBER = 10;
  75. const uint32_t CARLA_URI_MAP_ID_ATOM_OBJECT = 11;
  76. const uint32_t CARLA_URI_MAP_ID_ATOM_PATH = 12;
  77. const uint32_t CARLA_URI_MAP_ID_ATOM_PROPERTY = 13;
  78. const uint32_t CARLA_URI_MAP_ID_ATOM_RESOURCE = 14;
  79. const uint32_t CARLA_URI_MAP_ID_ATOM_SEQUENCE = 15;
  80. const uint32_t CARLA_URI_MAP_ID_ATOM_SOUND = 16;
  81. const uint32_t CARLA_URI_MAP_ID_ATOM_STRING = 17;
  82. const uint32_t CARLA_URI_MAP_ID_ATOM_TUPLE = 18;
  83. const uint32_t CARLA_URI_MAP_ID_ATOM_URI = 19;
  84. const uint32_t CARLA_URI_MAP_ID_ATOM_URID = 20;
  85. const uint32_t CARLA_URI_MAP_ID_ATOM_VECTOR = 21;
  86. const uint32_t CARLA_URI_MAP_ID_ATOM_TRANSFER_ATOM = 22;
  87. const uint32_t CARLA_URI_MAP_ID_ATOM_TRANSFER_EVENT = 23;
  88. const uint32_t CARLA_URI_MAP_ID_BUF_MAX_LENGTH = 24;
  89. const uint32_t CARLA_URI_MAP_ID_BUF_MIN_LENGTH = 25;
  90. const uint32_t CARLA_URI_MAP_ID_BUF_NOMINAL_LENGTH = 26;
  91. const uint32_t CARLA_URI_MAP_ID_BUF_SEQUENCE_SIZE = 27;
  92. const uint32_t CARLA_URI_MAP_ID_LOG_ERROR = 28;
  93. const uint32_t CARLA_URI_MAP_ID_LOG_NOTE = 29;
  94. const uint32_t CARLA_URI_MAP_ID_LOG_TRACE = 30;
  95. const uint32_t CARLA_URI_MAP_ID_LOG_WARNING = 31;
  96. const uint32_t CARLA_URI_MAP_ID_TIME_POSITION = 32; // base type
  97. const uint32_t CARLA_URI_MAP_ID_TIME_BAR = 33; // values
  98. const uint32_t CARLA_URI_MAP_ID_TIME_BAR_BEAT = 34;
  99. const uint32_t CARLA_URI_MAP_ID_TIME_BEAT = 35;
  100. const uint32_t CARLA_URI_MAP_ID_TIME_BEAT_UNIT = 36;
  101. const uint32_t CARLA_URI_MAP_ID_TIME_BEATS_PER_BAR = 37;
  102. const uint32_t CARLA_URI_MAP_ID_TIME_BEATS_PER_MINUTE = 38;
  103. const uint32_t CARLA_URI_MAP_ID_TIME_FRAME = 39;
  104. const uint32_t CARLA_URI_MAP_ID_TIME_FRAMES_PER_SECOND = 40;
  105. const uint32_t CARLA_URI_MAP_ID_TIME_SPEED = 41;
  106. const uint32_t CARLA_URI_MAP_ID_TIME_TICKS_PER_BEAT = 42;
  107. const uint32_t CARLA_URI_MAP_ID_MIDI_EVENT = 43;
  108. const uint32_t CARLA_URI_MAP_ID_PARAM_SAMPLE_RATE = 44;
  109. const uint32_t CARLA_URI_MAP_ID_UI_WINDOW_TITLE = 45;
  110. const uint32_t CARLA_URI_MAP_ID_CARLA_ATOM_WORKER = 46;
  111. const uint32_t CARLA_URI_MAP_ID_CARLA_TRANSIENT_WIN_ID = 47;
  112. const uint32_t CARLA_URI_MAP_ID_COUNT = 48;
  113. // LV2 Feature Ids
  114. enum CarlaLv2Features {
  115. kFeatureIdBufSizeBounded = 0,
  116. kFeatureIdBufSizeFixed,
  117. kFeatureIdBufSizePowerOf2,
  118. kFeatureIdEvent,
  119. kFeatureIdHardRtCapable,
  120. kFeatureIdInPlaceBroken,
  121. kFeatureIdIsLive,
  122. kFeatureIdLogs,
  123. kFeatureIdOptions,
  124. kFeatureIdPrograms,
  125. kFeatureIdResizePort,
  126. kFeatureIdRtMemPool,
  127. kFeatureIdRtMemPoolOld,
  128. kFeatureIdStateMakePath,
  129. kFeatureIdStateMapPath,
  130. kFeatureIdStrictBounds,
  131. kFeatureIdUriMap,
  132. kFeatureIdUridMap,
  133. kFeatureIdUridUnmap,
  134. kFeatureIdWorker,
  135. kFeatureIdInlineDisplay,
  136. kFeatureCountPlugin,
  137. kFeatureIdUiDataAccess,
  138. kFeatureIdUiInstanceAccess,
  139. kFeatureIdUiIdleInterface,
  140. kFeatureIdUiFixedSize,
  141. kFeatureIdUiMakeResident,
  142. kFeatureIdUiMakeResident2,
  143. kFeatureIdUiNoUserResize,
  144. kFeatureIdUiParent,
  145. kFeatureIdUiPortMap,
  146. kFeatureIdUiPortSubscribe,
  147. kFeatureIdUiResize,
  148. kFeatureIdUiTouch,
  149. kFeatureIdExternalUi,
  150. kFeatureIdExternalUiOld,
  151. kFeatureCountAll
  152. };
  153. // -------------------------------------------------------------------------------------------------------------------
  154. struct Lv2EventData {
  155. uint32_t type;
  156. uint32_t rindex;
  157. CarlaEngineEventPort* port;
  158. union {
  159. LV2_Atom_Buffer* atom;
  160. LV2_Event_Buffer* event;
  161. LV2_MIDI midi;
  162. };
  163. Lv2EventData() noexcept
  164. : type(0x0),
  165. rindex(0),
  166. port(nullptr) {}
  167. ~Lv2EventData() noexcept
  168. {
  169. if (port != nullptr)
  170. {
  171. delete port;
  172. port = nullptr;
  173. }
  174. const uint32_t rtype(type);
  175. type = 0x0;
  176. if (rtype & CARLA_EVENT_DATA_ATOM)
  177. {
  178. CARLA_SAFE_ASSERT_RETURN(atom != nullptr,);
  179. std::free(atom);
  180. atom = nullptr;
  181. }
  182. else if (rtype & CARLA_EVENT_DATA_EVENT)
  183. {
  184. CARLA_SAFE_ASSERT_RETURN(event != nullptr,);
  185. std::free(event);
  186. event = nullptr;
  187. }
  188. else if (rtype & CARLA_EVENT_DATA_MIDI_LL)
  189. {
  190. CARLA_SAFE_ASSERT_RETURN(midi.data != nullptr,);
  191. delete[] midi.data;
  192. midi.data = nullptr;
  193. }
  194. }
  195. CARLA_DECLARE_NON_COPY_STRUCT(Lv2EventData)
  196. };
  197. struct CarlaPluginLV2EventData {
  198. uint32_t count;
  199. Lv2EventData* data;
  200. Lv2EventData* ctrl; // default port, either this->data[x] or pData->portIn/Out
  201. uint32_t ctrlIndex;
  202. CarlaPluginLV2EventData() noexcept
  203. : count(0),
  204. data(nullptr),
  205. ctrl(nullptr),
  206. ctrlIndex(0) {}
  207. ~CarlaPluginLV2EventData() noexcept
  208. {
  209. CARLA_SAFE_ASSERT_INT(count == 0, count);
  210. CARLA_SAFE_ASSERT(data == nullptr);
  211. CARLA_SAFE_ASSERT(ctrl == nullptr);
  212. CARLA_SAFE_ASSERT_INT(ctrlIndex == 0, ctrlIndex);
  213. }
  214. void createNew(const uint32_t newCount)
  215. {
  216. CARLA_SAFE_ASSERT_INT(count == 0, count);
  217. CARLA_SAFE_ASSERT_INT(ctrlIndex == 0, ctrlIndex);
  218. CARLA_SAFE_ASSERT_RETURN(data == nullptr,);
  219. CARLA_SAFE_ASSERT_RETURN(ctrl == nullptr,);
  220. CARLA_SAFE_ASSERT_RETURN(newCount > 0,);
  221. data = new Lv2EventData[newCount];
  222. count = newCount;
  223. ctrl = nullptr;
  224. ctrlIndex = 0;
  225. }
  226. void clear() noexcept
  227. {
  228. if (data != nullptr)
  229. {
  230. for (uint32_t i=0; i < count; ++i)
  231. {
  232. if (data[i].port != nullptr && ctrl != nullptr && data[i].port == ctrl->port)
  233. data[i].port = nullptr;
  234. }
  235. delete[] data;
  236. data = nullptr;
  237. }
  238. count = 0;
  239. ctrl = nullptr;
  240. ctrlIndex = 0;
  241. }
  242. void initBuffers() const noexcept
  243. {
  244. for (uint32_t i=0; i < count; ++i)
  245. {
  246. if (data[i].port != nullptr && (ctrl == nullptr || data[i].port != ctrl->port))
  247. data[i].port->initBuffer();
  248. }
  249. }
  250. CARLA_DECLARE_NON_COPY_STRUCT(CarlaPluginLV2EventData)
  251. };
  252. // -------------------------------------------------------------------------------------------------------------------
  253. struct CarlaPluginLV2Options {
  254. enum OptIndex {
  255. MaxBlockLenth = 0,
  256. MinBlockLenth,
  257. NominalBlockLenth,
  258. SequenceSize,
  259. SampleRate,
  260. FrontendWinId,
  261. WindowTitle,
  262. Null,
  263. Count
  264. };
  265. int maxBufferSize;
  266. int minBufferSize;
  267. int nominalBufferSize;
  268. int sequenceSize;
  269. double sampleRate;
  270. int64_t frontendWinId;
  271. const char* windowTitle;
  272. LV2_Options_Option opts[Count];
  273. CarlaPluginLV2Options() noexcept
  274. : maxBufferSize(0),
  275. minBufferSize(0),
  276. nominalBufferSize(0),
  277. sequenceSize(MAX_DEFAULT_BUFFER_SIZE),
  278. sampleRate(0.0),
  279. frontendWinId(0),
  280. windowTitle(nullptr)
  281. {
  282. LV2_Options_Option& optMaxBlockLenth(opts[MaxBlockLenth]);
  283. optMaxBlockLenth.context = LV2_OPTIONS_INSTANCE;
  284. optMaxBlockLenth.subject = 0;
  285. optMaxBlockLenth.key = CARLA_URI_MAP_ID_BUF_MAX_LENGTH;
  286. optMaxBlockLenth.size = sizeof(int);
  287. optMaxBlockLenth.type = CARLA_URI_MAP_ID_ATOM_INT;
  288. optMaxBlockLenth.value = &maxBufferSize;
  289. LV2_Options_Option& optMinBlockLenth(opts[MinBlockLenth]);
  290. optMinBlockLenth.context = LV2_OPTIONS_INSTANCE;
  291. optMinBlockLenth.subject = 0;
  292. optMinBlockLenth.key = CARLA_URI_MAP_ID_BUF_MIN_LENGTH;
  293. optMinBlockLenth.size = sizeof(int);
  294. optMinBlockLenth.type = CARLA_URI_MAP_ID_ATOM_INT;
  295. optMinBlockLenth.value = &minBufferSize;
  296. LV2_Options_Option& optNominalBlockLenth(opts[NominalBlockLenth]);
  297. optNominalBlockLenth.context = LV2_OPTIONS_INSTANCE;
  298. optNominalBlockLenth.subject = 0;
  299. optNominalBlockLenth.key = CARLA_URI_MAP_ID_BUF_NOMINAL_LENGTH;
  300. optNominalBlockLenth.size = sizeof(int);
  301. optNominalBlockLenth.type = CARLA_URI_MAP_ID_ATOM_INT;
  302. optNominalBlockLenth.value = &nominalBufferSize;
  303. LV2_Options_Option& optSequenceSize(opts[SequenceSize]);
  304. optSequenceSize.context = LV2_OPTIONS_INSTANCE;
  305. optSequenceSize.subject = 0;
  306. optSequenceSize.key = CARLA_URI_MAP_ID_BUF_SEQUENCE_SIZE;
  307. optSequenceSize.size = sizeof(int);
  308. optSequenceSize.type = CARLA_URI_MAP_ID_ATOM_INT;
  309. optSequenceSize.value = &sequenceSize;
  310. LV2_Options_Option& optSampleRate(opts[SampleRate]);
  311. optSampleRate.context = LV2_OPTIONS_INSTANCE;
  312. optSampleRate.subject = 0;
  313. optSampleRate.key = CARLA_URI_MAP_ID_PARAM_SAMPLE_RATE;
  314. optSampleRate.size = sizeof(double);
  315. optSampleRate.type = CARLA_URI_MAP_ID_ATOM_DOUBLE;
  316. optSampleRate.value = &sampleRate;
  317. LV2_Options_Option& optFrontendWinId(opts[FrontendWinId]);
  318. optFrontendWinId.context = LV2_OPTIONS_INSTANCE;
  319. optFrontendWinId.subject = 0;
  320. optFrontendWinId.key = CARLA_URI_MAP_ID_CARLA_TRANSIENT_WIN_ID;
  321. optFrontendWinId.size = sizeof(int64_t);
  322. optFrontendWinId.type = CARLA_URI_MAP_ID_ATOM_LONG;
  323. optFrontendWinId.value = &frontendWinId;
  324. LV2_Options_Option& optWindowTitle(opts[WindowTitle]);
  325. optWindowTitle.context = LV2_OPTIONS_INSTANCE;
  326. optWindowTitle.subject = 0;
  327. optWindowTitle.key = CARLA_URI_MAP_ID_UI_WINDOW_TITLE;
  328. optWindowTitle.size = 0;
  329. optWindowTitle.type = CARLA_URI_MAP_ID_ATOM_STRING;
  330. optWindowTitle.value = nullptr;
  331. LV2_Options_Option& optNull(opts[Null]);
  332. optNull.context = LV2_OPTIONS_INSTANCE;
  333. optNull.subject = 0;
  334. optNull.key = CARLA_URI_MAP_ID_NULL;
  335. optNull.size = 0;
  336. optNull.type = CARLA_URI_MAP_ID_NULL;
  337. optNull.value = nullptr;
  338. }
  339. ~CarlaPluginLV2Options() noexcept
  340. {
  341. LV2_Options_Option& optWindowTitle(opts[WindowTitle]);
  342. optWindowTitle.size = 0;
  343. optWindowTitle.value = nullptr;
  344. if (windowTitle != nullptr)
  345. {
  346. delete[] windowTitle;
  347. windowTitle = nullptr;
  348. }
  349. }
  350. CARLA_DECLARE_NON_COPY_STRUCT(CarlaPluginLV2Options);
  351. };
  352. // -------------------------------------------------------------------------------------------------------------------
  353. class CarlaPluginLV2;
  354. class CarlaPipeServerLV2 : public CarlaPipeServer
  355. {
  356. public:
  357. enum UiState {
  358. UiNone = 0,
  359. UiHide,
  360. UiShow,
  361. UiCrashed
  362. };
  363. CarlaPipeServerLV2(CarlaEngine* const engine, CarlaPluginLV2* const plugin)
  364. : kEngine(engine),
  365. kPlugin(plugin),
  366. fFilename(),
  367. fPluginURI(),
  368. fUiURI(),
  369. fUiState(UiNone) {}
  370. ~CarlaPipeServerLV2() noexcept override
  371. {
  372. CARLA_SAFE_ASSERT_INT(fUiState == UiNone, fUiState);
  373. }
  374. UiState getAndResetUiState() noexcept
  375. {
  376. const UiState uiState(fUiState);
  377. fUiState = UiNone;
  378. return uiState;
  379. }
  380. void setData(const char* const filename, const char* const pluginURI, const char* const uiURI) noexcept
  381. {
  382. fFilename = filename;
  383. fPluginURI = pluginURI;
  384. fUiURI = uiURI;
  385. }
  386. bool startPipeServer(const int size) noexcept
  387. {
  388. const ScopedEngineEnvironmentLocker _seel(kEngine);
  389. const ScopedEnvVar _sev1("LV2_PATH", kEngine->getOptions().pathLV2);
  390. #ifdef CARLA_OS_LINUX
  391. const ScopedEnvVar _sev2("LD_PRELOAD", nullptr);
  392. #endif
  393. return CarlaPipeServer::startPipeServer(fFilename, fPluginURI, fUiURI, size);
  394. }
  395. void writeUiTitleMessage(const char* const title) const noexcept
  396. {
  397. CARLA_SAFE_ASSERT_RETURN(title != nullptr && title[0] != '\0',);
  398. const CarlaMutexLocker cml(getPipeLock());
  399. _writeMsgBuffer("uiTitle\n", 8);
  400. writeAndFixMessage(title);
  401. flushMessages();
  402. }
  403. protected:
  404. // returns true if msg was handled
  405. bool msgReceived(const char* const msg) noexcept override;
  406. private:
  407. CarlaEngine* const kEngine;
  408. CarlaPluginLV2* const kPlugin;
  409. CarlaString fFilename;
  410. CarlaString fPluginURI;
  411. CarlaString fUiURI;
  412. UiState fUiState;
  413. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPipeServerLV2)
  414. };
  415. // -------------------------------------------------------------------------------------------------------------------
  416. class CarlaPluginLV2 : public CarlaPlugin,
  417. private CarlaPluginUI::CloseCallback
  418. {
  419. public:
  420. CarlaPluginLV2(CarlaEngine* const engine, const uint id)
  421. : CarlaPlugin(engine, id),
  422. fHandle(nullptr),
  423. fHandle2(nullptr),
  424. fDescriptor(nullptr),
  425. fRdfDescriptor(nullptr),
  426. fAudioInBuffers(nullptr),
  427. fAudioOutBuffers(nullptr),
  428. fCvInBuffers(nullptr),
  429. fCvOutBuffers(nullptr),
  430. fParamBuffers(nullptr),
  431. fCanInit2(true),
  432. fNeedsFixedBuffers(false),
  433. fNeedsUiClose(false),
  434. fLatencyIndex(-1),
  435. fStrictBounds(-1),
  436. fAtomBufferIn(),
  437. fAtomBufferOut(),
  438. fAtomForge(),
  439. fTmpAtomBuffer(nullptr),
  440. fEventsIn(),
  441. fEventsOut(),
  442. fLv2Options(),
  443. fPipeServer(engine, this),
  444. fCustomURIDs(CARLA_URI_MAP_ID_COUNT, std::string("urn:null")),
  445. fFirstActive(true),
  446. fLastStateChunk(nullptr),
  447. fLastTimeInfo(),
  448. fExt(),
  449. fUI()
  450. {
  451. carla_debug("CarlaPluginLV2::CarlaPluginLV2(%p, %i)", engine, id);
  452. CARLA_SAFE_ASSERT(fCustomURIDs.size() == CARLA_URI_MAP_ID_COUNT);
  453. carla_zeroPointers(fFeatures, kFeatureCountAll+1);
  454. #if defined(__clang__)
  455. # pragma clang diagnostic push
  456. # pragma clang diagnostic ignored "-Wdeprecated-declarations"
  457. #elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
  458. # pragma GCC diagnostic push
  459. # pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  460. #endif
  461. fAtomForge.Blank = CARLA_URI_MAP_ID_ATOM_BLANK;
  462. fAtomForge.Bool = CARLA_URI_MAP_ID_ATOM_BOOL;
  463. fAtomForge.Chunk = CARLA_URI_MAP_ID_ATOM_CHUNK;
  464. fAtomForge.Double = CARLA_URI_MAP_ID_ATOM_DOUBLE;
  465. fAtomForge.Float = CARLA_URI_MAP_ID_ATOM_FLOAT;
  466. fAtomForge.Int = CARLA_URI_MAP_ID_ATOM_INT;
  467. fAtomForge.Literal = CARLA_URI_MAP_ID_ATOM_LITERAL;
  468. fAtomForge.Long = CARLA_URI_MAP_ID_ATOM_LONG;
  469. fAtomForge.Object = CARLA_URI_MAP_ID_ATOM_OBJECT;
  470. fAtomForge.Path = CARLA_URI_MAP_ID_ATOM_PATH;
  471. fAtomForge.Property = CARLA_URI_MAP_ID_ATOM_PROPERTY;
  472. fAtomForge.Resource = CARLA_URI_MAP_ID_ATOM_RESOURCE;
  473. fAtomForge.Sequence = CARLA_URI_MAP_ID_ATOM_SEQUENCE;
  474. fAtomForge.String = CARLA_URI_MAP_ID_ATOM_STRING;
  475. fAtomForge.Tuple = CARLA_URI_MAP_ID_ATOM_TUPLE;
  476. fAtomForge.URI = CARLA_URI_MAP_ID_ATOM_URI;
  477. fAtomForge.URID = CARLA_URI_MAP_ID_ATOM_URID;
  478. fAtomForge.Vector = CARLA_URI_MAP_ID_ATOM_VECTOR;
  479. #if defined(__clang__)
  480. # pragma clang diagnostic pop
  481. #elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
  482. # pragma GCC diagnostic pop
  483. #endif
  484. }
  485. ~CarlaPluginLV2() override
  486. {
  487. carla_debug("CarlaPluginLV2::~CarlaPluginLV2()");
  488. // close UI
  489. if (fUI.type != UI::TYPE_NULL)
  490. {
  491. showCustomUI(false);
  492. if (fUI.type == UI::TYPE_BRIDGE)
  493. {
  494. fPipeServer.stopPipeServer(pData->engine->getOptions().uiBridgesTimeout);
  495. }
  496. else
  497. {
  498. if (fFeatures[kFeatureIdUiDataAccess] != nullptr && fFeatures[kFeatureIdUiDataAccess]->data != nullptr)
  499. delete (LV2_Extension_Data_Feature*)fFeatures[kFeatureIdUiDataAccess]->data;
  500. if (fFeatures[kFeatureIdUiPortMap] != nullptr && fFeatures[kFeatureIdUiPortMap]->data != nullptr)
  501. delete (LV2UI_Port_Map*)fFeatures[kFeatureIdUiPortMap]->data;
  502. if (fFeatures[kFeatureIdUiResize] != nullptr && fFeatures[kFeatureIdUiResize]->data != nullptr)
  503. delete (LV2UI_Resize*)fFeatures[kFeatureIdUiResize]->data;
  504. if (fFeatures[kFeatureIdExternalUi] != nullptr && fFeatures[kFeatureIdExternalUi]->data != nullptr)
  505. delete (LV2_External_UI_Host*)fFeatures[kFeatureIdExternalUi]->data;
  506. fUI.descriptor = nullptr;
  507. pData->uiLibClose();
  508. }
  509. #ifndef LV2_UIS_ONLY_BRIDGES
  510. if (fUI.window != nullptr)
  511. {
  512. delete fUI.window;
  513. fUI.window = nullptr;
  514. }
  515. #endif
  516. fUI.rdfDescriptor = nullptr;
  517. }
  518. pData->singleMutex.lock();
  519. pData->masterMutex.lock();
  520. if (pData->client != nullptr && pData->client->isActive())
  521. pData->client->deactivate();
  522. if (pData->active)
  523. {
  524. deactivate();
  525. pData->active = false;
  526. }
  527. if (fDescriptor != nullptr)
  528. {
  529. if (fDescriptor->cleanup != nullptr)
  530. {
  531. if (fHandle != nullptr)
  532. fDescriptor->cleanup(fHandle);
  533. if (fHandle2 != nullptr)
  534. fDescriptor->cleanup(fHandle2);
  535. }
  536. fHandle = nullptr;
  537. fHandle2 = nullptr;
  538. fDescriptor = nullptr;
  539. }
  540. if (fRdfDescriptor != nullptr)
  541. {
  542. delete fRdfDescriptor;
  543. fRdfDescriptor = nullptr;
  544. }
  545. if (fFeatures[kFeatureIdEvent] != nullptr && fFeatures[kFeatureIdEvent]->data != nullptr)
  546. delete (LV2_Event_Feature*)fFeatures[kFeatureIdEvent]->data;
  547. if (fFeatures[kFeatureIdLogs] != nullptr && fFeatures[kFeatureIdLogs]->data != nullptr)
  548. delete (LV2_Log_Log*)fFeatures[kFeatureIdLogs]->data;
  549. if (fFeatures[kFeatureIdStateMakePath] != nullptr && fFeatures[kFeatureIdStateMakePath]->data != nullptr)
  550. delete (LV2_State_Make_Path*)fFeatures[kFeatureIdStateMakePath]->data;
  551. if (fFeatures[kFeatureIdStateMapPath] != nullptr && fFeatures[kFeatureIdStateMapPath]->data != nullptr)
  552. delete (LV2_State_Map_Path*)fFeatures[kFeatureIdStateMapPath]->data;
  553. if (fFeatures[kFeatureIdPrograms] != nullptr && fFeatures[kFeatureIdPrograms]->data != nullptr)
  554. delete (LV2_Programs_Host*)fFeatures[kFeatureIdPrograms]->data;
  555. if (fFeatures[kFeatureIdResizePort] != nullptr && fFeatures[kFeatureIdResizePort]->data != nullptr)
  556. delete (LV2_Resize_Port_Resize*)fFeatures[kFeatureIdResizePort]->data;
  557. if (fFeatures[kFeatureIdRtMemPool] != nullptr && fFeatures[kFeatureIdRtMemPool]->data != nullptr)
  558. delete (LV2_RtMemPool_Pool*)fFeatures[kFeatureIdRtMemPool]->data;
  559. if (fFeatures[kFeatureIdRtMemPoolOld] != nullptr && fFeatures[kFeatureIdRtMemPoolOld]->data != nullptr)
  560. delete (LV2_RtMemPool_Pool_Deprecated*)fFeatures[kFeatureIdRtMemPoolOld]->data;
  561. if (fFeatures[kFeatureIdUriMap] != nullptr && fFeatures[kFeatureIdUriMap]->data != nullptr)
  562. delete (LV2_URI_Map_Feature*)fFeatures[kFeatureIdUriMap]->data;
  563. if (fFeatures[kFeatureIdUridMap] != nullptr && fFeatures[kFeatureIdUridMap]->data != nullptr)
  564. delete (LV2_URID_Map*)fFeatures[kFeatureIdUridMap]->data;
  565. if (fFeatures[kFeatureIdUridUnmap] != nullptr && fFeatures[kFeatureIdUridUnmap]->data != nullptr)
  566. delete (LV2_URID_Unmap*)fFeatures[kFeatureIdUridUnmap]->data;
  567. if (fFeatures[kFeatureIdWorker] != nullptr && fFeatures[kFeatureIdWorker]->data != nullptr)
  568. delete (LV2_Worker_Schedule*)fFeatures[kFeatureIdWorker]->data;
  569. if (fFeatures[kFeatureIdInlineDisplay] != nullptr && fFeatures[kFeatureIdInlineDisplay]->data != nullptr)
  570. delete (LV2_Inline_Display*)fFeatures[kFeatureIdInlineDisplay]->data;
  571. for (uint32_t i=0; i < kFeatureCountAll; ++i)
  572. {
  573. if (fFeatures[i] != nullptr)
  574. {
  575. delete fFeatures[i];
  576. fFeatures[i] = nullptr;
  577. }
  578. }
  579. if (fLastStateChunk != nullptr)
  580. {
  581. std::free(fLastStateChunk);
  582. fLastStateChunk = nullptr;
  583. }
  584. if (fTmpAtomBuffer != nullptr)
  585. {
  586. delete[] fTmpAtomBuffer;
  587. fTmpAtomBuffer = nullptr;
  588. }
  589. clearBuffers();
  590. }
  591. // -------------------------------------------------------------------
  592. // Information (base)
  593. PluginType getType() const noexcept override
  594. {
  595. return PLUGIN_LV2;
  596. }
  597. PluginCategory getCategory() const noexcept override
  598. {
  599. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr, CarlaPlugin::getCategory());
  600. const LV2_Property cat1(fRdfDescriptor->Type[0]);
  601. const LV2_Property cat2(fRdfDescriptor->Type[1]);
  602. if (LV2_IS_DELAY(cat1, cat2))
  603. return PLUGIN_CATEGORY_DELAY;
  604. if (LV2_IS_DISTORTION(cat1, cat2))
  605. return PLUGIN_CATEGORY_OTHER;
  606. if (LV2_IS_DYNAMICS(cat1, cat2))
  607. return PLUGIN_CATEGORY_DYNAMICS;
  608. if (LV2_IS_EQ(cat1, cat2))
  609. return PLUGIN_CATEGORY_EQ;
  610. if (LV2_IS_FILTER(cat1, cat2))
  611. return PLUGIN_CATEGORY_FILTER;
  612. if (LV2_IS_GENERATOR(cat1, cat2))
  613. return PLUGIN_CATEGORY_SYNTH;
  614. if (LV2_IS_MODULATOR(cat1, cat2))
  615. return PLUGIN_CATEGORY_MODULATOR;
  616. if (LV2_IS_REVERB(cat1, cat2))
  617. return PLUGIN_CATEGORY_DELAY;
  618. if (LV2_IS_SIMULATOR(cat1, cat2))
  619. return PLUGIN_CATEGORY_OTHER;
  620. if (LV2_IS_SPATIAL(cat1, cat2))
  621. return PLUGIN_CATEGORY_OTHER;
  622. if (LV2_IS_SPECTRAL(cat1, cat2))
  623. return PLUGIN_CATEGORY_UTILITY;
  624. if (LV2_IS_UTILITY(cat1, cat2))
  625. return PLUGIN_CATEGORY_UTILITY;
  626. return CarlaPlugin::getCategory();
  627. }
  628. uint32_t getLatencyInFrames() const noexcept override
  629. {
  630. if (fLatencyIndex < 0 || fParamBuffers == nullptr)
  631. return 0;
  632. const float latency(fParamBuffers[fLatencyIndex]);
  633. CARLA_SAFE_ASSERT_RETURN(latency >= 0.0f, 0);
  634. return static_cast<uint32_t>(latency);
  635. }
  636. // -------------------------------------------------------------------
  637. // Information (count)
  638. uint32_t getMidiInCount() const noexcept override
  639. {
  640. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr, 0);
  641. uint32_t count = 0;
  642. for (uint32_t i=0; i < fRdfDescriptor->PortCount; ++i)
  643. {
  644. const LV2_Property portTypes(fRdfDescriptor->Ports[i].Types);
  645. if (LV2_IS_PORT_INPUT(portTypes) && LV2_PORT_SUPPORTS_MIDI_EVENT(portTypes))
  646. ++count;
  647. }
  648. return count;
  649. }
  650. uint32_t getMidiOutCount() const noexcept override
  651. {
  652. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr, 0);
  653. uint32_t count = 0;
  654. for (uint32_t i=0; i < fRdfDescriptor->PortCount; ++i)
  655. {
  656. const LV2_Property portTypes(fRdfDescriptor->Ports[i].Types);
  657. if (LV2_IS_PORT_OUTPUT(portTypes) && LV2_PORT_SUPPORTS_MIDI_EVENT(portTypes))
  658. ++count;
  659. }
  660. return count;
  661. }
  662. uint32_t getParameterScalePointCount(const uint32_t parameterId) const noexcept override
  663. {
  664. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr, 0);
  665. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, 0);
  666. const int32_t rindex(pData->param.data[parameterId].rindex);
  667. if (rindex < static_cast<int32_t>(fRdfDescriptor->PortCount))
  668. {
  669. const LV2_RDF_Port* const port(&fRdfDescriptor->Ports[rindex]);
  670. return port->ScalePointCount;
  671. }
  672. return 0;
  673. }
  674. // -------------------------------------------------------------------
  675. // Information (current data)
  676. // nothing
  677. // -------------------------------------------------------------------
  678. // Information (per-plugin data)
  679. uint getOptionsAvailable() const noexcept override
  680. {
  681. uint options = 0x0;
  682. // can't disable fixed buffers if using latency or MIDI output
  683. if (fLatencyIndex == -1 && getMidiOutCount() == 0 && ! fNeedsFixedBuffers)
  684. options |= PLUGIN_OPTION_FIXED_BUFFERS;
  685. // can't disable forced stereo if enabled in the engine
  686. if (pData->engine->getOptions().forceStereo)
  687. pass();
  688. // if inputs or outputs are just 1, then yes we can force stereo
  689. else if ((pData->audioIn.count == 1 || pData->audioOut.count == 1) && fCanInit2)
  690. options |= PLUGIN_OPTION_FORCE_STEREO;
  691. if (fExt.programs != nullptr)
  692. options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  693. if (getMidiInCount() != 0)
  694. {
  695. options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  696. options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  697. options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  698. options |= PLUGIN_OPTION_SEND_PITCHBEND;
  699. options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  700. options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  701. }
  702. return options;
  703. }
  704. float getParameterValue(const uint32_t parameterId) const noexcept override
  705. {
  706. CARLA_SAFE_ASSERT_RETURN(fParamBuffers != nullptr, 0.0f);
  707. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, 0.0f);
  708. if (pData->param.data[parameterId].type == PARAMETER_INPUT)
  709. {
  710. if (pData->param.data[parameterId].hints & PARAMETER_IS_STRICT_BOUNDS)
  711. pData->param.ranges[parameterId].fixValue(fParamBuffers[parameterId]);
  712. }
  713. else
  714. {
  715. if (fStrictBounds >= 0 && (pData->param.data[parameterId].hints & PARAMETER_IS_STRICT_BOUNDS) == 0)
  716. pData->param.ranges[parameterId].fixValue(fParamBuffers[parameterId]);
  717. }
  718. return fParamBuffers[parameterId];
  719. }
  720. float getParameterScalePointValue(const uint32_t parameterId, const uint32_t scalePointId) const noexcept override
  721. {
  722. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr, 0.0f);
  723. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, 0.0f);
  724. const int32_t rindex(pData->param.data[parameterId].rindex);
  725. if (rindex < static_cast<int32_t>(fRdfDescriptor->PortCount))
  726. {
  727. const LV2_RDF_Port* const port(&fRdfDescriptor->Ports[rindex]);
  728. CARLA_SAFE_ASSERT_RETURN(scalePointId < port->ScalePointCount, 0.0f);
  729. const LV2_RDF_PortScalePoint* const portScalePoint(&port->ScalePoints[scalePointId]);
  730. return portScalePoint->Value;
  731. }
  732. return 0.0f;
  733. }
  734. void getLabel(char* const strBuf) const noexcept override
  735. {
  736. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr,);
  737. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor->URI != nullptr,);
  738. std::strncpy(strBuf, fRdfDescriptor->URI, STR_MAX);
  739. }
  740. void getMaker(char* const strBuf) const noexcept override
  741. {
  742. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr,);
  743. if (fRdfDescriptor->Author != nullptr)
  744. std::strncpy(strBuf, fRdfDescriptor->Author, STR_MAX);
  745. else
  746. CarlaPlugin::getMaker(strBuf);
  747. }
  748. void getCopyright(char* const strBuf) const noexcept override
  749. {
  750. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr,);
  751. if (fRdfDescriptor->License != nullptr)
  752. std::strncpy(strBuf, fRdfDescriptor->License, STR_MAX);
  753. else
  754. CarlaPlugin::getCopyright(strBuf);
  755. }
  756. void getRealName(char* const strBuf) const noexcept override
  757. {
  758. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr,);
  759. if (fRdfDescriptor->Name != nullptr)
  760. std::strncpy(strBuf, fRdfDescriptor->Name, STR_MAX);
  761. else
  762. CarlaPlugin::getRealName(strBuf);
  763. }
  764. void getParameterName(const uint32_t parameterId, char* const strBuf) const noexcept override
  765. {
  766. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr,);
  767. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  768. const int32_t rindex(pData->param.data[parameterId].rindex);
  769. if (rindex < static_cast<int32_t>(fRdfDescriptor->PortCount))
  770. std::strncpy(strBuf, fRdfDescriptor->Ports[rindex].Name, STR_MAX);
  771. else
  772. CarlaPlugin::getParameterName(parameterId, strBuf);
  773. }
  774. void getParameterSymbol(const uint32_t parameterId, char* const strBuf) const noexcept override
  775. {
  776. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr,);
  777. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  778. const int32_t rindex(pData->param.data[parameterId].rindex);
  779. if (rindex < static_cast<int32_t>(fRdfDescriptor->PortCount))
  780. std::strncpy(strBuf, fRdfDescriptor->Ports[rindex].Symbol, STR_MAX);
  781. else
  782. CarlaPlugin::getParameterSymbol(parameterId, strBuf);
  783. }
  784. void getParameterUnit(const uint32_t parameterId, char* const strBuf) const noexcept override
  785. {
  786. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr,);
  787. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  788. const int32_t rindex(pData->param.data[parameterId].rindex);
  789. if (rindex < static_cast<int32_t>(fRdfDescriptor->PortCount))
  790. {
  791. const LV2_RDF_Port* const port(&fRdfDescriptor->Ports[rindex]);
  792. if (LV2_HAVE_PORT_UNIT_SYMBOL(port->Unit.Hints) && port->Unit.Symbol != nullptr)
  793. {
  794. std::strncpy(strBuf, port->Unit.Symbol, STR_MAX);
  795. return;
  796. }
  797. if (LV2_HAVE_PORT_UNIT_UNIT(port->Unit.Hints))
  798. {
  799. switch (port->Unit.Unit)
  800. {
  801. case LV2_PORT_UNIT_BAR:
  802. std::strncpy(strBuf, "bars", STR_MAX);
  803. return;
  804. case LV2_PORT_UNIT_BEAT:
  805. std::strncpy(strBuf, "beats", STR_MAX);
  806. return;
  807. case LV2_PORT_UNIT_BPM:
  808. std::strncpy(strBuf, "BPM", STR_MAX);
  809. return;
  810. case LV2_PORT_UNIT_CENT:
  811. std::strncpy(strBuf, "ct", STR_MAX);
  812. return;
  813. case LV2_PORT_UNIT_CM:
  814. std::strncpy(strBuf, "cm", STR_MAX);
  815. return;
  816. case LV2_PORT_UNIT_COEF:
  817. std::strncpy(strBuf, "(coef)", STR_MAX);
  818. return;
  819. case LV2_PORT_UNIT_DB:
  820. std::strncpy(strBuf, "dB", STR_MAX);
  821. return;
  822. case LV2_PORT_UNIT_DEGREE:
  823. std::strncpy(strBuf, "deg", STR_MAX);
  824. return;
  825. case LV2_PORT_UNIT_FRAME:
  826. std::strncpy(strBuf, "frames", STR_MAX);
  827. return;
  828. case LV2_PORT_UNIT_HZ:
  829. std::strncpy(strBuf, "Hz", STR_MAX);
  830. return;
  831. case LV2_PORT_UNIT_INCH:
  832. std::strncpy(strBuf, "in", STR_MAX);
  833. return;
  834. case LV2_PORT_UNIT_KHZ:
  835. std::strncpy(strBuf, "kHz", STR_MAX);
  836. return;
  837. case LV2_PORT_UNIT_KM:
  838. std::strncpy(strBuf, "km", STR_MAX);
  839. return;
  840. case LV2_PORT_UNIT_M:
  841. std::strncpy(strBuf, "m", STR_MAX);
  842. return;
  843. case LV2_PORT_UNIT_MHZ:
  844. std::strncpy(strBuf, "MHz", STR_MAX);
  845. return;
  846. case LV2_PORT_UNIT_MIDINOTE:
  847. std::strncpy(strBuf, "note", STR_MAX);
  848. return;
  849. case LV2_PORT_UNIT_MILE:
  850. std::strncpy(strBuf, "mi", STR_MAX);
  851. return;
  852. case LV2_PORT_UNIT_MIN:
  853. std::strncpy(strBuf, "min", STR_MAX);
  854. return;
  855. case LV2_PORT_UNIT_MM:
  856. std::strncpy(strBuf, "mm", STR_MAX);
  857. return;
  858. case LV2_PORT_UNIT_MS:
  859. std::strncpy(strBuf, "ms", STR_MAX);
  860. return;
  861. case LV2_PORT_UNIT_OCT:
  862. std::strncpy(strBuf, "oct", STR_MAX);
  863. return;
  864. case LV2_PORT_UNIT_PC:
  865. std::strncpy(strBuf, "%", STR_MAX);
  866. return;
  867. case LV2_PORT_UNIT_S:
  868. std::strncpy(strBuf, "s", STR_MAX);
  869. return;
  870. case LV2_PORT_UNIT_SEMITONE:
  871. std::strncpy(strBuf, "semi", STR_MAX);
  872. return;
  873. }
  874. }
  875. }
  876. CarlaPlugin::getParameterUnit(parameterId, strBuf);
  877. }
  878. void getParameterScalePointLabel(const uint32_t parameterId, const uint32_t scalePointId, char* const strBuf) const noexcept override
  879. {
  880. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr,);
  881. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  882. const int32_t rindex(pData->param.data[parameterId].rindex);
  883. if (rindex < static_cast<int32_t>(fRdfDescriptor->PortCount))
  884. {
  885. const LV2_RDF_Port* const port(&fRdfDescriptor->Ports[rindex]);
  886. CARLA_SAFE_ASSERT_RETURN(scalePointId < port->ScalePointCount,);
  887. const LV2_RDF_PortScalePoint* const portScalePoint(&port->ScalePoints[scalePointId]);
  888. if (portScalePoint->Label != nullptr)
  889. {
  890. std::strncpy(strBuf, portScalePoint->Label, STR_MAX);
  891. return;
  892. }
  893. }
  894. CarlaPlugin::getParameterScalePointLabel(parameterId, scalePointId, strBuf);
  895. }
  896. // -------------------------------------------------------------------
  897. // Set data (state)
  898. void prepareForSave() override
  899. {
  900. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr,);
  901. if (fExt.state != nullptr && fExt.state->save != nullptr)
  902. {
  903. fExt.state->save(fHandle, carla_lv2_state_store, this, LV2_STATE_IS_POD, fFeatures);
  904. if (fHandle2 != nullptr)
  905. fExt.state->save(fHandle2, carla_lv2_state_store, this, LV2_STATE_IS_POD, fFeatures);
  906. }
  907. }
  908. // -------------------------------------------------------------------
  909. // Set data (internal stuff)
  910. void setName(const char* const newName) override
  911. {
  912. CarlaPlugin::setName(newName);
  913. if (fLv2Options.windowTitle == nullptr)
  914. return;
  915. CarlaString guiTitle(pData->name);
  916. guiTitle += " (GUI)";
  917. delete[] fLv2Options.windowTitle;
  918. fLv2Options.windowTitle = guiTitle.dup();
  919. fLv2Options.opts[CarlaPluginLV2Options::WindowTitle].size = (uint32_t)std::strlen(fLv2Options.windowTitle);
  920. fLv2Options.opts[CarlaPluginLV2Options::WindowTitle].value = fLv2Options.windowTitle;
  921. if (fFeatures[kFeatureIdExternalUi] != nullptr && fFeatures[kFeatureIdExternalUi]->data != nullptr)
  922. ((LV2_External_UI_Host*)fFeatures[kFeatureIdExternalUi]->data)->plugin_human_id = fLv2Options.windowTitle;
  923. if (fPipeServer.isPipeRunning())
  924. fPipeServer.writeUiTitleMessage(fLv2Options.windowTitle);
  925. #ifndef LV2_UIS_ONLY_BRIDGES
  926. if (fUI.window != nullptr)
  927. fUI.window->setTitle(fLv2Options.windowTitle);
  928. #endif
  929. }
  930. // -------------------------------------------------------------------
  931. // Set data (plugin-specific stuff)
  932. void setParameterValue(const uint32_t parameterId, const float value, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  933. {
  934. CARLA_SAFE_ASSERT_RETURN(fParamBuffers != nullptr,);
  935. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  936. const float fixedValue(pData->param.getFixedValue(parameterId, value));
  937. fParamBuffers[parameterId] = fixedValue;
  938. CarlaPlugin::setParameterValue(parameterId, fixedValue, sendGui, sendOsc, sendCallback);
  939. }
  940. void setCustomData(const char* const type, const char* const key, const char* const value, const bool sendGui) override
  941. {
  942. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr,);
  943. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr,);
  944. CARLA_SAFE_ASSERT_RETURN(type != nullptr && type[0] != '\0',);
  945. CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
  946. CARLA_SAFE_ASSERT_RETURN(value != nullptr,);
  947. carla_debug("CarlaPluginLV2::setCustomData(%s, %s, %s, %s)", type, key, value, bool2str(sendGui));
  948. if (std::strcmp(type, CUSTOM_DATA_TYPE_PROPERTY) == 0)
  949. return CarlaPlugin::setCustomData(type, key, value, sendGui);
  950. // we should only call state restore once
  951. // so inject this in CarlaPlugin::loadSaveState
  952. if (std::strcmp(type, CUSTOM_DATA_TYPE_STRING) == 0 && std::strcmp(key, "CarlaLoadLv2StateNow") == 0 && std::strcmp(value, "true") == 0)
  953. {
  954. if (fExt.state == nullptr)
  955. return;
  956. LV2_State_Status status = LV2_STATE_ERR_UNKNOWN;
  957. {
  958. const ScopedSingleProcessLocker spl(this, true);
  959. try {
  960. status = fExt.state->restore(fHandle, carla_lv2_state_retrieve, this, 0, fFeatures);
  961. } catch(...) {}
  962. if (fHandle2 != nullptr)
  963. {
  964. try {
  965. fExt.state->restore(fHandle, carla_lv2_state_retrieve, this, 0, fFeatures);
  966. } catch(...) {}
  967. }
  968. }
  969. switch (status)
  970. {
  971. case LV2_STATE_SUCCESS:
  972. carla_debug("CarlaPluginLV2::setCustomData(\"%s\", \"%s\", <value>, %s) - success", type, key, bool2str(sendGui));
  973. break;
  974. case LV2_STATE_ERR_UNKNOWN:
  975. carla_stderr("CarlaPluginLV2::setCustomData(\"%s\", \"%s\", <value>, %s) - unknown error", type, key, bool2str(sendGui));
  976. break;
  977. case LV2_STATE_ERR_BAD_TYPE:
  978. carla_stderr("CarlaPluginLV2::setCustomData(\"%s\", \"%s\", <value>, %s) - error, bad type", type, key, bool2str(sendGui));
  979. break;
  980. case LV2_STATE_ERR_BAD_FLAGS:
  981. carla_stderr("CarlaPluginLV2::setCustomData(\"%s\", \"%s\", <value>, %s) - error, bad flags", type, key, bool2str(sendGui));
  982. break;
  983. case LV2_STATE_ERR_NO_FEATURE:
  984. carla_stderr("CarlaPluginLV2::setCustomData(\"%s\", \"%s\", <value>, %s) - error, missing feature", type, key, bool2str(sendGui));
  985. break;
  986. case LV2_STATE_ERR_NO_PROPERTY:
  987. carla_stderr("CarlaPluginLV2::setCustomData(\"%s\", \"%s\", <value>, %s) - error, missing property", type, key, bool2str(sendGui));
  988. break;
  989. case LV2_STATE_ERR_NO_SPACE:
  990. carla_stderr("CarlaPluginLV2::setCustomData(\"%s\", \"%s\", <value>, %s) - error, insufficient space", type, key, bool2str(sendGui));
  991. break;
  992. }
  993. return;
  994. }
  995. CarlaPlugin::setCustomData(type, key, value, sendGui);
  996. }
  997. void setProgram(const int32_t index, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  998. {
  999. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr,);
  1000. CARLA_SAFE_ASSERT_RETURN(index >= -1 && index < static_cast<int32_t>(pData->prog.count),);
  1001. if (index >= 0 && index < static_cast<int32_t>(fRdfDescriptor->PresetCount))
  1002. {
  1003. const LV2_URID_Map* const uridMap = (const LV2_URID_Map*)fFeatures[kFeatureIdUridMap]->data;
  1004. LilvState* const state = Lv2WorldClass::getInstance().getStateFromURI(fRdfDescriptor->Presets[index].URI,
  1005. uridMap);
  1006. CARLA_SAFE_ASSERT_RETURN(state != nullptr,);
  1007. // invalidate midi-program selection
  1008. CarlaPlugin::setMidiProgram(-1, false, false, sendCallback);
  1009. if (fExt.state != nullptr)
  1010. {
  1011. const ScopedSingleProcessLocker spl(this, (sendGui || sendOsc || sendCallback));
  1012. lilv_state_restore(state, fExt.state, fHandle, carla_lilv_set_port_value, this, 0, fFeatures);
  1013. if (fHandle2 != nullptr)
  1014. lilv_state_restore(state, fExt.state, fHandle2, carla_lilv_set_port_value, this, 0, fFeatures);
  1015. }
  1016. else
  1017. {
  1018. lilv_state_emit_port_values(state, carla_lilv_set_port_value, this);
  1019. }
  1020. lilv_state_free(state);
  1021. }
  1022. CarlaPlugin::setProgram(index, sendGui, sendOsc, sendCallback);
  1023. }
  1024. void setMidiProgram(const int32_t index, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  1025. {
  1026. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr,);
  1027. CARLA_SAFE_ASSERT_RETURN(index >= -1 && index < static_cast<int32_t>(pData->midiprog.count),);
  1028. if (index >= 0 && fExt.programs != nullptr && fExt.programs->select_program != nullptr)
  1029. {
  1030. const uint32_t bank(pData->midiprog.data[index].bank);
  1031. const uint32_t program(pData->midiprog.data[index].program);
  1032. const ScopedSingleProcessLocker spl(this, (sendGui || sendOsc || sendCallback));
  1033. try {
  1034. fExt.programs->select_program(fHandle, bank, program);
  1035. } catch(...) {}
  1036. if (fHandle2 != nullptr)
  1037. {
  1038. try {
  1039. fExt.programs->select_program(fHandle2, bank, program);
  1040. } catch(...) {}
  1041. }
  1042. }
  1043. CarlaPlugin::setMidiProgram(index, sendGui, sendOsc, sendCallback);
  1044. }
  1045. // -------------------------------------------------------------------
  1046. // Set ui stuff
  1047. void showCustomUI(const bool yesNo) override
  1048. {
  1049. CARLA_SAFE_ASSERT_RETURN(fUI.type != UI::TYPE_NULL,);
  1050. const uintptr_t frontendWinId(pData->engine->getOptions().frontendWinId);
  1051. if (! yesNo)
  1052. pData->transientTryCounter = 0;
  1053. if (fUI.type == UI::TYPE_BRIDGE)
  1054. {
  1055. if (yesNo)
  1056. {
  1057. if (fPipeServer.isPipeRunning())
  1058. {
  1059. fPipeServer.writeFocusMessage();
  1060. return;
  1061. }
  1062. if (! fPipeServer.startPipeServer(std::min(fLv2Options.sequenceSize, 819200)))
  1063. {
  1064. pData->engine->callback(ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, 0, 0, 0.0f, nullptr);
  1065. return;
  1066. }
  1067. // manually write messages so we can take the lock for ourselves
  1068. {
  1069. char tmpBuf[0xff+1];
  1070. tmpBuf[0xff] = '\0';
  1071. const CarlaMutexLocker cml(fPipeServer.getPipeLock());
  1072. const ScopedLocale csl;
  1073. // write URI mappings
  1074. uint32_t u = 0;
  1075. for (auto it=fCustomURIDs.begin(), end=fCustomURIDs.end(); it != end; ++it, ++u)
  1076. {
  1077. if (u < CARLA_URI_MAP_ID_COUNT)
  1078. continue;
  1079. const std::string& uri(*it);
  1080. std::snprintf(tmpBuf, 0xff, "%u\n", u);
  1081. fPipeServer.writeMessage("urid\n", 5);
  1082. fPipeServer.writeMessage(tmpBuf);
  1083. fPipeServer.writeAndFixMessage(uri.c_str());
  1084. }
  1085. // write UI options
  1086. fPipeServer.writeMessage("uiOptions\n", 10);
  1087. std::snprintf(tmpBuf, 0xff, "%g\n", pData->engine->getSampleRate());
  1088. fPipeServer.writeMessage(tmpBuf);
  1089. std::snprintf(tmpBuf, 0xff, "%s\n", bool2str(true)); // useTheme
  1090. fPipeServer.writeMessage(tmpBuf);
  1091. std::snprintf(tmpBuf, 0xff, "%s\n", bool2str(true)); // useThemeColors
  1092. fPipeServer.writeMessage(tmpBuf);
  1093. fPipeServer.writeAndFixMessage(fLv2Options.windowTitle != nullptr ? fLv2Options.windowTitle : "");
  1094. std::snprintf(tmpBuf, 0xff, P_INTPTR "\n", frontendWinId);
  1095. fPipeServer.writeMessage(tmpBuf);
  1096. // write parameter values
  1097. for (uint32_t i=0; i < pData->param.count; ++i)
  1098. {
  1099. fPipeServer.writeMessage("control\n", 8);
  1100. std::snprintf(tmpBuf, 0xff, "%i\n", pData->param.data[i].rindex);
  1101. fPipeServer.writeMessage(tmpBuf);
  1102. std::snprintf(tmpBuf, 0xff, "%f\n", getParameterValue(i));
  1103. fPipeServer.writeMessage(tmpBuf);
  1104. }
  1105. // ready to show
  1106. fPipeServer.writeMessage("show\n", 5);
  1107. fPipeServer.flushMessages();
  1108. }
  1109. #ifndef BUILD_BRIDGE
  1110. if (fUI.rdfDescriptor->Type == LV2_UI_MOD)
  1111. pData->tryTransient();
  1112. #endif
  1113. }
  1114. else
  1115. {
  1116. fPipeServer.stopPipeServer(pData->engine->getOptions().uiBridgesTimeout);
  1117. }
  1118. return;
  1119. }
  1120. // take some precautions
  1121. CARLA_SAFE_ASSERT_RETURN(fUI.descriptor != nullptr,);
  1122. CARLA_SAFE_ASSERT_RETURN(fUI.rdfDescriptor != nullptr,);
  1123. if (yesNo)
  1124. {
  1125. CARLA_SAFE_ASSERT_RETURN(fUI.descriptor->instantiate != nullptr,);
  1126. CARLA_SAFE_ASSERT_RETURN(fUI.descriptor->cleanup != nullptr,);
  1127. }
  1128. else
  1129. {
  1130. if (fUI.handle == nullptr)
  1131. return;
  1132. }
  1133. if (yesNo)
  1134. {
  1135. if (fUI.handle == nullptr)
  1136. {
  1137. #ifndef LV2_UIS_ONLY_BRIDGES
  1138. if (fUI.type == UI::TYPE_EMBED && fUI.window == nullptr)
  1139. {
  1140. const char* msg = nullptr;
  1141. switch (fUI.rdfDescriptor->Type)
  1142. {
  1143. case LV2_UI_GTK2:
  1144. case LV2_UI_GTK3:
  1145. case LV2_UI_QT4:
  1146. case LV2_UI_QT5:
  1147. case LV2_UI_EXTERNAL:
  1148. case LV2_UI_OLD_EXTERNAL:
  1149. msg = "Invalid UI type";
  1150. break;
  1151. case LV2_UI_COCOA:
  1152. # ifdef CARLA_OS_MAC
  1153. fUI.window = CarlaPluginUI::newCocoa(this, frontendWinId, isUiResizable());
  1154. # else
  1155. msg = "UI is for MacOS only";
  1156. # endif
  1157. break;
  1158. case LV2_UI_WINDOWS:
  1159. # ifdef CARLA_OS_WIN
  1160. fUI.window = CarlaPluginUI::newWindows(this, frontendWinId, isUiResizable());
  1161. # else
  1162. msg = "UI is for Windows only";
  1163. # endif
  1164. break;
  1165. case LV2_UI_X11:
  1166. # ifdef HAVE_X11
  1167. fUI.window = CarlaPluginUI::newX11(this, frontendWinId, isUiResizable());
  1168. # else
  1169. msg = "UI is only for systems with X11";
  1170. # endif
  1171. break;
  1172. default:
  1173. msg = "Unknown UI type";
  1174. break;
  1175. }
  1176. if (fUI.window == nullptr && fExt.uishow == nullptr)
  1177. return pData->engine->callback(ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, -1, 0, 0.0f, msg);
  1178. if (fUI.window != nullptr)
  1179. fFeatures[kFeatureIdUiParent]->data = fUI.window->getPtr();
  1180. }
  1181. #endif
  1182. if (fUI.window != nullptr)
  1183. fUI.window->setTitle(fLv2Options.windowTitle);
  1184. fUI.widget = nullptr;
  1185. fUI.handle = fUI.descriptor->instantiate(fUI.descriptor, fRdfDescriptor->URI, fUI.rdfDescriptor->Bundle,
  1186. carla_lv2_ui_write_function, this, &fUI.widget, fFeatures);
  1187. }
  1188. CARLA_SAFE_ASSERT(fUI.handle != nullptr);
  1189. CARLA_SAFE_ASSERT(fUI.type != UI::TYPE_EXTERNAL || fUI.widget != nullptr);
  1190. if (fUI.handle == nullptr || (fUI.type == UI::TYPE_EXTERNAL && fUI.widget == nullptr))
  1191. {
  1192. fUI.widget = nullptr;
  1193. if (fUI.handle != nullptr)
  1194. {
  1195. fUI.descriptor->cleanup(fUI.handle);
  1196. fUI.handle = nullptr;
  1197. }
  1198. return pData->engine->callback(ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, -1, 0, 0.0f, "Plugin refused to open its own UI");
  1199. }
  1200. updateUi();
  1201. #ifndef LV2_UIS_ONLY_BRIDGES
  1202. if (fUI.type == UI::TYPE_EMBED)
  1203. {
  1204. if (fUI.window != nullptr)
  1205. {
  1206. fUI.window->show();
  1207. }
  1208. else if (fExt.uishow != nullptr)
  1209. {
  1210. fExt.uishow->show(fUI.handle);
  1211. # ifndef BUILD_BRIDGE
  1212. pData->tryTransient();
  1213. # endif
  1214. }
  1215. }
  1216. else
  1217. #endif
  1218. {
  1219. LV2_EXTERNAL_UI_SHOW((LV2_External_UI_Widget*)fUI.widget);
  1220. #ifndef BUILD_BRIDGE
  1221. pData->tryTransient();
  1222. #endif
  1223. }
  1224. }
  1225. else
  1226. {
  1227. #ifndef LV2_UIS_ONLY_BRIDGES
  1228. if (fUI.type == UI::TYPE_EMBED)
  1229. {
  1230. if (fUI.window != nullptr)
  1231. fUI.window->hide();
  1232. else if (fExt.uishow != nullptr)
  1233. fExt.uishow->hide(fUI.handle);
  1234. }
  1235. else
  1236. #endif
  1237. {
  1238. CARLA_SAFE_ASSERT(fUI.widget != nullptr);
  1239. if (fUI.widget != nullptr)
  1240. LV2_EXTERNAL_UI_HIDE((LV2_External_UI_Widget*)fUI.widget);
  1241. }
  1242. fUI.descriptor->cleanup(fUI.handle);
  1243. fUI.handle = nullptr;
  1244. fUI.widget = nullptr;
  1245. }
  1246. }
  1247. void uiIdle() override
  1248. {
  1249. if (fAtomBufferOut.isDataAvailableForReading())
  1250. {
  1251. Lv2AtomRingBuffer tmpRingBuffer(fAtomBufferOut, fTmpAtomBuffer);
  1252. CARLA_SAFE_ASSERT(tmpRingBuffer.isDataAvailableForReading());
  1253. uint32_t portIndex;
  1254. const LV2_Atom* atom;
  1255. const bool hasPortEvent(fUI.handle != nullptr && fUI.descriptor != nullptr &&
  1256. fUI.descriptor->port_event != nullptr && ! fNeedsUiClose);
  1257. for (; tmpRingBuffer.get(atom, portIndex);)
  1258. {
  1259. if (atom->type == CARLA_URI_MAP_ID_CARLA_ATOM_WORKER)
  1260. {
  1261. CARLA_SAFE_ASSERT_CONTINUE(fExt.worker != nullptr && fExt.worker->work != nullptr);
  1262. fExt.worker->work(fHandle, carla_lv2_worker_respond, this, atom->size, LV2_ATOM_BODY_CONST(atom));
  1263. }
  1264. else if (fUI.type == UI::TYPE_BRIDGE)
  1265. {
  1266. if (fPipeServer.isPipeRunning())
  1267. fPipeServer.writeLv2AtomMessage(portIndex, atom);
  1268. }
  1269. else
  1270. {
  1271. if (hasPortEvent)
  1272. fUI.descriptor->port_event(fUI.handle, portIndex, lv2_atom_total_size(atom), CARLA_URI_MAP_ID_ATOM_TRANSFER_EVENT, atom);
  1273. }
  1274. }
  1275. }
  1276. if (fPipeServer.isPipeRunning())
  1277. {
  1278. fPipeServer.idlePipe();
  1279. switch (fPipeServer.getAndResetUiState())
  1280. {
  1281. case CarlaPipeServerLV2::UiNone:
  1282. case CarlaPipeServerLV2::UiShow:
  1283. break;
  1284. case CarlaPipeServerLV2::UiHide:
  1285. fPipeServer.stopPipeServer(2000);
  1286. // nobreak
  1287. case CarlaPipeServerLV2::UiCrashed:
  1288. pData->transientTryCounter = 0;
  1289. pData->engine->callback(ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, 0, 0, 0.0f, nullptr);
  1290. break;
  1291. }
  1292. }
  1293. else
  1294. {
  1295. // TODO - detect if ui-bridge crashed
  1296. }
  1297. if (fNeedsUiClose)
  1298. {
  1299. fNeedsUiClose = false;
  1300. showCustomUI(false);
  1301. pData->engine->callback(ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, 0, 0, 0.0f, nullptr);
  1302. }
  1303. else if (fUI.handle != nullptr && fUI.descriptor != nullptr)
  1304. {
  1305. if (fUI.type == UI::TYPE_EXTERNAL && fUI.widget != nullptr)
  1306. LV2_EXTERNAL_UI_RUN((LV2_External_UI_Widget*)fUI.widget);
  1307. #ifndef LV2_UIS_ONLY_BRIDGES
  1308. else if (fUI.type == UI::TYPE_EMBED && fUI.window != nullptr)
  1309. fUI.window->idle();
  1310. // note: UI might have been closed by window idle
  1311. if (fNeedsUiClose)
  1312. pass();
  1313. else if (fUI.handle != nullptr && fExt.uiidle != nullptr && fExt.uiidle->idle(fUI.handle) != 0)
  1314. {
  1315. showCustomUI(false);
  1316. pData->engine->callback(ENGINE_CALLBACK_UI_STATE_CHANGED, pData->id, 0, 0, 0.0f, nullptr);
  1317. CARLA_SAFE_ASSERT(fUI.handle == nullptr);
  1318. }
  1319. #endif
  1320. }
  1321. CarlaPlugin::uiIdle();
  1322. }
  1323. // -------------------------------------------------------------------
  1324. // Plugin state
  1325. void reload() override
  1326. {
  1327. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  1328. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr,);
  1329. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr,);
  1330. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr,);
  1331. carla_debug("CarlaPluginLV2::reload() - start");
  1332. const EngineProcessMode processMode(pData->engine->getProccessMode());
  1333. // Safely disable plugin for reload
  1334. const ScopedDisabler sd(this);
  1335. if (pData->active)
  1336. deactivate();
  1337. clearBuffers();
  1338. const float sampleRate(static_cast<float>(pData->engine->getSampleRate()));
  1339. const uint32_t portCount(fRdfDescriptor->PortCount);
  1340. uint32_t aIns, aOuts, cvIns, cvOuts, params;
  1341. aIns = aOuts = cvIns = cvOuts = params = 0;
  1342. LinkedList<uint> evIns, evOuts;
  1343. const uint32_t eventBufferSize(static_cast<uint32_t>(fLv2Options.sequenceSize)+0xff);
  1344. bool forcedStereoIn, forcedStereoOut;
  1345. forcedStereoIn = forcedStereoOut = false;
  1346. bool needsCtrlIn, needsCtrlOut;
  1347. needsCtrlIn = needsCtrlOut = false;
  1348. for (uint32_t i=0; i < portCount; ++i)
  1349. {
  1350. const LV2_Property portTypes(fRdfDescriptor->Ports[i].Types);
  1351. if (LV2_IS_PORT_AUDIO(portTypes))
  1352. {
  1353. if (LV2_IS_PORT_INPUT(portTypes))
  1354. aIns += 1;
  1355. else if (LV2_IS_PORT_OUTPUT(portTypes))
  1356. aOuts += 1;
  1357. }
  1358. else if (LV2_IS_PORT_CV(portTypes))
  1359. {
  1360. if (LV2_IS_PORT_INPUT(portTypes))
  1361. cvIns += 1;
  1362. else if (LV2_IS_PORT_OUTPUT(portTypes))
  1363. cvOuts += 1;
  1364. }
  1365. else if (LV2_IS_PORT_ATOM_SEQUENCE(portTypes))
  1366. {
  1367. if (LV2_IS_PORT_INPUT(portTypes))
  1368. evIns.append(CARLA_EVENT_DATA_ATOM);
  1369. else if (LV2_IS_PORT_OUTPUT(portTypes))
  1370. evOuts.append(CARLA_EVENT_DATA_ATOM);
  1371. }
  1372. else if (LV2_IS_PORT_EVENT(portTypes))
  1373. {
  1374. if (LV2_IS_PORT_INPUT(portTypes))
  1375. evIns.append(CARLA_EVENT_DATA_EVENT);
  1376. else if (LV2_IS_PORT_OUTPUT(portTypes))
  1377. evOuts.append(CARLA_EVENT_DATA_EVENT);
  1378. }
  1379. else if (LV2_IS_PORT_MIDI_LL(portTypes))
  1380. {
  1381. if (LV2_IS_PORT_INPUT(portTypes))
  1382. evIns.append(CARLA_EVENT_DATA_MIDI_LL);
  1383. else if (LV2_IS_PORT_OUTPUT(portTypes))
  1384. evOuts.append(CARLA_EVENT_DATA_MIDI_LL);
  1385. }
  1386. else if (LV2_IS_PORT_CONTROL(portTypes))
  1387. params += 1;
  1388. }
  1389. if ((pData->options & PLUGIN_OPTION_FORCE_STEREO) != 0 && aIns <= 1 && aOuts <= 1 && fExt.state == nullptr && fExt.worker == nullptr)
  1390. {
  1391. if (fHandle2 == nullptr)
  1392. {
  1393. try {
  1394. fHandle2 = fDescriptor->instantiate(fDescriptor, sampleRate, fRdfDescriptor->Bundle, fFeatures);
  1395. } catch(...) {}
  1396. }
  1397. if (fHandle2 != nullptr)
  1398. {
  1399. if (aIns == 1)
  1400. {
  1401. aIns = 2;
  1402. forcedStereoIn = true;
  1403. }
  1404. if (aOuts == 1)
  1405. {
  1406. aOuts = 2;
  1407. forcedStereoOut = true;
  1408. }
  1409. }
  1410. }
  1411. if (aIns > 0)
  1412. {
  1413. pData->audioIn.createNew(aIns);
  1414. fAudioInBuffers = new float*[aIns];
  1415. for (uint32_t i=0; i < aIns; ++i)
  1416. fAudioInBuffers[i] = nullptr;
  1417. }
  1418. if (aOuts > 0)
  1419. {
  1420. pData->audioOut.createNew(aOuts);
  1421. fAudioOutBuffers = new float*[aOuts];
  1422. needsCtrlIn = true;
  1423. for (uint32_t i=0; i < aOuts; ++i)
  1424. fAudioOutBuffers[i] = nullptr;
  1425. }
  1426. if (cvIns > 0)
  1427. {
  1428. pData->cvIn.createNew(cvIns);
  1429. fCvInBuffers = new float*[cvIns];
  1430. for (uint32_t i=0; i < cvIns; ++i)
  1431. fCvInBuffers[i] = nullptr;
  1432. }
  1433. if (cvOuts > 0)
  1434. {
  1435. pData->cvOut.createNew(cvOuts);
  1436. fCvOutBuffers = new float*[cvOuts];
  1437. for (uint32_t i=0; i < cvOuts; ++i)
  1438. fCvOutBuffers[i] = nullptr;
  1439. }
  1440. if (params > 0)
  1441. {
  1442. pData->param.createNew(params, true);
  1443. fParamBuffers = new float[params];
  1444. FloatVectorOperations::clear(fParamBuffers, static_cast<int>(params));
  1445. }
  1446. if (const uint32_t count = static_cast<uint32_t>(evIns.count()))
  1447. {
  1448. fEventsIn.createNew(count);
  1449. for (uint32_t i=0; i < count; ++i)
  1450. {
  1451. const uint32_t& type(evIns.getAt(i, 0x0));
  1452. if (type == CARLA_EVENT_DATA_ATOM)
  1453. {
  1454. fEventsIn.data[i].type = CARLA_EVENT_DATA_ATOM;
  1455. fEventsIn.data[i].atom = lv2_atom_buffer_new(eventBufferSize, CARLA_URI_MAP_ID_NULL, CARLA_URI_MAP_ID_ATOM_SEQUENCE, true);
  1456. }
  1457. else if (type == CARLA_EVENT_DATA_EVENT)
  1458. {
  1459. fEventsIn.data[i].type = CARLA_EVENT_DATA_EVENT;
  1460. fEventsIn.data[i].event = lv2_event_buffer_new(eventBufferSize, LV2_EVENT_AUDIO_STAMP);
  1461. }
  1462. else if (type == CARLA_EVENT_DATA_MIDI_LL)
  1463. {
  1464. fEventsIn.data[i].type = CARLA_EVENT_DATA_MIDI_LL;
  1465. fEventsIn.data[i].midi.capacity = eventBufferSize;
  1466. fEventsIn.data[i].midi.data = new uchar[eventBufferSize];
  1467. }
  1468. }
  1469. }
  1470. else
  1471. {
  1472. fEventsIn.createNew(1);
  1473. fEventsIn.ctrl = &fEventsIn.data[0];
  1474. }
  1475. if (const uint32_t count = static_cast<uint32_t>(evOuts.count()))
  1476. {
  1477. fEventsOut.createNew(count);
  1478. for (uint32_t i=0; i < count; ++i)
  1479. {
  1480. const uint32_t& type(evOuts.getAt(i, 0x0));
  1481. if (type == CARLA_EVENT_DATA_ATOM)
  1482. {
  1483. fEventsOut.data[i].type = CARLA_EVENT_DATA_ATOM;
  1484. fEventsOut.data[i].atom = lv2_atom_buffer_new(eventBufferSize, CARLA_URI_MAP_ID_NULL, CARLA_URI_MAP_ID_ATOM_SEQUENCE, false);
  1485. }
  1486. else if (type == CARLA_EVENT_DATA_EVENT)
  1487. {
  1488. fEventsOut.data[i].type = CARLA_EVENT_DATA_EVENT;
  1489. fEventsOut.data[i].event = lv2_event_buffer_new(eventBufferSize, LV2_EVENT_AUDIO_STAMP);
  1490. }
  1491. else if (type == CARLA_EVENT_DATA_MIDI_LL)
  1492. {
  1493. fEventsOut.data[i].type = CARLA_EVENT_DATA_MIDI_LL;
  1494. fEventsOut.data[i].midi.capacity = eventBufferSize;
  1495. fEventsOut.data[i].midi.data = new uchar[eventBufferSize];
  1496. }
  1497. }
  1498. }
  1499. const uint portNameSize(pData->engine->getMaxPortNameSize());
  1500. CarlaString portName;
  1501. for (uint32_t i=0, iAudioIn=0, iAudioOut=0, iCvIn=0, iCvOut=0, iEvIn=0, iEvOut=0, iCtrl=0; i < portCount; ++i)
  1502. {
  1503. const LV2_Property portTypes(fRdfDescriptor->Ports[i].Types);
  1504. portName.clear();
  1505. 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))
  1506. {
  1507. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1508. {
  1509. portName = pData->name;
  1510. portName += ":";
  1511. }
  1512. portName += fRdfDescriptor->Ports[i].Name;
  1513. portName.truncate(portNameSize);
  1514. }
  1515. if (LV2_IS_PORT_AUDIO(portTypes))
  1516. {
  1517. if (LV2_IS_PORT_INPUT(portTypes))
  1518. {
  1519. const uint32_t j = iAudioIn++;
  1520. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true, j);
  1521. pData->audioIn.ports[j].rindex = i;
  1522. if (forcedStereoIn)
  1523. {
  1524. portName += "_2";
  1525. pData->audioIn.ports[1].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true, 1);
  1526. pData->audioIn.ports[1].rindex = i;
  1527. }
  1528. }
  1529. else if (LV2_IS_PORT_OUTPUT(portTypes))
  1530. {
  1531. const uint32_t j = iAudioOut++;
  1532. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, j);
  1533. pData->audioOut.ports[j].rindex = i;
  1534. if (forcedStereoOut)
  1535. {
  1536. portName += "_2";
  1537. pData->audioOut.ports[1].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, 1);
  1538. pData->audioOut.ports[1].rindex = i;
  1539. }
  1540. }
  1541. else
  1542. carla_stderr2("WARNING - Got a broken Port (Audio, but not input or output)");
  1543. }
  1544. else if (LV2_IS_PORT_CV(portTypes))
  1545. {
  1546. if (LV2_IS_PORT_INPUT(portTypes))
  1547. {
  1548. const uint32_t j = iCvIn++;
  1549. pData->cvIn.ports[j].port = (CarlaEngineCVPort*)pData->client->addPort(kEnginePortTypeCV, portName, true, j);
  1550. pData->cvIn.ports[j].rindex = i;
  1551. }
  1552. else if (LV2_IS_PORT_OUTPUT(portTypes))
  1553. {
  1554. const uint32_t j = iCvOut++;
  1555. pData->cvOut.ports[j].port = (CarlaEngineCVPort*)pData->client->addPort(kEnginePortTypeCV, portName, false, j);
  1556. pData->cvOut.ports[j].rindex = i;
  1557. }
  1558. else
  1559. carla_stderr("WARNING - Got a broken Port (CV, but not input or output)");
  1560. }
  1561. else if (LV2_IS_PORT_ATOM_SEQUENCE(portTypes))
  1562. {
  1563. if (LV2_IS_PORT_INPUT(portTypes))
  1564. {
  1565. const uint32_t j = iEvIn++;
  1566. fDescriptor->connect_port(fHandle, i, &fEventsIn.data[j].atom->atoms);
  1567. if (fHandle2 != nullptr)
  1568. fDescriptor->connect_port(fHandle2, i, &fEventsIn.data[j].atom->atoms);
  1569. fEventsIn.data[j].rindex = i;
  1570. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  1571. fEventsIn.data[j].type |= CARLA_EVENT_TYPE_MIDI;
  1572. if (portTypes & LV2_PORT_DATA_PATCH_MESSAGE)
  1573. fEventsIn.data[j].type |= CARLA_EVENT_TYPE_MESSAGE;
  1574. if (portTypes & LV2_PORT_DATA_TIME_POSITION)
  1575. fEventsIn.data[j].type |= CARLA_EVENT_TYPE_TIME;
  1576. if (evIns.count() == 1)
  1577. {
  1578. fEventsIn.ctrl = &fEventsIn.data[j];
  1579. fEventsIn.ctrlIndex = j;
  1580. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  1581. needsCtrlIn = true;
  1582. }
  1583. else
  1584. {
  1585. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  1586. fEventsIn.data[j].port = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, j);
  1587. if (LV2_IS_PORT_DESIGNATION_CONTROL(fRdfDescriptor->Ports[i].Designation))
  1588. {
  1589. fEventsIn.ctrl = &fEventsIn.data[j];
  1590. fEventsIn.ctrlIndex = j;
  1591. }
  1592. }
  1593. }
  1594. else if (LV2_IS_PORT_OUTPUT(portTypes))
  1595. {
  1596. const uint32_t j = iEvOut++;
  1597. fDescriptor->connect_port(fHandle, i, &fEventsOut.data[j].atom->atoms);
  1598. if (fHandle2 != nullptr)
  1599. fDescriptor->connect_port(fHandle2, i, &fEventsOut.data[j].atom->atoms);
  1600. fEventsOut.data[j].rindex = i;
  1601. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  1602. fEventsOut.data[j].type |= CARLA_EVENT_TYPE_MIDI;
  1603. if (portTypes & LV2_PORT_DATA_PATCH_MESSAGE)
  1604. fEventsOut.data[j].type |= CARLA_EVENT_TYPE_MESSAGE;
  1605. if (portTypes & LV2_PORT_DATA_TIME_POSITION)
  1606. fEventsOut.data[j].type |= CARLA_EVENT_TYPE_TIME;
  1607. if (evOuts.count() == 1)
  1608. {
  1609. fEventsOut.ctrl = &fEventsOut.data[j];
  1610. fEventsOut.ctrlIndex = j;
  1611. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  1612. needsCtrlOut = true;
  1613. }
  1614. else
  1615. {
  1616. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  1617. fEventsOut.data[j].port = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, j);
  1618. if (LV2_IS_PORT_DESIGNATION_CONTROL(fRdfDescriptor->Ports[i].Designation))
  1619. {
  1620. fEventsOut.ctrl = &fEventsOut.data[j];
  1621. fEventsOut.ctrlIndex = j;
  1622. }
  1623. }
  1624. }
  1625. else
  1626. carla_stderr2("WARNING - Got a broken Port (Atom-Sequence, but not input or output)");
  1627. }
  1628. else if (LV2_IS_PORT_EVENT(portTypes))
  1629. {
  1630. if (LV2_IS_PORT_INPUT(portTypes))
  1631. {
  1632. const uint32_t j = iEvIn++;
  1633. fDescriptor->connect_port(fHandle, i, fEventsIn.data[j].event);
  1634. if (fHandle2 != nullptr)
  1635. fDescriptor->connect_port(fHandle2, i, fEventsIn.data[j].event);
  1636. fEventsIn.data[j].rindex = i;
  1637. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  1638. fEventsIn.data[j].type |= CARLA_EVENT_TYPE_MIDI;
  1639. if (portTypes & LV2_PORT_DATA_PATCH_MESSAGE)
  1640. fEventsIn.data[j].type |= CARLA_EVENT_TYPE_MESSAGE;
  1641. if (portTypes & LV2_PORT_DATA_TIME_POSITION)
  1642. fEventsIn.data[j].type |= CARLA_EVENT_TYPE_TIME;
  1643. if (evIns.count() == 1)
  1644. {
  1645. fEventsIn.ctrl = &fEventsIn.data[j];
  1646. fEventsIn.ctrlIndex = j;
  1647. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  1648. needsCtrlIn = true;
  1649. }
  1650. else
  1651. {
  1652. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  1653. fEventsIn.data[j].port = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, j);
  1654. if (LV2_IS_PORT_DESIGNATION_CONTROL(fRdfDescriptor->Ports[i].Designation))
  1655. {
  1656. fEventsIn.ctrl = &fEventsIn.data[j];
  1657. fEventsIn.ctrlIndex = j;
  1658. }
  1659. }
  1660. }
  1661. else if (LV2_IS_PORT_OUTPUT(portTypes))
  1662. {
  1663. const uint32_t j = iEvOut++;
  1664. fDescriptor->connect_port(fHandle, i, fEventsOut.data[j].event);
  1665. if (fHandle2 != nullptr)
  1666. fDescriptor->connect_port(fHandle2, i, fEventsOut.data[j].event);
  1667. fEventsOut.data[j].rindex = i;
  1668. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  1669. fEventsOut.data[j].type |= CARLA_EVENT_TYPE_MIDI;
  1670. if (portTypes & LV2_PORT_DATA_PATCH_MESSAGE)
  1671. fEventsOut.data[j].type |= CARLA_EVENT_TYPE_MESSAGE;
  1672. if (portTypes & LV2_PORT_DATA_TIME_POSITION)
  1673. fEventsOut.data[j].type |= CARLA_EVENT_TYPE_TIME;
  1674. if (evOuts.count() == 1)
  1675. {
  1676. fEventsOut.ctrl = &fEventsOut.data[j];
  1677. fEventsOut.ctrlIndex = j;
  1678. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  1679. needsCtrlOut = true;
  1680. }
  1681. else
  1682. {
  1683. if (portTypes & LV2_PORT_DATA_MIDI_EVENT)
  1684. fEventsOut.data[j].port = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, j);
  1685. if (LV2_IS_PORT_DESIGNATION_CONTROL(fRdfDescriptor->Ports[i].Designation))
  1686. {
  1687. fEventsOut.ctrl = &fEventsOut.data[j];
  1688. fEventsOut.ctrlIndex = j;
  1689. }
  1690. }
  1691. }
  1692. else
  1693. carla_stderr2("WARNING - Got a broken Port (Event, but not input or output)");
  1694. }
  1695. else if (LV2_IS_PORT_MIDI_LL(portTypes))
  1696. {
  1697. if (LV2_IS_PORT_INPUT(portTypes))
  1698. {
  1699. const uint32_t j = iEvIn++;
  1700. fDescriptor->connect_port(fHandle, i, &fEventsIn.data[j].midi);
  1701. if (fHandle2 != nullptr)
  1702. fDescriptor->connect_port(fHandle2, i, &fEventsIn.data[j].midi);
  1703. fEventsIn.data[j].type |= CARLA_EVENT_TYPE_MIDI;
  1704. fEventsIn.data[j].rindex = i;
  1705. if (evIns.count() == 1)
  1706. {
  1707. needsCtrlIn = true;
  1708. fEventsIn.ctrl = &fEventsIn.data[j];
  1709. fEventsIn.ctrlIndex = j;
  1710. }
  1711. else
  1712. {
  1713. fEventsIn.data[j].port = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, j);
  1714. if (LV2_IS_PORT_DESIGNATION_CONTROL(fRdfDescriptor->Ports[i].Designation))
  1715. {
  1716. fEventsIn.ctrl = &fEventsIn.data[j];
  1717. fEventsIn.ctrlIndex = j;
  1718. }
  1719. }
  1720. }
  1721. else if (LV2_IS_PORT_OUTPUT(portTypes))
  1722. {
  1723. const uint32_t j = iEvOut++;
  1724. fDescriptor->connect_port(fHandle, i, &fEventsOut.data[j].midi);
  1725. if (fHandle2 != nullptr)
  1726. fDescriptor->connect_port(fHandle2, i, &fEventsOut.data[j].midi);
  1727. fEventsOut.data[j].type |= CARLA_EVENT_TYPE_MIDI;
  1728. fEventsOut.data[j].rindex = i;
  1729. if (evOuts.count() == 1)
  1730. {
  1731. needsCtrlOut = true;
  1732. fEventsOut.ctrl = &fEventsOut.data[j];
  1733. fEventsOut.ctrlIndex = j;
  1734. }
  1735. else
  1736. {
  1737. fEventsOut.data[j].port = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, j);
  1738. if (LV2_IS_PORT_DESIGNATION_CONTROL(fRdfDescriptor->Ports[i].Designation))
  1739. {
  1740. fEventsOut.ctrl = &fEventsOut.data[j];
  1741. fEventsOut.ctrlIndex = j;
  1742. }
  1743. }
  1744. }
  1745. else
  1746. carla_stderr2("WARNING - Got a broken Port (MIDI, but not input or output)");
  1747. }
  1748. else if (LV2_IS_PORT_CONTROL(portTypes))
  1749. {
  1750. const LV2_Property portProps(fRdfDescriptor->Ports[i].Properties);
  1751. const LV2_Property portDesignation(fRdfDescriptor->Ports[i].Designation);
  1752. const LV2_RDF_PortPoints portPoints(fRdfDescriptor->Ports[i].Points);
  1753. const uint32_t j = iCtrl++;
  1754. pData->param.data[j].index = static_cast<int32_t>(j);
  1755. pData->param.data[j].rindex = static_cast<int32_t>(i);
  1756. float min, max, def, step, stepSmall, stepLarge;
  1757. // min value
  1758. if (LV2_HAVE_MINIMUM_PORT_POINT(portPoints.Hints))
  1759. min = portPoints.Minimum;
  1760. else
  1761. min = 0.0f;
  1762. // max value
  1763. if (LV2_HAVE_MAXIMUM_PORT_POINT(portPoints.Hints))
  1764. max = portPoints.Maximum;
  1765. else
  1766. max = 1.0f;
  1767. if (LV2_IS_PORT_SAMPLE_RATE(portProps))
  1768. {
  1769. min *= sampleRate;
  1770. max *= sampleRate;
  1771. pData->param.data[j].hints |= PARAMETER_USES_SAMPLERATE;
  1772. }
  1773. // stupid hack for ir.lv2 (broken plugin)
  1774. if (std::strcmp(fRdfDescriptor->URI, "http://factorial.hu/plugins/lv2/ir") == 0 && std::strncmp(fRdfDescriptor->Ports[i].Name, "FileHash", 8) == 0)
  1775. {
  1776. min = 0.0f;
  1777. max = (float)0xffffff;
  1778. }
  1779. if (min >= max)
  1780. {
  1781. carla_stderr2("WARNING - Broken plugin parameter '%s': min >= max", fRdfDescriptor->Ports[i].Name);
  1782. max = min + 0.1f;
  1783. }
  1784. // default value
  1785. if (LV2_HAVE_DEFAULT_PORT_POINT(portPoints.Hints))
  1786. {
  1787. def = portPoints.Default;
  1788. }
  1789. else
  1790. {
  1791. // no default value
  1792. if (min < 0.0f && max > 0.0f)
  1793. def = 0.0f;
  1794. else
  1795. def = min;
  1796. }
  1797. if (def < min)
  1798. def = min;
  1799. else if (def > max)
  1800. def = max;
  1801. if (LV2_IS_PORT_TOGGLED(portProps))
  1802. {
  1803. step = max - min;
  1804. stepSmall = step;
  1805. stepLarge = step;
  1806. pData->param.data[j].hints |= PARAMETER_IS_BOOLEAN;
  1807. }
  1808. else if (LV2_IS_PORT_INTEGER(portProps))
  1809. {
  1810. step = 1.0f;
  1811. stepSmall = 1.0f;
  1812. stepLarge = 10.0f;
  1813. pData->param.data[j].hints |= PARAMETER_IS_INTEGER;
  1814. }
  1815. else
  1816. {
  1817. float range = max - min;
  1818. step = range/100.0f;
  1819. stepSmall = range/1000.0f;
  1820. stepLarge = range/10.0f;
  1821. }
  1822. if (LV2_IS_PORT_INPUT(portTypes))
  1823. {
  1824. pData->param.data[j].type = PARAMETER_INPUT;
  1825. if (LV2_IS_PORT_DESIGNATION_LATENCY(portDesignation))
  1826. {
  1827. carla_stderr("Plugin has latency input port, this should not happen!");
  1828. }
  1829. else if (LV2_IS_PORT_DESIGNATION_SAMPLE_RATE(portDesignation))
  1830. {
  1831. def = sampleRate;
  1832. step = 1.0f;
  1833. stepSmall = 1.0f;
  1834. stepLarge = 1.0f;
  1835. pData->param.special[j] = PARAMETER_SPECIAL_SAMPLE_RATE;
  1836. }
  1837. else if (LV2_IS_PORT_DESIGNATION_FREEWHEELING(portDesignation))
  1838. {
  1839. pData->param.special[j] = PARAMETER_SPECIAL_FREEWHEEL;
  1840. }
  1841. else if (LV2_IS_PORT_DESIGNATION_TIME(portDesignation))
  1842. {
  1843. pData->param.special[j] = PARAMETER_SPECIAL_TIME;
  1844. }
  1845. else
  1846. {
  1847. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  1848. pData->param.data[j].hints |= PARAMETER_IS_AUTOMABLE;
  1849. needsCtrlIn = true;
  1850. }
  1851. // MIDI CC value
  1852. const LV2_RDF_PortMidiMap& portMidiMap(fRdfDescriptor->Ports[i].MidiMap);
  1853. if (LV2_IS_PORT_MIDI_MAP_CC(portMidiMap.Type))
  1854. {
  1855. if (portMidiMap.Number < MAX_MIDI_CONTROL && ! MIDI_IS_CONTROL_BANK_SELECT(portMidiMap.Number))
  1856. pData->param.data[j].midiCC = static_cast<int16_t>(portMidiMap.Number);
  1857. }
  1858. }
  1859. else if (LV2_IS_PORT_OUTPUT(portTypes))
  1860. {
  1861. pData->param.data[j].type = PARAMETER_OUTPUT;
  1862. if (LV2_IS_PORT_DESIGNATION_LATENCY(portDesignation))
  1863. {
  1864. min = 0.0f;
  1865. max = sampleRate;
  1866. def = 0.0f;
  1867. step = 1.0f;
  1868. stepSmall = 1.0f;
  1869. stepLarge = 1.0f;
  1870. pData->param.special[j] = PARAMETER_SPECIAL_LATENCY;
  1871. CARLA_SAFE_ASSERT_INT2(fLatencyIndex == static_cast<int32_t>(j), fLatencyIndex, j);
  1872. }
  1873. else if (LV2_IS_PORT_DESIGNATION_SAMPLE_RATE(portDesignation))
  1874. {
  1875. def = sampleRate;
  1876. step = 1.0f;
  1877. stepSmall = 1.0f;
  1878. stepLarge = 1.0f;
  1879. pData->param.special[j] = PARAMETER_SPECIAL_SAMPLE_RATE;
  1880. }
  1881. else if (LV2_IS_PORT_DESIGNATION_FREEWHEELING(portDesignation))
  1882. {
  1883. carla_stderr("Plugin has freewheeling output port, this should not happen!");
  1884. }
  1885. else if (LV2_IS_PORT_DESIGNATION_TIME(portDesignation))
  1886. {
  1887. pData->param.special[j] = PARAMETER_SPECIAL_TIME;
  1888. }
  1889. else
  1890. {
  1891. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  1892. pData->param.data[j].hints |= PARAMETER_IS_AUTOMABLE;
  1893. needsCtrlOut = true;
  1894. }
  1895. }
  1896. else
  1897. {
  1898. pData->param.data[j].type = PARAMETER_UNKNOWN;
  1899. carla_stderr2("WARNING - Got a broken Port (Control, but not input or output)");
  1900. }
  1901. // extra parameter hints
  1902. if (LV2_IS_PORT_LOGARITHMIC(portProps))
  1903. pData->param.data[j].hints |= PARAMETER_IS_LOGARITHMIC;
  1904. if (LV2_IS_PORT_TRIGGER(portProps))
  1905. pData->param.data[j].hints |= PARAMETER_IS_TRIGGER;
  1906. if (LV2_IS_PORT_STRICT_BOUNDS(portProps))
  1907. pData->param.data[j].hints |= PARAMETER_IS_STRICT_BOUNDS;
  1908. if (LV2_IS_PORT_ENUMERATION(portProps))
  1909. pData->param.data[j].hints |= PARAMETER_USES_SCALEPOINTS;
  1910. // check if parameter is not enabled or automable
  1911. if (LV2_IS_PORT_NOT_ON_GUI(portProps))
  1912. pData->param.data[j].hints &= ~(PARAMETER_IS_ENABLED|PARAMETER_IS_AUTOMABLE);
  1913. else if (LV2_IS_PORT_CAUSES_ARTIFACTS(portProps) || LV2_IS_PORT_EXPENSIVE(portProps))
  1914. pData->param.data[j].hints &= ~PARAMETER_IS_AUTOMABLE;
  1915. else if (LV2_IS_PORT_NOT_AUTOMATIC(portProps) || LV2_IS_PORT_NON_AUTOMABLE(portProps))
  1916. pData->param.data[j].hints &= ~PARAMETER_IS_AUTOMABLE;
  1917. pData->param.ranges[j].min = min;
  1918. pData->param.ranges[j].max = max;
  1919. pData->param.ranges[j].def = def;
  1920. pData->param.ranges[j].step = step;
  1921. pData->param.ranges[j].stepSmall = stepSmall;
  1922. pData->param.ranges[j].stepLarge = stepLarge;
  1923. // Start parameters in their default values (except freewheel, which is off by default)
  1924. if (pData->param.data[j].type == PARAMETER_INPUT && pData->param.special[j] == PARAMETER_SPECIAL_FREEWHEEL)
  1925. fParamBuffers[j] = min;
  1926. else
  1927. fParamBuffers[j] = def;
  1928. fDescriptor->connect_port(fHandle, i, &fParamBuffers[j]);
  1929. if (fHandle2 != nullptr)
  1930. fDescriptor->connect_port(fHandle2, i, &fParamBuffers[j]);
  1931. }
  1932. else
  1933. {
  1934. // Port Type not supported, but it's optional anyway
  1935. fDescriptor->connect_port(fHandle, i, nullptr);
  1936. if (fHandle2 != nullptr)
  1937. fDescriptor->connect_port(fHandle2, i, nullptr);
  1938. }
  1939. }
  1940. if (needsCtrlIn)
  1941. {
  1942. portName.clear();
  1943. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1944. {
  1945. portName = pData->name;
  1946. portName += ":";
  1947. }
  1948. portName += "events-in";
  1949. portName.truncate(portNameSize);
  1950. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, 0);
  1951. }
  1952. if (needsCtrlOut)
  1953. {
  1954. portName.clear();
  1955. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1956. {
  1957. portName = pData->name;
  1958. portName += ":";
  1959. }
  1960. portName += "events-out";
  1961. portName.truncate(portNameSize);
  1962. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, 0);
  1963. }
  1964. if (fExt.worker != nullptr || (fUI.type != UI::TYPE_NULL && fEventsIn.count > 0 && (fEventsIn.data[0].type & CARLA_EVENT_DATA_ATOM) != 0))
  1965. fAtomBufferIn.createBuffer(eventBufferSize);
  1966. if (fExt.worker != nullptr || (fUI.type != UI::TYPE_NULL && fEventsOut.count > 0 && (fEventsOut.data[0].type & CARLA_EVENT_DATA_ATOM) != 0))
  1967. {
  1968. fAtomBufferOut.createBuffer(std::min(eventBufferSize*32, 1638400U));
  1969. fTmpAtomBuffer = new uint8_t[fAtomBufferOut.getSize()];
  1970. }
  1971. if (fEventsIn.ctrl != nullptr && fEventsIn.ctrl->port == nullptr)
  1972. fEventsIn.ctrl->port = pData->event.portIn;
  1973. if (fEventsOut.ctrl != nullptr && fEventsOut.ctrl->port == nullptr)
  1974. fEventsOut.ctrl->port = pData->event.portOut;
  1975. if (fCanInit2 && (forcedStereoIn || forcedStereoOut))
  1976. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  1977. else
  1978. pData->options &= ~PLUGIN_OPTION_FORCE_STEREO;
  1979. // plugin hints
  1980. pData->hints = 0x0;
  1981. if (isRealtimeSafe())
  1982. pData->hints |= PLUGIN_IS_RTSAFE;
  1983. if (fUI.type != UI::TYPE_NULL)
  1984. {
  1985. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  1986. if (fUI.type == UI::TYPE_EMBED || fUI.type == UI::TYPE_EXTERNAL)
  1987. pData->hints |= PLUGIN_NEEDS_UI_MAIN_THREAD;
  1988. }
  1989. if (LV2_IS_GENERATOR(fRdfDescriptor->Type[0], fRdfDescriptor->Type[1]))
  1990. pData->hints |= PLUGIN_IS_SYNTH;
  1991. if (aOuts > 0 && (aIns == aOuts || aIns == 1))
  1992. pData->hints |= PLUGIN_CAN_DRYWET;
  1993. if (aOuts > 0)
  1994. pData->hints |= PLUGIN_CAN_VOLUME;
  1995. if (aOuts >= 2 && aOuts % 2 == 0)
  1996. pData->hints |= PLUGIN_CAN_BALANCE;
  1997. // extra plugin hints
  1998. pData->extraHints = 0x0;
  1999. if (! fCanInit2)
  2000. {
  2001. // can't run in rack
  2002. }
  2003. else if (fExt.state != nullptr || fExt.worker != nullptr)
  2004. {
  2005. if ((aIns == 0 || aIns == 2) && (aOuts == 0 || aOuts == 2) && evIns.count() <= 1 && evOuts.count() <= 1)
  2006. pData->extraHints |= PLUGIN_EXTRA_HINT_CAN_RUN_RACK;
  2007. }
  2008. else
  2009. {
  2010. if (aIns <= 2 && aOuts <= 2 && (aIns == aOuts || aIns == 0 || aOuts == 0) && evIns.count() <= 1 && evOuts.count() <= 1)
  2011. pData->extraHints |= PLUGIN_EXTRA_HINT_CAN_RUN_RACK;
  2012. }
  2013. // check initial latency
  2014. findInitialLatencyValue(aIns, aOuts);
  2015. bufferSizeChanged(pData->engine->getBufferSize());
  2016. reloadPrograms(true);
  2017. evIns.clear();
  2018. evOuts.clear();
  2019. if (pData->active)
  2020. activate();
  2021. carla_debug("CarlaPluginLV2::reload() - end");
  2022. }
  2023. void findInitialLatencyValue(const uint32_t aIns, const uint32_t aOuts) const
  2024. {
  2025. if (fLatencyIndex < 0)
  2026. return;
  2027. // we need to pre-run the plugin so it can update its latency control-port
  2028. const uint32_t bufferSize = static_cast<uint32_t>(fLv2Options.nominalBufferSize);
  2029. float tmpIn [(aIns > 0) ? aIns : 1][bufferSize];
  2030. float tmpOut[(aOuts > 0) ? aOuts : 1][bufferSize];
  2031. for (uint32_t j=0; j < aIns; ++j)
  2032. {
  2033. carla_zeroFloats(tmpIn[j], bufferSize);
  2034. try {
  2035. fDescriptor->connect_port(fHandle, pData->audioIn.ports[j].rindex, tmpIn[j]);
  2036. } CARLA_SAFE_EXCEPTION("LV2 connect_port latency input");
  2037. }
  2038. for (uint32_t j=0; j < aOuts; ++j)
  2039. {
  2040. carla_zeroFloats(tmpOut[j], bufferSize);
  2041. try {
  2042. fDescriptor->connect_port(fHandle, pData->audioOut.ports[j].rindex, tmpOut[j]);
  2043. } CARLA_SAFE_EXCEPTION("LV2 connect_port latency output");
  2044. }
  2045. if (fDescriptor->activate != nullptr)
  2046. {
  2047. try {
  2048. fDescriptor->activate(fHandle);
  2049. } CARLA_SAFE_EXCEPTION("LV2 latency activate");
  2050. }
  2051. try {
  2052. fDescriptor->run(fHandle, bufferSize);
  2053. } CARLA_SAFE_EXCEPTION("LV2 latency run");
  2054. if (fDescriptor->deactivate != nullptr)
  2055. {
  2056. try {
  2057. fDescriptor->deactivate(fHandle);
  2058. } CARLA_SAFE_EXCEPTION("LV2 latency deactivate");
  2059. }
  2060. // done, let's get the value
  2061. if (const uint32_t latency = getLatencyInFrames())
  2062. {
  2063. pData->client->setLatency(latency);
  2064. #ifndef BUILD_BRIDGE
  2065. pData->latency.recreateBuffers(std::max(aIns, aOuts), latency);
  2066. #endif
  2067. }
  2068. }
  2069. void reloadPrograms(const bool doInit) override
  2070. {
  2071. carla_debug("CarlaPluginLV2::reloadPrograms(%s)", bool2str(doInit));
  2072. const uint32_t oldCount = pData->midiprog.count;
  2073. const int32_t current = pData->midiprog.current;
  2074. // special LV2 programs handling
  2075. if (doInit)
  2076. {
  2077. pData->prog.clear();
  2078. const uint32_t presetCount(fRdfDescriptor->PresetCount);
  2079. if (presetCount > 0)
  2080. {
  2081. pData->prog.createNew(presetCount);
  2082. for (uint32_t i=0; i < presetCount; ++i)
  2083. pData->prog.names[i] = carla_strdup(fRdfDescriptor->Presets[i].Label);
  2084. }
  2085. }
  2086. // Delete old programs
  2087. pData->midiprog.clear();
  2088. // Query new programs
  2089. uint32_t newCount = 0;
  2090. if (fExt.programs != nullptr && fExt.programs->get_program != nullptr && fExt.programs->select_program != nullptr)
  2091. {
  2092. for (; fExt.programs->get_program(fHandle, newCount);)
  2093. ++newCount;
  2094. }
  2095. if (newCount > 0)
  2096. {
  2097. pData->midiprog.createNew(newCount);
  2098. // Update data
  2099. for (uint32_t i=0; i < newCount; ++i)
  2100. {
  2101. const LV2_Program_Descriptor* const pdesc(fExt.programs->get_program(fHandle, i));
  2102. CARLA_SAFE_ASSERT_CONTINUE(pdesc != nullptr);
  2103. CARLA_SAFE_ASSERT(pdesc->name != nullptr);
  2104. pData->midiprog.data[i].bank = pdesc->bank;
  2105. pData->midiprog.data[i].program = pdesc->program;
  2106. pData->midiprog.data[i].name = carla_strdup(pdesc->name);
  2107. }
  2108. }
  2109. #if defined(HAVE_LIBLO) && ! defined(BUILD_BRIDGE)
  2110. // Update OSC Names
  2111. if (pData->engine->isOscControlRegistered() && pData->id < pData->engine->getCurrentPluginCount())
  2112. {
  2113. pData->engine->oscSend_control_set_midi_program_count(pData->id, newCount);
  2114. for (uint32_t i=0; i < newCount; ++i)
  2115. pData->engine->oscSend_control_set_midi_program_data(pData->id, i, pData->midiprog.data[i].bank, pData->midiprog.data[i].program, pData->midiprog.data[i].name);
  2116. }
  2117. #endif
  2118. if (doInit)
  2119. {
  2120. if (newCount > 0)
  2121. {
  2122. setMidiProgram(0, false, false, false);
  2123. }
  2124. else
  2125. {
  2126. // load default state
  2127. if (LilvState* const state = Lv2WorldClass::getInstance().getStateFromURI(fDescriptor->URI, (const LV2_URID_Map*)fFeatures[kFeatureIdUridMap]->data))
  2128. {
  2129. lilv_state_restore(state, fExt.state, fHandle, carla_lilv_set_port_value, this, 0, fFeatures);
  2130. if (fHandle2 != nullptr)
  2131. lilv_state_restore(state, fExt.state, fHandle2, carla_lilv_set_port_value, this, 0, fFeatures);
  2132. lilv_state_free(state);
  2133. }
  2134. }
  2135. }
  2136. else
  2137. {
  2138. // Check if current program is invalid
  2139. bool programChanged = false;
  2140. if (newCount == oldCount+1)
  2141. {
  2142. // one midi program added, probably created by user
  2143. pData->midiprog.current = static_cast<int32_t>(oldCount);
  2144. programChanged = true;
  2145. }
  2146. else if (current < 0 && newCount > 0)
  2147. {
  2148. // programs exist now, but not before
  2149. pData->midiprog.current = 0;
  2150. programChanged = true;
  2151. }
  2152. else if (current >= 0 && newCount == 0)
  2153. {
  2154. // programs existed before, but not anymore
  2155. pData->midiprog.current = -1;
  2156. programChanged = true;
  2157. }
  2158. else if (current >= static_cast<int32_t>(newCount))
  2159. {
  2160. // current midi program > count
  2161. pData->midiprog.current = 0;
  2162. programChanged = true;
  2163. }
  2164. else
  2165. {
  2166. // no change
  2167. pData->midiprog.current = current;
  2168. }
  2169. if (programChanged)
  2170. setMidiProgram(pData->midiprog.current, true, true, true);
  2171. pData->engine->callback(ENGINE_CALLBACK_RELOAD_PROGRAMS, pData->id, 0, 0, 0.0f, nullptr);
  2172. }
  2173. }
  2174. // -------------------------------------------------------------------
  2175. // Plugin processing
  2176. void activate() noexcept override
  2177. {
  2178. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr,);
  2179. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr,);
  2180. if (fDescriptor->activate != nullptr)
  2181. {
  2182. try {
  2183. fDescriptor->activate(fHandle);
  2184. } CARLA_SAFE_EXCEPTION("LV2 activate");
  2185. if (fHandle2 != nullptr)
  2186. {
  2187. try {
  2188. fDescriptor->activate(fHandle2);
  2189. } CARLA_SAFE_EXCEPTION("LV2 activate #2");
  2190. }
  2191. }
  2192. fFirstActive = true;
  2193. }
  2194. void deactivate() noexcept override
  2195. {
  2196. CARLA_SAFE_ASSERT_RETURN(fDescriptor != nullptr,);
  2197. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr,);
  2198. if (fDescriptor->deactivate != nullptr)
  2199. {
  2200. try {
  2201. fDescriptor->deactivate(fHandle);
  2202. } CARLA_SAFE_EXCEPTION("LV2 deactivate");
  2203. if (fHandle2 != nullptr)
  2204. {
  2205. try {
  2206. fDescriptor->deactivate(fHandle2);
  2207. } CARLA_SAFE_EXCEPTION("LV2 deactivate #2");
  2208. }
  2209. }
  2210. }
  2211. void process(const float** const audioIn, float** const audioOut, const float** const cvIn, float** const cvOut, const uint32_t frames) override
  2212. {
  2213. // --------------------------------------------------------------------------------------------------------
  2214. // Check if active
  2215. if (! pData->active)
  2216. {
  2217. // disable any output sound
  2218. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  2219. FloatVectorOperations::clear(audioOut[i], static_cast<int>(frames));
  2220. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  2221. FloatVectorOperations::clear(cvOut[i], static_cast<int>(frames));
  2222. return;
  2223. }
  2224. // --------------------------------------------------------------------------------------------------------
  2225. // Event itenerators from different APIs (input)
  2226. LV2_Atom_Buffer_Iterator evInAtomIters[fEventsIn.count];
  2227. LV2_Event_Iterator evInEventIters[fEventsIn.count];
  2228. LV2_MIDIState evInMidiStates[fEventsIn.count];
  2229. for (uint32_t i=0; i < fEventsIn.count; ++i)
  2230. {
  2231. if (fEventsIn.data[i].type & CARLA_EVENT_DATA_ATOM)
  2232. {
  2233. lv2_atom_buffer_reset(fEventsIn.data[i].atom, true);
  2234. lv2_atom_buffer_begin(&evInAtomIters[i], fEventsIn.data[i].atom);
  2235. }
  2236. else if (fEventsIn.data[i].type & CARLA_EVENT_DATA_EVENT)
  2237. {
  2238. lv2_event_buffer_reset(fEventsIn.data[i].event, LV2_EVENT_AUDIO_STAMP, fEventsIn.data[i].event->data);
  2239. lv2_event_begin(&evInEventIters[i], fEventsIn.data[i].event);
  2240. }
  2241. else if (fEventsIn.data[i].type & CARLA_EVENT_DATA_MIDI_LL)
  2242. {
  2243. fEventsIn.data[i].midi.event_count = 0;
  2244. fEventsIn.data[i].midi.size = 0;
  2245. evInMidiStates[i].midi = &fEventsIn.data[i].midi;
  2246. evInMidiStates[i].frame_count = frames;
  2247. evInMidiStates[i].position = 0;
  2248. }
  2249. }
  2250. for (uint32_t i=0; i < fEventsOut.count; ++i)
  2251. {
  2252. if (fEventsOut.data[i].type & CARLA_EVENT_DATA_ATOM)
  2253. {
  2254. lv2_atom_buffer_reset(fEventsOut.data[i].atom, false);
  2255. }
  2256. else if (fEventsOut.data[i].type & CARLA_EVENT_DATA_EVENT)
  2257. {
  2258. lv2_event_buffer_reset(fEventsOut.data[i].event, LV2_EVENT_AUDIO_STAMP, fEventsOut.data[i].event->data);
  2259. }
  2260. else if (fEventsOut.data[i].type & CARLA_EVENT_DATA_MIDI_LL)
  2261. {
  2262. // not needed
  2263. }
  2264. }
  2265. // --------------------------------------------------------------------------------------------------------
  2266. // Check if needs reset
  2267. if (pData->needsReset)
  2268. {
  2269. if (fEventsIn.ctrl != nullptr && (fEventsIn.ctrl->type & CARLA_EVENT_TYPE_MIDI) != 0)
  2270. {
  2271. const uint32_t j = fEventsIn.ctrlIndex;
  2272. CARLA_ASSERT(j < fEventsIn.count);
  2273. uint8_t midiData[3] = { 0, 0, 0 };
  2274. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  2275. {
  2276. for (uint8_t i=0; i < MAX_MIDI_CHANNELS; ++i)
  2277. {
  2278. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (i & MIDI_CHANNEL_BIT));
  2279. midiData[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  2280. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  2281. lv2_atom_buffer_write(&evInAtomIters[j], 0, 0, CARLA_URI_MAP_ID_MIDI_EVENT, 3, midiData);
  2282. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  2283. lv2_event_write(&evInEventIters[j], 0, 0, CARLA_URI_MAP_ID_MIDI_EVENT, 3, midiData);
  2284. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  2285. lv2midi_put_event(&evInMidiStates[j], 0.0, 3, midiData);
  2286. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (i & MIDI_CHANNEL_BIT));
  2287. midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  2288. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  2289. lv2_atom_buffer_write(&evInAtomIters[j], 0, 0, CARLA_URI_MAP_ID_MIDI_EVENT, 3, midiData);
  2290. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  2291. lv2_event_write(&evInEventIters[j], 0, 0, CARLA_URI_MAP_ID_MIDI_EVENT, 3, midiData);
  2292. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  2293. lv2midi_put_event(&evInMidiStates[j], 0.0, 3, midiData);
  2294. }
  2295. }
  2296. else if (pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  2297. {
  2298. for (uint8_t k=0; k < MAX_MIDI_NOTE; ++k)
  2299. {
  2300. midiData[0] = uint8_t(MIDI_STATUS_NOTE_OFF | (pData->ctrlChannel & MIDI_CHANNEL_BIT));
  2301. midiData[1] = k;
  2302. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  2303. lv2_atom_buffer_write(&evInAtomIters[j], 0, 0, CARLA_URI_MAP_ID_MIDI_EVENT, 3, midiData);
  2304. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  2305. lv2_event_write(&evInEventIters[j], 0, 0, CARLA_URI_MAP_ID_MIDI_EVENT, 3, midiData);
  2306. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  2307. lv2midi_put_event(&evInMidiStates[j], 0.0, 3, midiData);
  2308. }
  2309. }
  2310. }
  2311. pData->needsReset = false;
  2312. }
  2313. // --------------------------------------------------------------------------------------------------------
  2314. // TimeInfo
  2315. const EngineTimeInfo& timeInfo(pData->engine->getTimeInfo());
  2316. if (fFirstActive || fLastTimeInfo != timeInfo)
  2317. {
  2318. bool doPostRt;
  2319. int32_t rindex;
  2320. // update input ports
  2321. for (uint32_t k=0; k < pData->param.count; ++k)
  2322. {
  2323. if (pData->param.data[k].type != PARAMETER_INPUT)
  2324. continue;
  2325. if (pData->param.special[k] != PARAMETER_SPECIAL_TIME)
  2326. continue;
  2327. doPostRt = false;
  2328. rindex = pData->param.data[k].rindex;
  2329. CARLA_SAFE_ASSERT_CONTINUE(rindex >= 0 && rindex < static_cast<int32_t>(fRdfDescriptor->PortCount));
  2330. switch (fRdfDescriptor->Ports[rindex].Designation)
  2331. {
  2332. // Non-BBT
  2333. case LV2_PORT_DESIGNATION_TIME_SPEED:
  2334. if (fLastTimeInfo.playing != timeInfo.playing)
  2335. {
  2336. fParamBuffers[k] = timeInfo.playing ? 1.0f : 0.0f;
  2337. doPostRt = true;
  2338. }
  2339. break;
  2340. case LV2_PORT_DESIGNATION_TIME_FRAME:
  2341. if (fLastTimeInfo.frame != timeInfo.frame)
  2342. {
  2343. fParamBuffers[k] = static_cast<float>(timeInfo.frame);
  2344. doPostRt = true;
  2345. }
  2346. break;
  2347. case LV2_PORT_DESIGNATION_TIME_FRAMES_PER_SECOND:
  2348. break;
  2349. // BBT
  2350. case LV2_PORT_DESIGNATION_TIME_BAR:
  2351. if ((timeInfo.valid & EngineTimeInfo::kValidBBT) != 0 && fLastTimeInfo.bbt.bar != timeInfo.bbt.bar)
  2352. {
  2353. fParamBuffers[k] = static_cast<float>(timeInfo.bbt.bar - 1);
  2354. doPostRt = true;
  2355. }
  2356. break;
  2357. case LV2_PORT_DESIGNATION_TIME_BAR_BEAT:
  2358. if ((timeInfo.valid & EngineTimeInfo::kValidBBT) != 0 && (fLastTimeInfo.bbt.tick != timeInfo.bbt.tick ||
  2359. fLastTimeInfo.bbt.beat != timeInfo.bbt.beat))
  2360. {
  2361. fParamBuffers[k] = static_cast<float>(static_cast<double>(timeInfo.bbt.beat) - 1.0 + (static_cast<double>(timeInfo.bbt.tick) / timeInfo.bbt.ticksPerBeat));
  2362. doPostRt = true;
  2363. }
  2364. break;
  2365. case LV2_PORT_DESIGNATION_TIME_BEAT:
  2366. if ((timeInfo.valid & EngineTimeInfo::kValidBBT) != 0 && fLastTimeInfo.bbt.beat != timeInfo.bbt.beat)
  2367. {
  2368. fParamBuffers[k] = static_cast<float>(timeInfo.bbt.beat - 1);
  2369. doPostRt = true;
  2370. }
  2371. break;
  2372. case LV2_PORT_DESIGNATION_TIME_BEAT_UNIT:
  2373. if ((timeInfo.valid & EngineTimeInfo::kValidBBT) != 0 && carla_isNotEqual(fLastTimeInfo.bbt.beatType, timeInfo.bbt.beatType))
  2374. {
  2375. fParamBuffers[k] = timeInfo.bbt.beatType;
  2376. doPostRt = true;
  2377. }
  2378. break;
  2379. case LV2_PORT_DESIGNATION_TIME_BEATS_PER_BAR:
  2380. if ((timeInfo.valid & EngineTimeInfo::kValidBBT) != 0 && carla_isNotEqual(fLastTimeInfo.bbt.beatsPerBar, timeInfo.bbt.beatsPerBar))
  2381. {
  2382. fParamBuffers[k] = timeInfo.bbt.beatsPerBar;
  2383. doPostRt = true;
  2384. }
  2385. break;
  2386. case LV2_PORT_DESIGNATION_TIME_BEATS_PER_MINUTE:
  2387. if ((timeInfo.valid & EngineTimeInfo::kValidBBT) != 0 && carla_isNotEqual(fLastTimeInfo.bbt.beatsPerMinute, timeInfo.bbt.beatsPerMinute))
  2388. {
  2389. fParamBuffers[k] = static_cast<float>(timeInfo.bbt.beatsPerMinute);
  2390. doPostRt = true;
  2391. }
  2392. break;
  2393. case LV2_PORT_DESIGNATION_TIME_TICKS_PER_BEAT:
  2394. if ((timeInfo.valid & EngineTimeInfo::kValidBBT) != 0 && carla_isNotEqual(fLastTimeInfo.bbt.ticksPerBeat, timeInfo.bbt.ticksPerBeat))
  2395. {
  2396. fParamBuffers[k] = static_cast<float>(timeInfo.bbt.ticksPerBeat);
  2397. doPostRt = true;
  2398. }
  2399. break;
  2400. }
  2401. if (doPostRt)
  2402. pData->postponeRtEvent(kPluginPostRtEventParameterChange, static_cast<int32_t>(k), 1, fParamBuffers[k]);
  2403. }
  2404. for (uint32_t i=0; i < fEventsIn.count; ++i)
  2405. {
  2406. if ((fEventsIn.data[i].type & CARLA_EVENT_DATA_ATOM) == 0 || (fEventsIn.data[i].type & CARLA_EVENT_TYPE_TIME) == 0)
  2407. continue;
  2408. uint8_t timeInfoBuf[256];
  2409. lv2_atom_forge_set_buffer(&fAtomForge, timeInfoBuf, sizeof(timeInfoBuf));
  2410. LV2_Atom_Forge_Frame forgeFrame;
  2411. lv2_atom_forge_object(&fAtomForge, &forgeFrame, CARLA_URI_MAP_ID_NULL, CARLA_URI_MAP_ID_TIME_POSITION);
  2412. lv2_atom_forge_key(&fAtomForge, CARLA_URI_MAP_ID_TIME_SPEED);
  2413. lv2_atom_forge_float(&fAtomForge, timeInfo.playing ? 1.0f : 0.0f);
  2414. lv2_atom_forge_key(&fAtomForge, CARLA_URI_MAP_ID_TIME_FRAME);
  2415. lv2_atom_forge_long(&fAtomForge, static_cast<int64_t>(timeInfo.frame));
  2416. if (timeInfo.valid & EngineTimeInfo::kValidBBT)
  2417. {
  2418. lv2_atom_forge_key(&fAtomForge, CARLA_URI_MAP_ID_TIME_BAR);
  2419. lv2_atom_forge_long(&fAtomForge, timeInfo.bbt.bar - 1);
  2420. lv2_atom_forge_key(&fAtomForge, CARLA_URI_MAP_ID_TIME_BAR_BEAT);
  2421. lv2_atom_forge_float(&fAtomForge, static_cast<float>(static_cast<double>(timeInfo.bbt.beat) - 1.0 + (static_cast<double>(timeInfo.bbt.tick) / timeInfo.bbt.ticksPerBeat)));
  2422. lv2_atom_forge_key(&fAtomForge, CARLA_URI_MAP_ID_TIME_BEAT);
  2423. lv2_atom_forge_double(&fAtomForge, timeInfo.bbt.beat - 1);
  2424. lv2_atom_forge_key(&fAtomForge, CARLA_URI_MAP_ID_TIME_BEAT_UNIT);
  2425. lv2_atom_forge_int(&fAtomForge, static_cast<int32_t>(timeInfo.bbt.beatType));
  2426. lv2_atom_forge_key(&fAtomForge, CARLA_URI_MAP_ID_TIME_BEATS_PER_BAR);
  2427. lv2_atom_forge_float(&fAtomForge, timeInfo.bbt.beatsPerBar);
  2428. lv2_atom_forge_key(&fAtomForge, CARLA_URI_MAP_ID_TIME_BEATS_PER_MINUTE);
  2429. lv2_atom_forge_float(&fAtomForge, static_cast<float>(timeInfo.bbt.beatsPerMinute));
  2430. lv2_atom_forge_key(&fAtomForge, CARLA_URI_MAP_ID_TIME_TICKS_PER_BEAT);
  2431. lv2_atom_forge_double(&fAtomForge, timeInfo.bbt.ticksPerBeat);
  2432. }
  2433. lv2_atom_forge_pop(&fAtomForge, &forgeFrame);
  2434. LV2_Atom* const atom((LV2_Atom*)timeInfoBuf);
  2435. CARLA_SAFE_ASSERT_BREAK(atom->size < 256);
  2436. // send only deprecated blank object for now
  2437. lv2_atom_buffer_write(&evInAtomIters[i], 0, 0, CARLA_URI_MAP_ID_ATOM_BLANK, atom->size, LV2_ATOM_BODY_CONST(atom));
  2438. // for atom:object
  2439. //lv2_atom_buffer_write(&evInAtomIters[i], 0, 0, atom->type, atom->size, LV2_ATOM_BODY_CONST(atom));
  2440. }
  2441. pData->postRtEvents.trySplice();
  2442. carla_copyStruct(fLastTimeInfo, timeInfo);
  2443. }
  2444. // --------------------------------------------------------------------------------------------------------
  2445. // Event Input and Processing
  2446. if (fEventsIn.ctrl != nullptr)
  2447. {
  2448. // ----------------------------------------------------------------------------------------------------
  2449. // Message Input
  2450. if (fAtomBufferIn.tryLock())
  2451. {
  2452. if (fAtomBufferIn.isDataAvailableForReading())
  2453. {
  2454. const LV2_Atom* atom;
  2455. uint32_t j, portIndex;
  2456. for (; fAtomBufferIn.get(atom, portIndex);)
  2457. {
  2458. j = (portIndex < fEventsIn.count) ? portIndex : fEventsIn.ctrlIndex;
  2459. if (atom->type == CARLA_URI_MAP_ID_CARLA_ATOM_WORKER)
  2460. {
  2461. CARLA_SAFE_ASSERT_CONTINUE(fExt.worker != nullptr && fExt.worker->work_response != nullptr);
  2462. fExt.worker->work_response(fHandle, atom->size, LV2_ATOM_BODY_CONST(atom));
  2463. }
  2464. else if (! lv2_atom_buffer_write(&evInAtomIters[j], 0, 0, atom->type, atom->size, LV2_ATOM_BODY_CONST(atom)))
  2465. {
  2466. carla_stdout("Event input buffer full, at least 1 message lost");
  2467. continue;
  2468. }
  2469. }
  2470. }
  2471. fAtomBufferIn.unlock();
  2472. }
  2473. // ----------------------------------------------------------------------------------------------------
  2474. // MIDI Input (External)
  2475. if (pData->extNotes.mutex.tryLock())
  2476. {
  2477. if ((fEventsIn.ctrl->type & CARLA_EVENT_TYPE_MIDI) == 0)
  2478. {
  2479. // does not handle MIDI
  2480. pData->extNotes.data.clear();
  2481. }
  2482. else
  2483. {
  2484. const uint32_t j = fEventsIn.ctrlIndex;
  2485. for (RtLinkedList<ExternalMidiNote>::Itenerator it = pData->extNotes.data.begin2(); it.valid(); it.next())
  2486. {
  2487. const ExternalMidiNote& note(it.getValue(kExternalMidiNoteFallback));
  2488. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  2489. uint8_t midiEvent[3];
  2490. midiEvent[0] = uint8_t((note.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT));
  2491. midiEvent[1] = note.note;
  2492. midiEvent[2] = note.velo;
  2493. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  2494. lv2_atom_buffer_write(&evInAtomIters[j], 0, 0, CARLA_URI_MAP_ID_MIDI_EVENT, 3, midiEvent);
  2495. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  2496. lv2_event_write(&evInEventIters[j], 0, 0, CARLA_URI_MAP_ID_MIDI_EVENT, 3, midiEvent);
  2497. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  2498. lv2midi_put_event(&evInMidiStates[j], 0.0, 3, midiEvent);
  2499. }
  2500. pData->extNotes.data.clear();
  2501. }
  2502. pData->extNotes.mutex.unlock();
  2503. } // End of MIDI Input (External)
  2504. // ----------------------------------------------------------------------------------------------------
  2505. // Event Input (System)
  2506. #ifndef BUILD_BRIDGE
  2507. bool allNotesOffSent = false;
  2508. #endif
  2509. bool isSampleAccurate = (pData->options & PLUGIN_OPTION_FIXED_BUFFERS) == 0;
  2510. uint32_t startTime = 0;
  2511. uint32_t timeOffset = 0;
  2512. uint32_t nextBankId;
  2513. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0)
  2514. nextBankId = pData->midiprog.data[pData->midiprog.current].bank;
  2515. else
  2516. nextBankId = 0;
  2517. const uint32_t numEvents = (fEventsIn.ctrl->port != nullptr) ? fEventsIn.ctrl->port->getEventCount() : 0;
  2518. for (uint32_t i=0; i < numEvents; ++i)
  2519. {
  2520. const EngineEvent& event(fEventsIn.ctrl->port->getEvent(i));
  2521. if (event.time >= frames)
  2522. continue;
  2523. CARLA_ASSERT_INT2(event.time >= timeOffset, event.time, timeOffset);
  2524. if (isSampleAccurate && event.time > timeOffset)
  2525. {
  2526. if (processSingle(audioIn, audioOut, cvIn, cvOut, event.time - timeOffset, timeOffset))
  2527. {
  2528. startTime = 0;
  2529. timeOffset = event.time;
  2530. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0)
  2531. nextBankId = pData->midiprog.data[pData->midiprog.current].bank;
  2532. else
  2533. nextBankId = 0;
  2534. for (uint32_t j=0; j < fEventsIn.count; ++j)
  2535. {
  2536. if (fEventsIn.data[j].type & CARLA_EVENT_DATA_ATOM)
  2537. {
  2538. lv2_atom_buffer_reset(fEventsIn.data[j].atom, true);
  2539. lv2_atom_buffer_begin(&evInAtomIters[j], fEventsIn.data[j].atom);
  2540. }
  2541. else if (fEventsIn.data[j].type & CARLA_EVENT_DATA_EVENT)
  2542. {
  2543. lv2_event_buffer_reset(fEventsIn.data[j].event, LV2_EVENT_AUDIO_STAMP, fEventsIn.data[j].event->data);
  2544. lv2_event_begin(&evInEventIters[j], fEventsIn.data[j].event);
  2545. }
  2546. else if (fEventsIn.data[j].type & CARLA_EVENT_DATA_MIDI_LL)
  2547. {
  2548. fEventsIn.data[j].midi.event_count = 0;
  2549. fEventsIn.data[j].midi.size = 0;
  2550. evInMidiStates[j].position = event.time;
  2551. }
  2552. }
  2553. for (uint32_t j=0; j < fEventsOut.count; ++j)
  2554. {
  2555. if (fEventsOut.data[j].type & CARLA_EVENT_DATA_ATOM)
  2556. {
  2557. lv2_atom_buffer_reset(fEventsOut.data[j].atom, false);
  2558. }
  2559. else if (fEventsOut.data[j].type & CARLA_EVENT_DATA_EVENT)
  2560. {
  2561. lv2_event_buffer_reset(fEventsOut.data[j].event, LV2_EVENT_AUDIO_STAMP, fEventsOut.data[j].event->data);
  2562. }
  2563. else if (fEventsOut.data[j].type & CARLA_EVENT_DATA_MIDI_LL)
  2564. {
  2565. // not needed
  2566. }
  2567. }
  2568. }
  2569. else
  2570. {
  2571. startTime += timeOffset;
  2572. }
  2573. }
  2574. switch (event.type)
  2575. {
  2576. case kEngineEventTypeNull:
  2577. break;
  2578. case kEngineEventTypeControl: {
  2579. const EngineControlEvent& ctrlEvent(event.ctrl);
  2580. switch (ctrlEvent.type)
  2581. {
  2582. case kEngineControlEventTypeNull:
  2583. break;
  2584. case kEngineControlEventTypeParameter: {
  2585. #ifndef BUILD_BRIDGE
  2586. // Control backend stuff
  2587. if (event.channel == pData->ctrlChannel)
  2588. {
  2589. float value;
  2590. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  2591. {
  2592. value = ctrlEvent.value;
  2593. setDryWet(value, false, false);
  2594. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  2595. }
  2596. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  2597. {
  2598. value = ctrlEvent.value*127.0f/100.0f;
  2599. setVolume(value, false, false);
  2600. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  2601. }
  2602. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  2603. {
  2604. float left, right;
  2605. value = ctrlEvent.value/0.5f - 1.0f;
  2606. if (value < 0.0f)
  2607. {
  2608. left = -1.0f;
  2609. right = (value*2.0f)+1.0f;
  2610. }
  2611. else if (value > 0.0f)
  2612. {
  2613. left = (value*2.0f)-1.0f;
  2614. right = 1.0f;
  2615. }
  2616. else
  2617. {
  2618. left = -1.0f;
  2619. right = 1.0f;
  2620. }
  2621. setBalanceLeft(left, false, false);
  2622. setBalanceRight(right, false, false);
  2623. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  2624. pData->postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  2625. }
  2626. }
  2627. #endif
  2628. // Control plugin parameters
  2629. uint32_t k;
  2630. for (k=0; k < pData->param.count; ++k)
  2631. {
  2632. if (pData->param.data[k].midiChannel != event.channel)
  2633. continue;
  2634. if (pData->param.data[k].midiCC != ctrlEvent.param)
  2635. continue;
  2636. if (pData->param.data[k].type != PARAMETER_INPUT)
  2637. continue;
  2638. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  2639. continue;
  2640. float value;
  2641. if (pData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  2642. {
  2643. value = (ctrlEvent.value < 0.5f) ? pData->param.ranges[k].min : pData->param.ranges[k].max;
  2644. }
  2645. else
  2646. {
  2647. if (pData->param.data[k].hints & PARAMETER_IS_LOGARITHMIC)
  2648. value = pData->param.ranges[k].getUnnormalizedLogValue(ctrlEvent.value);
  2649. else
  2650. value = pData->param.ranges[k].getUnnormalizedValue(ctrlEvent.value);
  2651. if (pData->param.data[k].hints & PARAMETER_IS_INTEGER)
  2652. value = std::rint(value);
  2653. }
  2654. setParameterValue(k, value, false, false, false);
  2655. pData->postponeRtEvent(kPluginPostRtEventParameterChange, static_cast<int32_t>(k), 0, value);
  2656. }
  2657. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param < MAX_MIDI_CONTROL)
  2658. {
  2659. uint8_t midiData[3];
  2660. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  2661. midiData[1] = uint8_t(ctrlEvent.param);
  2662. midiData[2] = uint8_t(ctrlEvent.value*127.0f);
  2663. const uint32_t mtime(isSampleAccurate ? startTime : event.time);
  2664. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  2665. lv2_atom_buffer_write(&evInAtomIters[fEventsIn.ctrlIndex], mtime, 0, CARLA_URI_MAP_ID_MIDI_EVENT, 3, midiData);
  2666. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  2667. lv2_event_write(&evInEventIters[fEventsIn.ctrlIndex], mtime, 0, CARLA_URI_MAP_ID_MIDI_EVENT, 3, midiData);
  2668. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  2669. lv2midi_put_event(&evInMidiStates[fEventsIn.ctrlIndex], mtime, 3, midiData);
  2670. }
  2671. break;
  2672. } // case kEngineControlEventTypeParameter
  2673. case kEngineControlEventTypeMidiBank:
  2674. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  2675. {
  2676. if (event.channel == pData->ctrlChannel)
  2677. nextBankId = ctrlEvent.param;
  2678. }
  2679. else if (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES)
  2680. {
  2681. uint8_t midiData[3];
  2682. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  2683. midiData[1] = MIDI_CONTROL_BANK_SELECT;
  2684. midiData[2] = uint8_t(ctrlEvent.param);
  2685. const uint32_t mtime(isSampleAccurate ? startTime : event.time);
  2686. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  2687. lv2_atom_buffer_write(&evInAtomIters[fEventsIn.ctrlIndex], mtime, 0, CARLA_URI_MAP_ID_MIDI_EVENT, 3, midiData);
  2688. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  2689. lv2_event_write(&evInEventIters[fEventsIn.ctrlIndex], mtime, 0, CARLA_URI_MAP_ID_MIDI_EVENT, 3, midiData);
  2690. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  2691. lv2midi_put_event(&evInMidiStates[fEventsIn.ctrlIndex], mtime, 3, midiData);
  2692. }
  2693. break;
  2694. case kEngineControlEventTypeMidiProgram:
  2695. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  2696. {
  2697. if (event.channel == pData->ctrlChannel)
  2698. {
  2699. const uint32_t nextProgramId(ctrlEvent.param);
  2700. for (uint32_t k=0; k < pData->midiprog.count; ++k)
  2701. {
  2702. if (pData->midiprog.data[k].bank == nextBankId && pData->midiprog.data[k].program == nextProgramId)
  2703. {
  2704. const int32_t index(static_cast<int32_t>(k));
  2705. setMidiProgram(index, false, false, false);
  2706. pData->postponeRtEvent(kPluginPostRtEventMidiProgramChange, index, 0, 0.0f);
  2707. break;
  2708. }
  2709. }
  2710. }
  2711. }
  2712. else if (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES)
  2713. {
  2714. uint8_t midiData[2];
  2715. midiData[0] = uint8_t(MIDI_STATUS_PROGRAM_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  2716. midiData[1] = uint8_t(ctrlEvent.param);
  2717. const uint32_t mtime(isSampleAccurate ? startTime : event.time);
  2718. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  2719. lv2_atom_buffer_write(&evInAtomIters[fEventsIn.ctrlIndex], mtime, 0, CARLA_URI_MAP_ID_MIDI_EVENT, 2, midiData);
  2720. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  2721. lv2_event_write(&evInEventIters[fEventsIn.ctrlIndex], mtime, 0, CARLA_URI_MAP_ID_MIDI_EVENT, 2, midiData);
  2722. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  2723. lv2midi_put_event(&evInMidiStates[fEventsIn.ctrlIndex], mtime, 2, midiData);
  2724. }
  2725. break;
  2726. case kEngineControlEventTypeAllSoundOff:
  2727. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  2728. {
  2729. const uint32_t mtime(isSampleAccurate ? startTime : event.time);
  2730. uint8_t midiData[3];
  2731. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  2732. midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  2733. midiData[2] = 0;
  2734. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  2735. lv2_atom_buffer_write(&evInAtomIters[fEventsIn.ctrlIndex], mtime, 0, CARLA_URI_MAP_ID_MIDI_EVENT, 3, midiData);
  2736. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  2737. lv2_event_write(&evInEventIters[fEventsIn.ctrlIndex], mtime, 0, CARLA_URI_MAP_ID_MIDI_EVENT, 3, midiData);
  2738. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  2739. lv2midi_put_event(&evInMidiStates[fEventsIn.ctrlIndex], mtime, 3, midiData);
  2740. }
  2741. break;
  2742. case kEngineControlEventTypeAllNotesOff:
  2743. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  2744. {
  2745. #ifndef BUILD_BRIDGE
  2746. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  2747. {
  2748. allNotesOffSent = true;
  2749. sendMidiAllNotesOffToCallback();
  2750. }
  2751. #endif
  2752. const uint32_t mtime(isSampleAccurate ? startTime : event.time);
  2753. uint8_t midiData[3];
  2754. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  2755. midiData[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  2756. midiData[2] = 0;
  2757. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  2758. lv2_atom_buffer_write(&evInAtomIters[fEventsIn.ctrlIndex], mtime, 0, CARLA_URI_MAP_ID_MIDI_EVENT, 3, midiData);
  2759. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  2760. lv2_event_write(&evInEventIters[fEventsIn.ctrlIndex], mtime, 0, CARLA_URI_MAP_ID_MIDI_EVENT, 3, midiData);
  2761. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  2762. lv2midi_put_event(&evInMidiStates[fEventsIn.ctrlIndex], mtime, 3, midiData);
  2763. }
  2764. break;
  2765. } // switch (ctrlEvent.type)
  2766. break;
  2767. } // case kEngineEventTypeControl
  2768. case kEngineEventTypeMidi: {
  2769. const EngineMidiEvent& midiEvent(event.midi);
  2770. const uint8_t* const midiData(midiEvent.size > EngineMidiEvent::kDataSize ? midiEvent.dataExt : midiEvent.data);
  2771. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiData));
  2772. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  2773. continue;
  2774. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  2775. continue;
  2776. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  2777. continue;
  2778. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  2779. continue;
  2780. // Fix bad note-off (per LV2 spec)
  2781. if (status == MIDI_STATUS_NOTE_ON && midiData[2] == 0)
  2782. status = MIDI_STATUS_NOTE_OFF;
  2783. const uint32_t j = fEventsIn.ctrlIndex;
  2784. const uint32_t mtime = isSampleAccurate ? startTime : event.time;
  2785. // put back channel in data
  2786. uint8_t midiData2[midiEvent.size];
  2787. midiData2[0] = uint8_t(status | (event.channel & MIDI_CHANNEL_BIT));
  2788. std::memcpy(midiData2+1, midiData+1, static_cast<std::size_t>(midiEvent.size-1));
  2789. if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_ATOM)
  2790. lv2_atom_buffer_write(&evInAtomIters[j], mtime, 0, CARLA_URI_MAP_ID_MIDI_EVENT, midiEvent.size, midiData2);
  2791. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_EVENT)
  2792. lv2_event_write(&evInEventIters[j], mtime, 0, CARLA_URI_MAP_ID_MIDI_EVENT, midiEvent.size, midiData2);
  2793. else if (fEventsIn.ctrl->type & CARLA_EVENT_DATA_MIDI_LL)
  2794. lv2midi_put_event(&evInMidiStates[j], mtime, midiEvent.size, midiData2);
  2795. if (status == MIDI_STATUS_NOTE_ON)
  2796. pData->postponeRtEvent(kPluginPostRtEventNoteOn, event.channel, midiData[1], midiData[2]);
  2797. else if (status == MIDI_STATUS_NOTE_OFF)
  2798. pData->postponeRtEvent(kPluginPostRtEventNoteOff, event.channel, midiData[1], 0.0f);
  2799. } break;
  2800. } // switch (event.type)
  2801. }
  2802. pData->postRtEvents.trySplice();
  2803. if (frames > timeOffset)
  2804. processSingle(audioIn, audioOut, cvIn, cvOut, frames - timeOffset, timeOffset);
  2805. } // End of Event Input and Processing
  2806. // --------------------------------------------------------------------------------------------------------
  2807. // Plugin processing (no events)
  2808. else
  2809. {
  2810. processSingle(audioIn, audioOut, cvIn, cvOut, frames, 0);
  2811. } // End of Plugin processing (no events)
  2812. // --------------------------------------------------------------------------------------------------------
  2813. // Events/MIDI Output
  2814. for (uint32_t i=0; i < fEventsOut.count; ++i)
  2815. {
  2816. Lv2EventData& evData(fEventsOut.data[i]);
  2817. if (evData.type & CARLA_EVENT_DATA_ATOM)
  2818. {
  2819. const LV2_Atom_Event* ev;
  2820. LV2_Atom_Buffer_Iterator iter;
  2821. uint8_t* data;
  2822. lv2_atom_buffer_begin(&iter, evData.atom);
  2823. for (;;)
  2824. {
  2825. data = nullptr;
  2826. ev = lv2_atom_buffer_get(&iter, &data);
  2827. if (ev == nullptr || ev->body.size == 0 || data == nullptr)
  2828. break;
  2829. if (ev->body.type == CARLA_URI_MAP_ID_MIDI_EVENT)
  2830. {
  2831. if (evData.port != nullptr)
  2832. {
  2833. CARLA_SAFE_ASSERT_CONTINUE(ev->time.frames >= 0);
  2834. CARLA_SAFE_ASSERT_CONTINUE(ev->body.size < 0xFF);
  2835. evData.port->writeMidiEvent(static_cast<uint32_t>(ev->time.frames), static_cast<uint8_t>(ev->body.size), data);
  2836. }
  2837. }
  2838. else //if (ev->body.type == CARLA_URI_MAP_ID_ATOM_BLANK)
  2839. {
  2840. //carla_stdout("Got out event, %s", carla_lv2_urid_unmap(this, ev->body.type));
  2841. fAtomBufferOut.put(&ev->body, evData.rindex);
  2842. }
  2843. lv2_atom_buffer_increment(&iter);
  2844. }
  2845. }
  2846. else if ((evData.type & CARLA_EVENT_DATA_EVENT) != 0 && evData.port != nullptr)
  2847. {
  2848. const LV2_Event* ev;
  2849. LV2_Event_Iterator iter;
  2850. uint8_t* data;
  2851. lv2_event_begin(&iter, evData.event);
  2852. for (;;)
  2853. {
  2854. data = nullptr;
  2855. ev = lv2_event_get(&iter, &data);
  2856. if (ev == nullptr || data == nullptr)
  2857. break;
  2858. if (ev->type == CARLA_URI_MAP_ID_MIDI_EVENT)
  2859. {
  2860. CARLA_SAFE_ASSERT_CONTINUE(ev->size < 0xFF);
  2861. evData.port->writeMidiEvent(ev->frames, static_cast<uint8_t>(ev->size), data);
  2862. }
  2863. lv2_event_increment(&iter);
  2864. }
  2865. }
  2866. else if ((evData.type & CARLA_EVENT_DATA_MIDI_LL) != 0 && evData.port != nullptr)
  2867. {
  2868. LV2_MIDIState state = { &evData.midi, frames, 0 };
  2869. uint32_t eventSize;
  2870. double eventTime;
  2871. uchar* eventData;
  2872. for (;;)
  2873. {
  2874. eventSize = 0;
  2875. eventTime = 0.0;
  2876. eventData = nullptr;
  2877. lv2midi_get_event(&state, &eventTime, &eventSize, &eventData);
  2878. if (eventData == nullptr || eventSize == 0)
  2879. break;
  2880. CARLA_SAFE_ASSERT_CONTINUE(eventSize < 0xFF);
  2881. CARLA_SAFE_ASSERT_CONTINUE(eventTime >= 0.0);
  2882. evData.port->writeMidiEvent(static_cast<uint32_t>(eventTime), static_cast<uint8_t>(eventSize), eventData);
  2883. lv2midi_step(&state);
  2884. }
  2885. }
  2886. }
  2887. #ifndef BUILD_BRIDGE
  2888. // --------------------------------------------------------------------------------------------------------
  2889. // Control Output
  2890. if (pData->event.portOut != nullptr)
  2891. {
  2892. uint8_t channel;
  2893. uint16_t param;
  2894. float value;
  2895. for (uint32_t k=0; k < pData->param.count; ++k)
  2896. {
  2897. if (pData->param.data[k].type != PARAMETER_OUTPUT)
  2898. continue;
  2899. if (fStrictBounds >= 0 && (pData->param.data[k].hints & PARAMETER_IS_STRICT_BOUNDS) != 0)
  2900. // plugin is responsible to ensure correct bounds
  2901. pData->param.ranges[k].fixValue(fParamBuffers[k]);
  2902. if (pData->param.data[k].midiCC > 0)
  2903. {
  2904. channel = pData->param.data[k].midiChannel;
  2905. param = static_cast<uint16_t>(pData->param.data[k].midiCC);
  2906. value = pData->param.ranges[k].getNormalizedValue(fParamBuffers[k]);
  2907. pData->event.portOut->writeControlEvent(0, channel, kEngineControlEventTypeParameter, param, value);
  2908. }
  2909. }
  2910. } // End of Control Output
  2911. #endif
  2912. // --------------------------------------------------------------------------------------------------------
  2913. // Final work
  2914. if (fExt.worker != nullptr && fExt.worker->end_run != nullptr)
  2915. {
  2916. fExt.worker->end_run(fHandle);
  2917. if (fHandle2 != nullptr)
  2918. fExt.worker->end_run(fHandle2);
  2919. }
  2920. fFirstActive = false;
  2921. // --------------------------------------------------------------------------------------------------------
  2922. }
  2923. bool processSingle(const float** const audioIn, float** const audioOut, const float** const cvIn, float** const cvOut, const uint32_t frames, const uint32_t timeOffset)
  2924. {
  2925. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  2926. if (pData->audioIn.count > 0)
  2927. {
  2928. CARLA_SAFE_ASSERT_RETURN(audioIn != nullptr, false);
  2929. }
  2930. if (pData->audioOut.count > 0)
  2931. {
  2932. CARLA_SAFE_ASSERT_RETURN(audioOut != nullptr, false);
  2933. }
  2934. if (pData->cvIn.count > 0)
  2935. {
  2936. CARLA_SAFE_ASSERT_RETURN(cvIn != nullptr, false);
  2937. }
  2938. if (pData->cvOut.count > 0)
  2939. {
  2940. CARLA_SAFE_ASSERT_RETURN(cvOut != nullptr, false);
  2941. }
  2942. // --------------------------------------------------------------------------------------------------------
  2943. // Try lock, silence otherwise
  2944. if (pData->engine->isOffline())
  2945. {
  2946. pData->singleMutex.lock();
  2947. }
  2948. else if (! pData->singleMutex.tryLock())
  2949. {
  2950. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  2951. {
  2952. for (uint32_t k=0; k < frames; ++k)
  2953. audioOut[i][k+timeOffset] = 0.0f;
  2954. }
  2955. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  2956. {
  2957. for (uint32_t k=0; k < frames; ++k)
  2958. cvOut[i][k+timeOffset] = 0.0f;
  2959. }
  2960. return false;
  2961. }
  2962. const int iframes(static_cast<int>(frames));
  2963. // --------------------------------------------------------------------------------------------------------
  2964. // Set audio buffers
  2965. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  2966. FloatVectorOperations::copy(fAudioInBuffers[i], audioIn[i]+timeOffset, iframes);
  2967. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  2968. FloatVectorOperations::clear(fAudioOutBuffers[i], iframes);
  2969. // --------------------------------------------------------------------------------------------------------
  2970. // Set CV buffers
  2971. for (uint32_t i=0; i < pData->cvIn.count; ++i)
  2972. FloatVectorOperations::copy(fCvInBuffers[i], cvIn[i]+timeOffset, iframes);
  2973. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  2974. FloatVectorOperations::clear(fCvOutBuffers[i], iframes);
  2975. // --------------------------------------------------------------------------------------------------------
  2976. // Run plugin
  2977. fDescriptor->run(fHandle, frames);
  2978. if (fHandle2 != nullptr)
  2979. fDescriptor->run(fHandle2, frames);
  2980. // --------------------------------------------------------------------------------------------------------
  2981. // Handle trigger parameters
  2982. for (uint32_t k=0; k < pData->param.count; ++k)
  2983. {
  2984. if (pData->param.data[k].type != PARAMETER_INPUT)
  2985. continue;
  2986. if (pData->param.data[k].hints & PARAMETER_IS_TRIGGER)
  2987. {
  2988. if (carla_isNotEqual(fParamBuffers[k], pData->param.ranges[k].def))
  2989. {
  2990. fParamBuffers[k] = pData->param.ranges[k].def;
  2991. pData->postponeRtEvent(kPluginPostRtEventParameterChange, static_cast<int32_t>(k), 0, fParamBuffers[k]);
  2992. }
  2993. }
  2994. }
  2995. pData->postRtEvents.trySplice();
  2996. #ifndef BUILD_BRIDGE
  2997. // --------------------------------------------------------------------------------------------------------
  2998. // Post-processing (dry/wet, volume and balance)
  2999. {
  3000. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  3001. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  3002. const bool isMono = (pData->audioIn.count == 1);
  3003. bool isPair;
  3004. float bufValue, oldBufLeft[doBalance ? frames : 1];
  3005. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  3006. {
  3007. // Dry/Wet
  3008. if (doDryWet)
  3009. {
  3010. const uint32_t c = isMono ? 0 : i;
  3011. for (uint32_t k=0; k < frames; ++k)
  3012. {
  3013. if (k < pData->latency.frames)
  3014. bufValue = pData->latency.buffers[c][k];
  3015. else if (pData->latency.frames < frames)
  3016. bufValue = fAudioInBuffers[c][k-pData->latency.frames];
  3017. else
  3018. bufValue = fAudioInBuffers[c][k];
  3019. fAudioOutBuffers[i][k] = (fAudioOutBuffers[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  3020. }
  3021. }
  3022. // Balance
  3023. if (doBalance)
  3024. {
  3025. isPair = (i % 2 == 0);
  3026. if (isPair)
  3027. {
  3028. CARLA_ASSERT(i+1 < pData->audioOut.count);
  3029. FloatVectorOperations::copy(oldBufLeft, fAudioOutBuffers[i], iframes);
  3030. }
  3031. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  3032. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  3033. for (uint32_t k=0; k < frames; ++k)
  3034. {
  3035. if (isPair)
  3036. {
  3037. // left
  3038. fAudioOutBuffers[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  3039. fAudioOutBuffers[i][k] += fAudioOutBuffers[i+1][k] * (1.0f - balRangeR);
  3040. }
  3041. else
  3042. {
  3043. // right
  3044. fAudioOutBuffers[i][k] = fAudioOutBuffers[i][k] * balRangeR;
  3045. fAudioOutBuffers[i][k] += oldBufLeft[k] * balRangeL;
  3046. }
  3047. }
  3048. }
  3049. // Volume (and buffer copy)
  3050. {
  3051. for (uint32_t k=0; k < frames; ++k)
  3052. audioOut[i][k+timeOffset] = fAudioOutBuffers[i][k] * pData->postProc.volume;
  3053. }
  3054. }
  3055. } // End of Post-processing
  3056. // --------------------------------------------------------------------------------------------------------
  3057. // Save latency values for next callback
  3058. if (const uint32_t latframes = pData->latency.frames)
  3059. {
  3060. CARLA_SAFE_ASSERT(timeOffset == 0);
  3061. if (latframes <= frames)
  3062. {
  3063. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  3064. FloatVectorOperations::copy(pData->latency.buffers[i], audioIn[i]+(frames-latframes), static_cast<int>(latframes));
  3065. }
  3066. else
  3067. {
  3068. const uint32_t diff = pData->latency.frames-frames;
  3069. for (uint32_t i=0, k; i<pData->audioIn.count; ++i)
  3070. {
  3071. // push back buffer by 'frames'
  3072. for (k=0; k < diff; ++k)
  3073. pData->latency.buffers[i][k] = pData->latency.buffers[i][k+frames];
  3074. // put current input at the end
  3075. for (uint32_t j=0; k < latframes; ++j, ++k)
  3076. pData->latency.buffers[i][k] = audioIn[i][j];
  3077. }
  3078. }
  3079. }
  3080. #else // BUILD_BRIDGE
  3081. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  3082. {
  3083. for (uint32_t k=0; k < frames; ++k)
  3084. audioOut[i][k+timeOffset] = fAudioOutBuffers[i][k];
  3085. }
  3086. #endif
  3087. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  3088. {
  3089. for (uint32_t k=0; k < frames; ++k)
  3090. cvOut[i][k+timeOffset] = fCvOutBuffers[i][k];
  3091. }
  3092. // --------------------------------------------------------------------------------------------------------
  3093. pData->singleMutex.unlock();
  3094. return true;
  3095. }
  3096. void bufferSizeChanged(const uint32_t newBufferSize) override
  3097. {
  3098. CARLA_ASSERT_INT(newBufferSize > 0, newBufferSize);
  3099. carla_debug("CarlaPluginLV2::bufferSizeChanged(%i) - start", newBufferSize);
  3100. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  3101. {
  3102. if (fAudioInBuffers[i] != nullptr)
  3103. delete[] fAudioInBuffers[i];
  3104. fAudioInBuffers[i] = new float[newBufferSize];
  3105. }
  3106. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  3107. {
  3108. if (fAudioOutBuffers[i] != nullptr)
  3109. delete[] fAudioOutBuffers[i];
  3110. fAudioOutBuffers[i] = new float[newBufferSize];
  3111. }
  3112. if (fHandle2 == nullptr)
  3113. {
  3114. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  3115. {
  3116. CARLA_ASSERT(fAudioInBuffers[i] != nullptr);
  3117. fDescriptor->connect_port(fHandle, pData->audioIn.ports[i].rindex, fAudioInBuffers[i]);
  3118. }
  3119. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  3120. {
  3121. CARLA_ASSERT(fAudioOutBuffers[i] != nullptr);
  3122. fDescriptor->connect_port(fHandle, pData->audioOut.ports[i].rindex, fAudioOutBuffers[i]);
  3123. }
  3124. }
  3125. else
  3126. {
  3127. if (pData->audioIn.count > 0)
  3128. {
  3129. CARLA_ASSERT(pData->audioIn.count == 2);
  3130. CARLA_ASSERT(fAudioInBuffers[0] != nullptr);
  3131. CARLA_ASSERT(fAudioInBuffers[1] != nullptr);
  3132. fDescriptor->connect_port(fHandle, pData->audioIn.ports[0].rindex, fAudioInBuffers[0]);
  3133. fDescriptor->connect_port(fHandle2, pData->audioIn.ports[1].rindex, fAudioInBuffers[1]);
  3134. }
  3135. if (pData->audioOut.count > 0)
  3136. {
  3137. CARLA_ASSERT(pData->audioOut.count == 2);
  3138. CARLA_ASSERT(fAudioOutBuffers[0] != nullptr);
  3139. CARLA_ASSERT(fAudioOutBuffers[1] != nullptr);
  3140. fDescriptor->connect_port(fHandle, pData->audioOut.ports[0].rindex, fAudioOutBuffers[0]);
  3141. fDescriptor->connect_port(fHandle2, pData->audioOut.ports[1].rindex, fAudioOutBuffers[1]);
  3142. }
  3143. }
  3144. for (uint32_t i=0; i < pData->cvIn.count; ++i)
  3145. {
  3146. if (fCvInBuffers[i] != nullptr)
  3147. delete[] fCvInBuffers[i];
  3148. fCvInBuffers[i] = new float[newBufferSize];
  3149. fDescriptor->connect_port(fHandle, pData->cvIn.ports[i].rindex, fCvInBuffers[i]);
  3150. if (fHandle2 != nullptr)
  3151. fDescriptor->connect_port(fHandle2, pData->cvIn.ports[i].rindex, fCvInBuffers[i]);
  3152. }
  3153. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  3154. {
  3155. if (fCvOutBuffers[i] != nullptr)
  3156. delete[] fCvOutBuffers[i];
  3157. fCvOutBuffers[i] = new float[newBufferSize];
  3158. fDescriptor->connect_port(fHandle, pData->cvOut.ports[i].rindex, fCvOutBuffers[i]);
  3159. if (fHandle2 != nullptr)
  3160. fDescriptor->connect_port(fHandle2, pData->cvOut.ports[i].rindex, fCvOutBuffers[i]);
  3161. }
  3162. const int newBufferSizeInt(static_cast<int>(newBufferSize));
  3163. if (fLv2Options.maxBufferSize != newBufferSizeInt || (fLv2Options.minBufferSize != 1 && fLv2Options.minBufferSize != newBufferSizeInt))
  3164. {
  3165. fLv2Options.maxBufferSize = fLv2Options.nominalBufferSize = newBufferSizeInt;
  3166. if (fLv2Options.minBufferSize != 1)
  3167. fLv2Options.minBufferSize = newBufferSizeInt;
  3168. if (fExt.options != nullptr && fExt.options->set != nullptr)
  3169. {
  3170. fExt.options->set(fHandle, &fLv2Options.opts[CarlaPluginLV2Options::MaxBlockLenth]);
  3171. fExt.options->set(fHandle, &fLv2Options.opts[CarlaPluginLV2Options::NominalBlockLenth]);
  3172. if (fLv2Options.minBufferSize != 1)
  3173. fExt.options->set(fHandle, &fLv2Options.opts[CarlaPluginLV2Options::MinBlockLenth]);
  3174. }
  3175. }
  3176. carla_debug("CarlaPluginLV2::bufferSizeChanged(%i) - end", newBufferSize);
  3177. }
  3178. void sampleRateChanged(const double newSampleRate) override
  3179. {
  3180. CARLA_ASSERT_INT(newSampleRate > 0.0, newSampleRate);
  3181. carla_debug("CarlaPluginLV2::sampleRateChanged(%g) - start", newSampleRate);
  3182. if (carla_isNotEqual(fLv2Options.sampleRate, newSampleRate))
  3183. {
  3184. fLv2Options.sampleRate = newSampleRate;
  3185. if (fExt.options != nullptr && fExt.options->set != nullptr)
  3186. fExt.options->set(fHandle, &fLv2Options.opts[CarlaPluginLV2Options::SampleRate]);
  3187. }
  3188. for (uint32_t k=0; k < pData->param.count; ++k)
  3189. {
  3190. if (pData->param.data[k].type == PARAMETER_INPUT && pData->param.special[k] == PARAMETER_SPECIAL_SAMPLE_RATE)
  3191. {
  3192. fParamBuffers[k] = static_cast<float>(newSampleRate);
  3193. pData->postponeRtEvent(kPluginPostRtEventParameterChange, static_cast<int32_t>(k), 1, fParamBuffers[k]);
  3194. break;
  3195. }
  3196. }
  3197. carla_debug("CarlaPluginLV2::sampleRateChanged(%g) - end", newSampleRate);
  3198. }
  3199. void offlineModeChanged(const bool isOffline) override
  3200. {
  3201. for (uint32_t k=0; k < pData->param.count; ++k)
  3202. {
  3203. if (pData->param.data[k].type == PARAMETER_INPUT && pData->param.special[k] == PARAMETER_SPECIAL_FREEWHEEL)
  3204. {
  3205. fParamBuffers[k] = isOffline ? pData->param.ranges[k].max : pData->param.ranges[k].min;
  3206. pData->postponeRtEvent(kPluginPostRtEventParameterChange, static_cast<int32_t>(k), 1, fParamBuffers[k]);
  3207. break;
  3208. }
  3209. }
  3210. }
  3211. // -------------------------------------------------------------------
  3212. // Plugin buffers
  3213. void initBuffers() const noexcept override
  3214. {
  3215. fEventsIn.initBuffers();
  3216. fEventsOut.initBuffers();
  3217. CarlaPlugin::initBuffers();
  3218. }
  3219. void clearBuffers() noexcept override
  3220. {
  3221. carla_debug("CarlaPluginLV2::clearBuffers() - start");
  3222. if (fAudioInBuffers != nullptr)
  3223. {
  3224. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  3225. {
  3226. if (fAudioInBuffers[i] != nullptr)
  3227. {
  3228. delete[] fAudioInBuffers[i];
  3229. fAudioInBuffers[i] = nullptr;
  3230. }
  3231. }
  3232. delete[] fAudioInBuffers;
  3233. fAudioInBuffers = nullptr;
  3234. }
  3235. if (fAudioOutBuffers != nullptr)
  3236. {
  3237. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  3238. {
  3239. if (fAudioOutBuffers[i] != nullptr)
  3240. {
  3241. delete[] fAudioOutBuffers[i];
  3242. fAudioOutBuffers[i] = nullptr;
  3243. }
  3244. }
  3245. delete[] fAudioOutBuffers;
  3246. fAudioOutBuffers = nullptr;
  3247. }
  3248. if (fCvInBuffers != nullptr)
  3249. {
  3250. for (uint32_t i=0; i < pData->cvIn.count; ++i)
  3251. {
  3252. if (fCvInBuffers[i] != nullptr)
  3253. {
  3254. delete[] fCvInBuffers[i];
  3255. fCvInBuffers[i] = nullptr;
  3256. }
  3257. }
  3258. delete[] fCvInBuffers;
  3259. fCvInBuffers = nullptr;
  3260. }
  3261. if (fCvOutBuffers != nullptr)
  3262. {
  3263. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  3264. {
  3265. if (fCvOutBuffers[i] != nullptr)
  3266. {
  3267. delete[] fCvOutBuffers[i];
  3268. fCvOutBuffers[i] = nullptr;
  3269. }
  3270. }
  3271. delete[] fCvOutBuffers;
  3272. fCvOutBuffers = nullptr;
  3273. }
  3274. if (fParamBuffers != nullptr)
  3275. {
  3276. delete[] fParamBuffers;
  3277. fParamBuffers = nullptr;
  3278. }
  3279. fEventsIn.clear();
  3280. fEventsOut.clear();
  3281. CarlaPlugin::clearBuffers();
  3282. carla_debug("CarlaPluginLV2::clearBuffers() - end");
  3283. }
  3284. // -------------------------------------------------------------------
  3285. // Post-poned UI Stuff
  3286. void uiParameterChange(const uint32_t index, const float value) noexcept override
  3287. {
  3288. CARLA_SAFE_ASSERT_RETURN(fUI.type != UI::TYPE_NULL,);
  3289. CARLA_SAFE_ASSERT_RETURN(index < pData->param.count,);
  3290. if (fUI.type == UI::TYPE_BRIDGE)
  3291. {
  3292. if (fPipeServer.isPipeRunning())
  3293. fPipeServer.writeControlMessage(static_cast<uint32_t>(pData->param.data[index].rindex), value);
  3294. }
  3295. else
  3296. {
  3297. if (fUI.handle != nullptr && fUI.descriptor != nullptr && fUI.descriptor->port_event != nullptr && ! fNeedsUiClose)
  3298. {
  3299. CARLA_SAFE_ASSERT_RETURN(pData->param.data[index].rindex >= 0,);
  3300. fUI.descriptor->port_event(fUI.handle, static_cast<uint32_t>(pData->param.data[index].rindex), sizeof(float), CARLA_URI_MAP_ID_NULL, &value);
  3301. }
  3302. }
  3303. }
  3304. void uiMidiProgramChange(const uint32_t index) noexcept override
  3305. {
  3306. CARLA_SAFE_ASSERT_RETURN(fUI.type != UI::TYPE_NULL,);
  3307. CARLA_SAFE_ASSERT_RETURN(index < pData->midiprog.count,);
  3308. if (fUI.type == UI::TYPE_BRIDGE)
  3309. {
  3310. if (fPipeServer.isPipeRunning())
  3311. fPipeServer.writeMidiProgramMessage(pData->midiprog.data[index].bank, pData->midiprog.data[index].program);
  3312. }
  3313. else
  3314. {
  3315. if (fExt.uiprograms != nullptr && fExt.uiprograms->select_program != nullptr && ! fNeedsUiClose)
  3316. fExt.uiprograms->select_program(fUI.handle, pData->midiprog.data[index].bank, pData->midiprog.data[index].program);
  3317. }
  3318. }
  3319. void uiNoteOn(const uint8_t channel, const uint8_t note, const uint8_t velo) noexcept override
  3320. {
  3321. CARLA_SAFE_ASSERT_RETURN(fUI.type != UI::TYPE_NULL,);
  3322. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  3323. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  3324. CARLA_SAFE_ASSERT_RETURN(velo > 0 && velo < MAX_MIDI_VALUE,);
  3325. if (fUI.type == UI::TYPE_BRIDGE)
  3326. {
  3327. if (fPipeServer.isPipeRunning())
  3328. fPipeServer.writeMidiNoteMessage(false, channel, note, velo);
  3329. }
  3330. else
  3331. {
  3332. if (fUI.handle != nullptr && fUI.descriptor != nullptr && fUI.descriptor->port_event != nullptr && fEventsIn.ctrl != nullptr && ! fNeedsUiClose)
  3333. {
  3334. LV2_Atom_MidiEvent midiEv;
  3335. midiEv.atom.type = CARLA_URI_MAP_ID_MIDI_EVENT;
  3336. midiEv.atom.size = 3;
  3337. midiEv.data[0] = uint8_t(MIDI_STATUS_NOTE_ON | (channel & MIDI_CHANNEL_BIT));
  3338. midiEv.data[1] = note;
  3339. midiEv.data[2] = velo;
  3340. fUI.descriptor->port_event(fUI.handle, fEventsIn.ctrl->rindex, lv2_atom_total_size(midiEv), CARLA_URI_MAP_ID_ATOM_TRANSFER_EVENT, &midiEv);
  3341. }
  3342. }
  3343. }
  3344. void uiNoteOff(const uint8_t channel, const uint8_t note) noexcept override
  3345. {
  3346. CARLA_SAFE_ASSERT_RETURN(fUI.type != UI::TYPE_NULL,);
  3347. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  3348. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  3349. if (fUI.type == UI::TYPE_BRIDGE)
  3350. {
  3351. if (fPipeServer.isPipeRunning())
  3352. fPipeServer.writeMidiNoteMessage(false, channel, note, 0);
  3353. }
  3354. else
  3355. {
  3356. if (fUI.handle != nullptr && fUI.descriptor != nullptr && fUI.descriptor->port_event != nullptr && fEventsIn.ctrl != nullptr && ! fNeedsUiClose)
  3357. {
  3358. LV2_Atom_MidiEvent midiEv;
  3359. midiEv.atom.type = CARLA_URI_MAP_ID_MIDI_EVENT;
  3360. midiEv.atom.size = 3;
  3361. midiEv.data[0] = uint8_t(MIDI_STATUS_NOTE_OFF | (channel & MIDI_CHANNEL_BIT));
  3362. midiEv.data[1] = note;
  3363. midiEv.data[2] = 0;
  3364. fUI.descriptor->port_event(fUI.handle, fEventsIn.ctrl->rindex, lv2_atom_total_size(midiEv), CARLA_URI_MAP_ID_ATOM_TRANSFER_EVENT, &midiEv);
  3365. }
  3366. }
  3367. }
  3368. // -------------------------------------------------------------------
  3369. bool isRealtimeSafe() const noexcept
  3370. {
  3371. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr, false);
  3372. for (uint32_t i=0; i < fRdfDescriptor->FeatureCount; ++i)
  3373. {
  3374. if (std::strcmp(fRdfDescriptor->Features[i].URI, LV2_CORE__hardRTCapable) == 0)
  3375. return true;
  3376. }
  3377. return false;
  3378. }
  3379. // -------------------------------------------------------------------
  3380. bool isUiBridgeable(const uint32_t uiId) const noexcept
  3381. {
  3382. CARLA_SAFE_ASSERT_RETURN(uiId < fRdfDescriptor->UICount, false);
  3383. #ifndef LV2_UIS_ONLY_INPROCESS
  3384. const LV2_RDF_UI* const rdfUI(&fRdfDescriptor->UIs[uiId]);
  3385. for (uint32_t i=0; i < rdfUI->FeatureCount; ++i)
  3386. {
  3387. const LV2_RDF_Feature& feat(rdfUI->Features[i]);
  3388. if (! feat.Required)
  3389. continue;
  3390. if (std::strcmp(feat.URI, LV2_INSTANCE_ACCESS_URI) == 0)
  3391. return false;
  3392. if (std::strcmp(feat.URI, LV2_DATA_ACCESS_URI) == 0)
  3393. return false;
  3394. }
  3395. // Calf UIs are mostly useless without their special graphs
  3396. // but they can be crashy under certain conditions, so follow user preferences
  3397. if (std::strstr(rdfUI->URI, "http://calf.sourceforge.net/plugins/gui/") != nullptr)
  3398. return pData->engine->getOptions().preferUiBridges;
  3399. return true;
  3400. #else
  3401. return false;
  3402. #endif
  3403. }
  3404. bool isUiResizable() const noexcept
  3405. {
  3406. CARLA_SAFE_ASSERT_RETURN(fUI.rdfDescriptor != nullptr, false);
  3407. for (uint32_t i=0; i < fUI.rdfDescriptor->FeatureCount; ++i)
  3408. {
  3409. if (std::strcmp(fUI.rdfDescriptor->Features[i].URI, LV2_UI__fixedSize) == 0)
  3410. return false;
  3411. if (std::strcmp(fUI.rdfDescriptor->Features[i].URI, LV2_UI__noUserResize) == 0)
  3412. return false;
  3413. }
  3414. return true;
  3415. }
  3416. const char* getUiBridgeBinary(const LV2_Property type) const
  3417. {
  3418. CarlaString bridgeBinary(pData->engine->getOptions().binaryDir);
  3419. if (bridgeBinary.isEmpty())
  3420. return nullptr;
  3421. switch (type)
  3422. {
  3423. case LV2_UI_GTK2:
  3424. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-gtk2";
  3425. break;
  3426. case LV2_UI_GTK3:
  3427. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-gtk3";
  3428. break;
  3429. case LV2_UI_QT4:
  3430. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-qt4";
  3431. break;
  3432. case LV2_UI_QT5:
  3433. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-qt5";
  3434. break;
  3435. case LV2_UI_COCOA:
  3436. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-cocoa";
  3437. break;
  3438. case LV2_UI_WINDOWS:
  3439. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-windows";
  3440. break;
  3441. case LV2_UI_X11:
  3442. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-x11";
  3443. break;
  3444. case LV2_UI_EXTERNAL:
  3445. case LV2_UI_OLD_EXTERNAL:
  3446. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-external";
  3447. break;
  3448. case LV2_UI_MOD:
  3449. bridgeBinary += CARLA_OS_SEP_STR "carla-bridge-lv2-modgui";
  3450. break;
  3451. default:
  3452. return nullptr;
  3453. }
  3454. #ifdef CARLA_OS_WIN
  3455. bridgeBinary += ".exe";
  3456. #endif
  3457. if (! File(bridgeBinary.buffer()).existsAsFile())
  3458. return nullptr;
  3459. return bridgeBinary.dup();
  3460. }
  3461. // -------------------------------------------------------------------
  3462. void recheckExtensions()
  3463. {
  3464. CARLA_SAFE_ASSERT_RETURN(fRdfDescriptor != nullptr,);
  3465. carla_debug("CarlaPluginLV2::recheckExtensions()");
  3466. fExt.options = nullptr;
  3467. fExt.programs = nullptr;
  3468. fExt.state = nullptr;
  3469. fExt.worker = nullptr;
  3470. fExt.inlineDisplay = nullptr;
  3471. for (uint32_t i=0; i < fRdfDescriptor->ExtensionCount; ++i)
  3472. {
  3473. CARLA_SAFE_ASSERT_CONTINUE(fRdfDescriptor->Extensions[i] != nullptr);
  3474. if (std::strcmp(fRdfDescriptor->Extensions[i], LV2_OPTIONS__interface) == 0)
  3475. pData->hints |= PLUGIN_HAS_EXTENSION_OPTIONS;
  3476. else if (std::strcmp(fRdfDescriptor->Extensions[i], LV2_PROGRAMS__Interface) == 0)
  3477. pData->hints |= PLUGIN_HAS_EXTENSION_PROGRAMS;
  3478. else if (std::strcmp(fRdfDescriptor->Extensions[i], LV2_STATE__interface) == 0)
  3479. pData->hints |= PLUGIN_HAS_EXTENSION_STATE;
  3480. else if (std::strcmp(fRdfDescriptor->Extensions[i], LV2_WORKER__interface) == 0)
  3481. pData->hints |= PLUGIN_HAS_EXTENSION_WORKER;
  3482. else if (std::strcmp(fRdfDescriptor->Extensions[i], LV2_INLINEDISPLAY__interface) == 0)
  3483. pData->hints |= PLUGIN_HAS_EXTENSION_INLINE_DISPLAY;
  3484. else
  3485. carla_stdout("Plugin has non-supported extension: '%s'", fRdfDescriptor->Extensions[i]);
  3486. }
  3487. if (fDescriptor->extension_data != nullptr)
  3488. {
  3489. if (pData->hints & PLUGIN_HAS_EXTENSION_OPTIONS)
  3490. fExt.options = (const LV2_Options_Interface*)fDescriptor->extension_data(LV2_OPTIONS__interface);
  3491. if (pData->hints & PLUGIN_HAS_EXTENSION_PROGRAMS)
  3492. fExt.programs = (const LV2_Programs_Interface*)fDescriptor->extension_data(LV2_PROGRAMS__Interface);
  3493. if (pData->hints & PLUGIN_HAS_EXTENSION_STATE)
  3494. fExt.state = (const LV2_State_Interface*)fDescriptor->extension_data(LV2_STATE__interface);
  3495. if (pData->hints & PLUGIN_HAS_EXTENSION_WORKER)
  3496. fExt.worker = (const LV2_Worker_Interface*)fDescriptor->extension_data(LV2_WORKER__interface);
  3497. if (pData->hints & PLUGIN_HAS_EXTENSION_INLINE_DISPLAY)
  3498. fExt.inlineDisplay = (const LV2_Inline_Display_Interface*)fDescriptor->extension_data(LV2_INLINEDISPLAY__interface);
  3499. // check if invalid
  3500. if (fExt.options != nullptr && fExt.options->get == nullptr && fExt.options->set == nullptr)
  3501. fExt.options = nullptr;
  3502. if (fExt.programs != nullptr && (fExt.programs->get_program == nullptr || fExt.programs->select_program == nullptr))
  3503. fExt.programs = nullptr;
  3504. if (fExt.state != nullptr && (fExt.state->save == nullptr || fExt.state->restore == nullptr))
  3505. fExt.state = nullptr;
  3506. if (fExt.worker != nullptr && fExt.worker->work == nullptr)
  3507. fExt.worker = nullptr;
  3508. if (fExt.inlineDisplay != nullptr)
  3509. {
  3510. if (fExt.inlineDisplay->render != nullptr)
  3511. pData->hints |= PLUGIN_HAS_INLINE_DISPLAY;
  3512. else
  3513. fExt.inlineDisplay = nullptr;
  3514. }
  3515. }
  3516. CARLA_SAFE_ASSERT_RETURN(fLatencyIndex == -1,);
  3517. int32_t iCtrl=0;
  3518. for (uint32_t i=0, count=fRdfDescriptor->PortCount; i<count; ++i)
  3519. {
  3520. const LV2_Property portTypes(fRdfDescriptor->Ports[i].Types);
  3521. if (! LV2_IS_PORT_CONTROL(portTypes))
  3522. continue;
  3523. const ScopedValueSetter<int32_t> svs(iCtrl, iCtrl, iCtrl+1);
  3524. if (! LV2_IS_PORT_OUTPUT(portTypes))
  3525. continue;
  3526. const LV2_Property portDesignation(fRdfDescriptor->Ports[i].Designation);
  3527. if (! LV2_IS_PORT_DESIGNATION_LATENCY(portDesignation))
  3528. continue;
  3529. fLatencyIndex = iCtrl;
  3530. break;
  3531. }
  3532. }
  3533. // -------------------------------------------------------------------
  3534. void updateUi()
  3535. {
  3536. CARLA_SAFE_ASSERT_RETURN(fUI.handle != nullptr,);
  3537. CARLA_SAFE_ASSERT_RETURN(fUI.descriptor != nullptr,);
  3538. carla_debug("CarlaPluginLV2::updateUi()");
  3539. // update midi program
  3540. if (fExt.uiprograms != nullptr && pData->midiprog.count > 0 && pData->midiprog.current >= 0)
  3541. {
  3542. const MidiProgramData& curData(pData->midiprog.getCurrent());
  3543. fExt.uiprograms->select_program(fUI.handle, curData.bank, curData.program);
  3544. }
  3545. // update control ports
  3546. if (fUI.descriptor->port_event != nullptr)
  3547. {
  3548. float value;
  3549. for (uint32_t i=0; i < pData->param.count; ++i)
  3550. {
  3551. value = getParameterValue(i);
  3552. fUI.descriptor->port_event(fUI.handle, static_cast<uint32_t>(pData->param.data[i].rindex), sizeof(float), CARLA_URI_MAP_ID_NULL, &value);
  3553. }
  3554. }
  3555. }
  3556. // -------------------------------------------------------------------
  3557. LV2_URID getCustomURID(const char* const uri)
  3558. {
  3559. CARLA_SAFE_ASSERT_RETURN(uri != nullptr && uri[0] != '\0', CARLA_URI_MAP_ID_NULL);
  3560. carla_debug("CarlaPluginLV2::getCustomURID(\"%s\")", uri);
  3561. const std::string s_uri(uri);
  3562. const std::ptrdiff_t s_pos(std::find(fCustomURIDs.begin(), fCustomURIDs.end(), s_uri) - fCustomURIDs.begin());
  3563. if (s_pos <= 0 || s_pos >= INT32_MAX)
  3564. return CARLA_URI_MAP_ID_NULL;
  3565. const LV2_URID urid = static_cast<LV2_URID>(s_pos);
  3566. const LV2_URID uriCount = static_cast<LV2_URID>(fCustomURIDs.size());
  3567. if (urid < uriCount)
  3568. return urid;
  3569. CARLA_SAFE_ASSERT(urid == uriCount);
  3570. fCustomURIDs.push_back(uri);
  3571. if (fUI.type == UI::TYPE_BRIDGE && fPipeServer.isPipeRunning())
  3572. fPipeServer.writeLv2UridMessage(uriCount, uri);
  3573. return urid;
  3574. }
  3575. const char* getCustomURIDString(const LV2_URID urid) const noexcept
  3576. {
  3577. static const char* const sFallback = "urn:null";
  3578. CARLA_SAFE_ASSERT_RETURN(urid != CARLA_URI_MAP_ID_NULL, sFallback);
  3579. CARLA_SAFE_ASSERT_RETURN(urid < fCustomURIDs.size(), sFallback);
  3580. carla_debug("CarlaPluginLV2::getCustomURIString(%i)", urid);
  3581. return fCustomURIDs[urid].c_str();
  3582. }
  3583. // -------------------------------------------------------------------
  3584. void handleProgramChanged(const int32_t index)
  3585. {
  3586. CARLA_SAFE_ASSERT_RETURN(index >= -1,);
  3587. carla_debug("CarlaPluginLV2::handleProgramChanged(%i)", index);
  3588. if (index == -1)
  3589. {
  3590. const ScopedSingleProcessLocker spl(this, true);
  3591. return reloadPrograms(false);
  3592. }
  3593. if (index < static_cast<int32_t>(pData->midiprog.count) && fExt.programs != nullptr && fExt.programs->get_program != nullptr)
  3594. {
  3595. if (const LV2_Program_Descriptor* const progDesc = fExt.programs->get_program(fHandle, static_cast<uint32_t>(index)))
  3596. {
  3597. CARLA_SAFE_ASSERT_RETURN(progDesc->name != nullptr,);
  3598. if (pData->midiprog.data[index].name != nullptr)
  3599. delete[] pData->midiprog.data[index].name;
  3600. pData->midiprog.data[index].name = carla_strdup(progDesc->name);
  3601. if (index == pData->midiprog.current)
  3602. pData->engine->callback(ENGINE_CALLBACK_UPDATE, pData->id, 0, 0, 0.0, nullptr);
  3603. else
  3604. pData->engine->callback(ENGINE_CALLBACK_RELOAD_PROGRAMS, pData->id, 0, 0, 0.0, nullptr);
  3605. }
  3606. }
  3607. }
  3608. // -------------------------------------------------------------------
  3609. LV2_Resize_Port_Status handleResizePort(const uint32_t index, const size_t size)
  3610. {
  3611. CARLA_SAFE_ASSERT_RETURN(size > 0, LV2_RESIZE_PORT_ERR_UNKNOWN);
  3612. carla_debug("CarlaPluginLV2::handleResizePort(%i, " P_SIZE ")", index, size);
  3613. // TODO
  3614. return LV2_RESIZE_PORT_ERR_NO_SPACE;
  3615. (void)index;
  3616. }
  3617. // -------------------------------------------------------------------
  3618. LV2_State_Status handleStateStore(const uint32_t key, const void* const value, const size_t size, const uint32_t type, const uint32_t flags)
  3619. {
  3620. CARLA_SAFE_ASSERT_RETURN(key != CARLA_URI_MAP_ID_NULL, LV2_STATE_ERR_NO_PROPERTY);
  3621. CARLA_SAFE_ASSERT_RETURN(value != nullptr, LV2_STATE_ERR_NO_PROPERTY);
  3622. CARLA_SAFE_ASSERT_RETURN(size > 0, LV2_STATE_ERR_NO_PROPERTY);
  3623. CARLA_SAFE_ASSERT_RETURN(type != CARLA_URI_MAP_ID_NULL, LV2_STATE_ERR_BAD_TYPE);
  3624. CARLA_SAFE_ASSERT_RETURN(flags & LV2_STATE_IS_POD, LV2_STATE_ERR_BAD_FLAGS);
  3625. carla_debug("CarlaPluginLV2::handleStateStore(%i:\"%s\", %p, " P_SIZE ", %i:\"%s\", %i)", key, carla_lv2_urid_unmap(this, key), value, size, type, carla_lv2_urid_unmap(this, type), flags);
  3626. const char* const skey(carla_lv2_urid_unmap(this, key));
  3627. const char* const stype(carla_lv2_urid_unmap(this, type));
  3628. CARLA_SAFE_ASSERT_RETURN(skey != nullptr, LV2_STATE_ERR_BAD_TYPE);
  3629. CARLA_SAFE_ASSERT_RETURN(stype != nullptr, LV2_STATE_ERR_BAD_TYPE);
  3630. // Check if we already have this key
  3631. for (LinkedList<CustomData>::Itenerator it = pData->custom.begin2(); it.valid(); it.next())
  3632. {
  3633. CustomData& cData(it.getValue(kCustomDataFallbackNC));
  3634. CARLA_SAFE_ASSERT_CONTINUE(cData.isValid());
  3635. if (std::strcmp(cData.key, skey) == 0)
  3636. {
  3637. // found it
  3638. delete[] cData.value;
  3639. if (type == CARLA_URI_MAP_ID_ATOM_STRING || type == CARLA_URI_MAP_ID_ATOM_PATH)
  3640. cData.value = carla_strdup((const char*)value);
  3641. else
  3642. cData.value = CarlaString::asBase64(value, size).dup();
  3643. return LV2_STATE_SUCCESS;
  3644. }
  3645. }
  3646. // Otherwise store it
  3647. CustomData newData;
  3648. newData.type = carla_strdup(stype);
  3649. newData.key = carla_strdup(skey);
  3650. if (type == CARLA_URI_MAP_ID_ATOM_STRING || type == CARLA_URI_MAP_ID_ATOM_PATH)
  3651. newData.value = carla_strdup((const char*)value);
  3652. else
  3653. newData.value = CarlaString::asBase64(value, size).dup();
  3654. pData->custom.append(newData);
  3655. return LV2_STATE_SUCCESS;
  3656. }
  3657. const void* handleStateRetrieve(const uint32_t key, size_t* const size, uint32_t* const type, uint32_t* const flags)
  3658. {
  3659. CARLA_SAFE_ASSERT_RETURN(key != CARLA_URI_MAP_ID_NULL, nullptr);
  3660. CARLA_SAFE_ASSERT_RETURN(size != nullptr, nullptr);
  3661. CARLA_SAFE_ASSERT_RETURN(type != nullptr, nullptr);
  3662. CARLA_SAFE_ASSERT_RETURN(flags != nullptr, nullptr);
  3663. carla_debug("CarlaPluginLV2::handleStateRetrieve(%i, %p, %p, %p)", key, size, type, flags);
  3664. const char* const skey(carla_lv2_urid_unmap(this, key));
  3665. CARLA_SAFE_ASSERT_RETURN(skey != nullptr, nullptr);
  3666. const char* stype = nullptr;
  3667. const char* stringData = nullptr;
  3668. for (LinkedList<CustomData>::Itenerator it = pData->custom.begin2(); it.valid(); it.next())
  3669. {
  3670. const CustomData& cData(it.getValue(kCustomDataFallback));
  3671. CARLA_SAFE_ASSERT_CONTINUE(cData.isValid());
  3672. if (std::strcmp(cData.key, skey) == 0)
  3673. {
  3674. stype = cData.type;
  3675. stringData = cData.value;
  3676. break;
  3677. }
  3678. }
  3679. CARLA_SAFE_ASSERT_RETURN(stype != nullptr, nullptr);
  3680. CARLA_SAFE_ASSERT_RETURN(stringData != nullptr, nullptr);
  3681. *type = carla_lv2_urid_map(this, stype);
  3682. *flags = LV2_STATE_IS_POD;
  3683. if (*type == CARLA_URI_MAP_ID_ATOM_STRING || *type == CARLA_URI_MAP_ID_ATOM_PATH)
  3684. {
  3685. *size = std::strlen(stringData);
  3686. return stringData;
  3687. }
  3688. else
  3689. {
  3690. if (fLastStateChunk != nullptr)
  3691. {
  3692. std::free(fLastStateChunk);
  3693. fLastStateChunk = nullptr;
  3694. }
  3695. std::vector<uint8_t> chunk(carla_getChunkFromBase64String(stringData));
  3696. CARLA_SAFE_ASSERT_RETURN(chunk.size() > 0, nullptr);
  3697. fLastStateChunk = std::malloc(chunk.size());
  3698. CARLA_SAFE_ASSERT_RETURN(fLastStateChunk != nullptr, nullptr);
  3699. std::memcpy(fLastStateChunk, chunk.data(), chunk.size());
  3700. *size = chunk.size();
  3701. return fLastStateChunk;
  3702. }
  3703. }
  3704. // -------------------------------------------------------------------
  3705. LV2_Worker_Status handleWorkerSchedule(const uint32_t size, const void* const data)
  3706. {
  3707. CARLA_SAFE_ASSERT_RETURN(fExt.worker != nullptr && fExt.worker->work != nullptr, LV2_WORKER_ERR_UNKNOWN);
  3708. CARLA_SAFE_ASSERT_RETURN(fEventsIn.ctrl != nullptr, LV2_WORKER_ERR_UNKNOWN);
  3709. carla_debug("CarlaPluginLV2::handleWorkerSchedule(%i, %p)", size, data);
  3710. if (pData->engine->isOffline())
  3711. {
  3712. fExt.worker->work(fHandle, carla_lv2_worker_respond, this, size, data);
  3713. return LV2_WORKER_SUCCESS;
  3714. }
  3715. LV2_Atom atom;
  3716. atom.size = size;
  3717. atom.type = CARLA_URI_MAP_ID_CARLA_ATOM_WORKER;
  3718. return fAtomBufferOut.putChunk(&atom, data, fEventsOut.ctrlIndex) ? LV2_WORKER_SUCCESS : LV2_WORKER_ERR_NO_SPACE;
  3719. }
  3720. LV2_Worker_Status handleWorkerRespond(const uint32_t size, const void* const data)
  3721. {
  3722. carla_debug("CarlaPluginLV2::handleWorkerRespond(%i, %p)", size, data);
  3723. LV2_Atom atom;
  3724. atom.size = size;
  3725. atom.type = CARLA_URI_MAP_ID_CARLA_ATOM_WORKER;
  3726. return fAtomBufferIn.putChunk(&atom, data, fEventsIn.ctrlIndex) ? LV2_WORKER_SUCCESS : LV2_WORKER_ERR_NO_SPACE;
  3727. }
  3728. // -------------------------------------------------------------------
  3729. void handleInlineDisplayQueueRedraw()
  3730. {
  3731. // TODO
  3732. }
  3733. LV2_Inline_Display_Image_Surface* renderInlineDisplay(int width, int height)
  3734. {
  3735. CARLA_SAFE_ASSERT_RETURN(fExt.inlineDisplay != nullptr && fExt.inlineDisplay->render != nullptr, nullptr);
  3736. return fExt.inlineDisplay->render(fHandle, width, height);
  3737. }
  3738. // -------------------------------------------------------------------
  3739. void handleExternalUIClosed()
  3740. {
  3741. CARLA_SAFE_ASSERT_RETURN(fUI.type == UI::TYPE_EXTERNAL,);
  3742. carla_debug("CarlaPluginLV2::handleExternalUIClosed()");
  3743. fNeedsUiClose = true;
  3744. }
  3745. void handlePluginUIClosed() override
  3746. {
  3747. CARLA_SAFE_ASSERT_RETURN(fUI.type == UI::TYPE_EMBED,);
  3748. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  3749. carla_debug("CarlaPluginLV2::handlePluginUIClosed()");
  3750. fNeedsUiClose = true;
  3751. }
  3752. void handlePluginUIResized(const uint width, const uint height) override
  3753. {
  3754. CARLA_SAFE_ASSERT_RETURN(fUI.type == UI::TYPE_EMBED,);
  3755. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  3756. carla_debug("CarlaPluginLV2::handlePluginUIResized(%u, %u)", width, height);
  3757. if (fUI.handle != nullptr && fExt.uiresize != nullptr)
  3758. fExt.uiresize->ui_resize(fUI.handle, static_cast<int>(width), static_cast<int>(height));
  3759. }
  3760. // -------------------------------------------------------------------
  3761. uint32_t handleUIPortMap(const char* const symbol) const noexcept
  3762. {
  3763. CARLA_SAFE_ASSERT_RETURN(symbol != nullptr && symbol[0] != '\0', LV2UI_INVALID_PORT_INDEX);
  3764. carla_debug("CarlaPluginLV2::handleUIPortMap(\"%s\")", symbol);
  3765. for (uint32_t i=0; i < fRdfDescriptor->PortCount; ++i)
  3766. {
  3767. if (std::strcmp(fRdfDescriptor->Ports[i].Symbol, symbol) == 0)
  3768. return i;
  3769. }
  3770. return LV2UI_INVALID_PORT_INDEX;
  3771. }
  3772. int handleUIResize(const int width, const int height)
  3773. {
  3774. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr, 1);
  3775. CARLA_SAFE_ASSERT_RETURN(width > 0, 1);
  3776. CARLA_SAFE_ASSERT_RETURN(height > 0, 1);
  3777. carla_debug("CarlaPluginLV2::handleUIResize(%i, %i)", width, height);
  3778. fUI.window->setSize(static_cast<uint>(width), static_cast<uint>(height), true);
  3779. return 0;
  3780. }
  3781. void handleUIWrite(const uint32_t rindex, const uint32_t bufferSize, const uint32_t format, const void* const buffer)
  3782. {
  3783. CARLA_SAFE_ASSERT_RETURN(buffer != nullptr,);
  3784. CARLA_SAFE_ASSERT_RETURN(bufferSize > 0,);
  3785. carla_debug("CarlaPluginLV2::handleUIWrite(%i, %i, %i, %p)", rindex, bufferSize, format, buffer);
  3786. uint32_t index = LV2UI_INVALID_PORT_INDEX;
  3787. switch (format)
  3788. {
  3789. case CARLA_URI_MAP_ID_NULL: {
  3790. CARLA_SAFE_ASSERT_RETURN(bufferSize == sizeof(float),);
  3791. for (uint32_t i=0; i < pData->param.count; ++i)
  3792. {
  3793. if (pData->param.data[i].rindex != static_cast<int32_t>(rindex))
  3794. continue;
  3795. index = i;
  3796. break;
  3797. }
  3798. CARLA_SAFE_ASSERT_RETURN(index != LV2UI_INVALID_PORT_INDEX,);
  3799. const float value(*(const float*)buffer);
  3800. //if (carla_isNotEqual(fParamBuffers[index], value))
  3801. setParameterValue(index, value, false, true, true);
  3802. } break;
  3803. case CARLA_URI_MAP_ID_ATOM_TRANSFER_ATOM:
  3804. case CARLA_URI_MAP_ID_ATOM_TRANSFER_EVENT: {
  3805. CARLA_SAFE_ASSERT_RETURN(bufferSize >= sizeof(LV2_Atom),);
  3806. const LV2_Atom* const atom((const LV2_Atom*)buffer);
  3807. // plugins sometimes fail on this, not good...
  3808. CARLA_SAFE_ASSERT_INT2(bufferSize == lv2_atom_total_size(atom), bufferSize, atom->size);
  3809. for (uint32_t i=0; i < fEventsIn.count; ++i)
  3810. {
  3811. if (fEventsIn.data[i].rindex != rindex)
  3812. continue;
  3813. index = i;
  3814. break;
  3815. }
  3816. // for bad plugins
  3817. if (index == LV2UI_INVALID_PORT_INDEX)
  3818. {
  3819. CARLA_SAFE_ASSERT(index != LV2UI_INVALID_PORT_INDEX); // FIXME
  3820. index = fEventsIn.ctrlIndex;
  3821. }
  3822. fAtomBufferIn.put(atom, index);
  3823. } break;
  3824. default:
  3825. carla_stdout("CarlaPluginLV2::handleUIWrite(%i, %i, %i:\"%s\", %p) - unknown format", rindex, bufferSize, format, carla_lv2_urid_unmap(this, format), buffer);
  3826. break;
  3827. }
  3828. }
  3829. // -------------------------------------------------------------------
  3830. void handleLilvSetPortValue(const char* const portSymbol, const void* const value, const uint32_t size, const uint32_t type)
  3831. {
  3832. CARLA_SAFE_ASSERT_RETURN(portSymbol != nullptr && portSymbol[0] != '\0',);
  3833. CARLA_SAFE_ASSERT_RETURN(value != nullptr,);
  3834. CARLA_SAFE_ASSERT_RETURN(size > 0,);
  3835. CARLA_SAFE_ASSERT_RETURN(type != CARLA_URI_MAP_ID_NULL,);
  3836. carla_debug("CarlaPluginLV2::handleLilvSetPortValue(\"%s\", %p, %i, %i)", portSymbol, value, size, type);
  3837. int32_t rindex = -1;
  3838. for (uint32_t i=0; i < fRdfDescriptor->PortCount; ++i)
  3839. {
  3840. if (std::strcmp(fRdfDescriptor->Ports[i].Symbol, portSymbol) == 0)
  3841. {
  3842. rindex = static_cast<int32_t>(i);
  3843. break;
  3844. }
  3845. }
  3846. CARLA_SAFE_ASSERT_RETURN(rindex >= 0,);
  3847. float paramValue;
  3848. switch (type)
  3849. {
  3850. case CARLA_URI_MAP_ID_ATOM_BOOL:
  3851. CARLA_SAFE_ASSERT_RETURN(size == sizeof(bool),);
  3852. paramValue = (*(const bool*)value) ? 1.0f : 0.0f;
  3853. break;
  3854. case CARLA_URI_MAP_ID_ATOM_DOUBLE:
  3855. CARLA_SAFE_ASSERT_RETURN(size == sizeof(double),);
  3856. paramValue = static_cast<float>((*(const double*)value));
  3857. break;
  3858. case CARLA_URI_MAP_ID_ATOM_FLOAT:
  3859. CARLA_SAFE_ASSERT_RETURN(size == sizeof(float),);
  3860. paramValue = (*(const float*)value);
  3861. break;
  3862. case CARLA_URI_MAP_ID_ATOM_INT:
  3863. CARLA_SAFE_ASSERT_RETURN(size == sizeof(int32_t),);
  3864. paramValue = static_cast<float>((*(const int32_t*)value));
  3865. break;
  3866. case CARLA_URI_MAP_ID_ATOM_LONG:
  3867. CARLA_SAFE_ASSERT_RETURN(size == sizeof(int64_t),);
  3868. paramValue = static_cast<float>((*(const int64_t*)value));
  3869. break;
  3870. default:
  3871. carla_stdout("CarlaPluginLV2::handleLilvSetPortValue(\"%s\", %p, %i, %i:\"%s\") - unknown type", portSymbol, value, size, type, carla_lv2_urid_unmap(this, type));
  3872. return;
  3873. }
  3874. for (uint32_t i=0; i < pData->param.count; ++i)
  3875. {
  3876. if (pData->param.data[i].rindex == rindex)
  3877. {
  3878. setParameterValue(i, paramValue, true, true, true);
  3879. break;
  3880. }
  3881. }
  3882. }
  3883. // -------------------------------------------------------------------
  3884. void* getNativeHandle() const noexcept override
  3885. {
  3886. return fHandle;
  3887. }
  3888. const void* getNativeDescriptor() const noexcept override
  3889. {
  3890. return fDescriptor;
  3891. }
  3892. uintptr_t getUiBridgeProcessId() const noexcept override
  3893. {
  3894. return fPipeServer.isPipeRunning() ? fPipeServer.getPID() : 0;
  3895. }
  3896. // -------------------------------------------------------------------
  3897. public:
  3898. bool init(const char* const name, const char* const uri, const uint options)
  3899. {
  3900. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  3901. // ---------------------------------------------------------------
  3902. // first checks
  3903. if (pData->client != nullptr)
  3904. {
  3905. pData->engine->setLastError("Plugin client is already registered");
  3906. return false;
  3907. }
  3908. if (uri == nullptr || uri[0] == '\0')
  3909. {
  3910. pData->engine->setLastError("null uri");
  3911. return false;
  3912. }
  3913. // ---------------------------------------------------------------
  3914. // Init LV2 World if needed, sets LV2_PATH for lilv
  3915. Lv2WorldClass& lv2World(Lv2WorldClass::getInstance());
  3916. if (pData->engine->getOptions().pathLV2 != nullptr && pData->engine->getOptions().pathLV2[0] != '\0')
  3917. lv2World.initIfNeeded(pData->engine->getOptions().pathLV2);
  3918. else if (const char* const LV2_PATH = std::getenv("LV2_PATH"))
  3919. lv2World.initIfNeeded(LV2_PATH);
  3920. else
  3921. lv2World.initIfNeeded(LILV_DEFAULT_LV2_PATH);
  3922. // ---------------------------------------------------------------
  3923. // get plugin from lv2_rdf (lilv)
  3924. fRdfDescriptor = lv2_rdf_new(uri, true);
  3925. if (fRdfDescriptor == nullptr)
  3926. {
  3927. pData->engine->setLastError("Failed to find the requested plugin");
  3928. return false;
  3929. }
  3930. // ---------------------------------------------------------------
  3931. // open DLL
  3932. if (! pData->libOpen(fRdfDescriptor->Binary))
  3933. {
  3934. pData->engine->setLastError(pData->libError(fRdfDescriptor->Binary));
  3935. return false;
  3936. }
  3937. // ---------------------------------------------------------------
  3938. // try to get DLL main entry via new mode
  3939. if (const LV2_Lib_Descriptor_Function libDescFn = pData->libSymbol<LV2_Lib_Descriptor_Function>("lv2_lib_descriptor"))
  3940. {
  3941. // -----------------------------------------------------------
  3942. // all ok, get lib descriptor
  3943. const LV2_Lib_Descriptor* const libDesc = libDescFn(fRdfDescriptor->Bundle, nullptr);
  3944. if (libDesc == nullptr)
  3945. {
  3946. pData->engine->setLastError("Could not find the LV2 Descriptor");
  3947. return false;
  3948. }
  3949. // -----------------------------------------------------------
  3950. // get descriptor that matches URI (new mode)
  3951. uint32_t i = 0;
  3952. while ((fDescriptor = libDesc->get_plugin(libDesc->handle, i++)))
  3953. {
  3954. if (std::strcmp(fDescriptor->URI, uri) == 0)
  3955. break;
  3956. }
  3957. }
  3958. else
  3959. {
  3960. // -----------------------------------------------------------
  3961. // get DLL main entry (old mode)
  3962. const LV2_Descriptor_Function descFn = pData->libSymbol<LV2_Descriptor_Function>("lv2_descriptor");
  3963. if (descFn == nullptr)
  3964. {
  3965. pData->engine->setLastError("Could not find the LV2 Descriptor in the plugin library");
  3966. return false;
  3967. }
  3968. // -----------------------------------------------------------
  3969. // get descriptor that matches URI (old mode)
  3970. uint32_t i = 0;
  3971. while ((fDescriptor = descFn(i++)))
  3972. {
  3973. if (std::strcmp(fDescriptor->URI, uri) == 0)
  3974. break;
  3975. }
  3976. }
  3977. if (fDescriptor == nullptr)
  3978. {
  3979. pData->engine->setLastError("Could not find the requested plugin URI in the plugin library");
  3980. return false;
  3981. }
  3982. // ---------------------------------------------------------------
  3983. // check supported port-types and features
  3984. bool canContinue = true;
  3985. // Check supported ports
  3986. for (uint32_t j=0; j < fRdfDescriptor->PortCount; ++j)
  3987. {
  3988. const LV2_Property portTypes(fRdfDescriptor->Ports[j].Types);
  3989. if (! is_lv2_port_supported(portTypes))
  3990. {
  3991. if (! LV2_IS_PORT_OPTIONAL(fRdfDescriptor->Ports[j].Properties))
  3992. {
  3993. pData->engine->setLastError("Plugin requires a port type that is not currently supported");
  3994. canContinue = false;
  3995. break;
  3996. }
  3997. }
  3998. }
  3999. // Check supported features
  4000. for (uint32_t j=0; j < fRdfDescriptor->FeatureCount && canContinue; ++j)
  4001. {
  4002. const LV2_RDF_Feature& feature(fRdfDescriptor->Features[j]);
  4003. if (std::strcmp(feature.URI, LV2_DATA_ACCESS_URI) == 0 || std::strcmp(feature.URI, LV2_INSTANCE_ACCESS_URI) == 0)
  4004. {
  4005. carla_stderr("Plugin DSP wants UI feature '%s', ignoring this", feature.URI);
  4006. }
  4007. else if (std::strcmp(feature.URI, LV2_BUF_SIZE__fixedBlockLength) == 0)
  4008. {
  4009. fNeedsFixedBuffers = true;
  4010. }
  4011. else if (std::strcmp(feature.URI, LV2_PORT_PROPS__supportsStrictBounds) == 0)
  4012. {
  4013. fStrictBounds = feature.Required ? 1 : 0;
  4014. }
  4015. else if (feature.Required && ! is_lv2_feature_supported(feature.URI))
  4016. {
  4017. CarlaString msg("Plugin wants a feature that is not supported:\n");
  4018. msg += feature.URI;
  4019. canContinue = false;
  4020. pData->engine->setLastError(msg);
  4021. break;
  4022. }
  4023. }
  4024. if (! canContinue)
  4025. {
  4026. // error already set
  4027. return false;
  4028. }
  4029. if (fNeedsFixedBuffers && ! pData->engine->usesConstantBufferSize())
  4030. {
  4031. pData->engine->setLastError("Cannot use this plugin under the current engine.\n"
  4032. "The plugin requires a fixed block size which is not possible right now.");
  4033. return false;
  4034. }
  4035. // ---------------------------------------------------------------
  4036. // get info
  4037. if (name != nullptr && name[0] != '\0')
  4038. pData->name = pData->engine->getUniquePluginName(name);
  4039. else
  4040. pData->name = pData->engine->getUniquePluginName(fRdfDescriptor->Name);
  4041. // ---------------------------------------------------------------
  4042. // register client
  4043. pData->client = pData->engine->addClient(this);
  4044. if (pData->client == nullptr || ! pData->client->isOk())
  4045. {
  4046. pData->engine->setLastError("Failed to register plugin client");
  4047. return false;
  4048. }
  4049. // ---------------------------------------------------------------
  4050. // initialize options
  4051. const int bufferSize = static_cast<int>(pData->engine->getBufferSize());
  4052. fLv2Options.minBufferSize = fNeedsFixedBuffers ? bufferSize : 1;
  4053. fLv2Options.maxBufferSize = bufferSize;
  4054. fLv2Options.nominalBufferSize = bufferSize;
  4055. fLv2Options.sampleRate = pData->engine->getSampleRate();
  4056. fLv2Options.frontendWinId = static_cast<int64_t>(pData->engine->getOptions().frontendWinId);
  4057. uint32_t eventBufferSize = MAX_DEFAULT_BUFFER_SIZE;
  4058. for (uint32_t j=0; j < fRdfDescriptor->PortCount; ++j)
  4059. {
  4060. const LV2_Property portTypes(fRdfDescriptor->Ports[j].Types);
  4061. if (LV2_IS_PORT_ATOM_SEQUENCE(portTypes) || LV2_IS_PORT_EVENT(portTypes) || LV2_IS_PORT_MIDI_LL(portTypes))
  4062. {
  4063. if (fRdfDescriptor->Ports[j].MinimumSize > eventBufferSize)
  4064. eventBufferSize = fRdfDescriptor->Ports[j].MinimumSize;
  4065. }
  4066. }
  4067. fLv2Options.sequenceSize = static_cast<int>(eventBufferSize);
  4068. // ---------------------------------------------------------------
  4069. // initialize features (part 1)
  4070. LV2_Event_Feature* const eventFt = new LV2_Event_Feature;
  4071. eventFt->callback_data = this;
  4072. eventFt->lv2_event_ref = carla_lv2_event_ref;
  4073. eventFt->lv2_event_unref = carla_lv2_event_unref;
  4074. LV2_Log_Log* const logFt = new LV2_Log_Log;
  4075. logFt->handle = this;
  4076. logFt->printf = carla_lv2_log_printf;
  4077. logFt->vprintf = carla_lv2_log_vprintf;
  4078. LV2_State_Make_Path* const stateMakePathFt = new LV2_State_Make_Path;
  4079. stateMakePathFt->handle = this;
  4080. stateMakePathFt->path = carla_lv2_state_make_path;
  4081. LV2_State_Map_Path* const stateMapPathFt = new LV2_State_Map_Path;
  4082. stateMapPathFt->handle = this;
  4083. stateMapPathFt->abstract_path = carla_lv2_state_map_abstract_path;
  4084. stateMapPathFt->absolute_path = carla_lv2_state_map_absolute_path;
  4085. LV2_Programs_Host* const programsFt = new LV2_Programs_Host;
  4086. programsFt->handle = this;
  4087. programsFt->program_changed = carla_lv2_program_changed;
  4088. LV2_Resize_Port_Resize* const rsPortFt = new LV2_Resize_Port_Resize;
  4089. rsPortFt->data = this;
  4090. rsPortFt->resize = carla_lv2_resize_port;
  4091. LV2_RtMemPool_Pool* const rtMemPoolFt = new LV2_RtMemPool_Pool;
  4092. lv2_rtmempool_init(rtMemPoolFt);
  4093. LV2_RtMemPool_Pool_Deprecated* const rtMemPoolOldFt = new LV2_RtMemPool_Pool_Deprecated;
  4094. lv2_rtmempool_init_deprecated(rtMemPoolOldFt);
  4095. LV2_URI_Map_Feature* const uriMapFt = new LV2_URI_Map_Feature;
  4096. uriMapFt->callback_data = this;
  4097. uriMapFt->uri_to_id = carla_lv2_uri_to_id;
  4098. LV2_URID_Map* const uridMapFt = new LV2_URID_Map;
  4099. uridMapFt->handle = this;
  4100. uridMapFt->map = carla_lv2_urid_map;
  4101. LV2_URID_Unmap* const uridUnmapFt = new LV2_URID_Unmap;
  4102. uridUnmapFt->handle = this;
  4103. uridUnmapFt->unmap = carla_lv2_urid_unmap;
  4104. LV2_Worker_Schedule* const workerFt = new LV2_Worker_Schedule;
  4105. workerFt->handle = this;
  4106. workerFt->schedule_work = carla_lv2_worker_schedule;
  4107. LV2_Inline_Display* const inlineDisplay = new LV2_Inline_Display;
  4108. inlineDisplay->handle = this;
  4109. inlineDisplay->queue_draw = carla_lv2_inline_display_queue_draw;
  4110. // ---------------------------------------------------------------
  4111. // initialize features (part 2)
  4112. for (uint32_t j=0; j < kFeatureCountPlugin; ++j)
  4113. fFeatures[j] = new LV2_Feature;
  4114. fFeatures[kFeatureIdBufSizeBounded]->URI = LV2_BUF_SIZE__boundedBlockLength;
  4115. fFeatures[kFeatureIdBufSizeBounded]->data = nullptr;
  4116. fFeatures[kFeatureIdBufSizeFixed]->URI = fNeedsFixedBuffers
  4117. ? LV2_BUF_SIZE__fixedBlockLength
  4118. : LV2_BUF_SIZE__boundedBlockLength;
  4119. fFeatures[kFeatureIdBufSizeFixed]->data = nullptr;
  4120. fFeatures[kFeatureIdBufSizePowerOf2]->URI = LV2_BUF_SIZE__powerOf2BlockLength;
  4121. fFeatures[kFeatureIdBufSizePowerOf2]->data = nullptr;
  4122. fFeatures[kFeatureIdEvent]->URI = LV2_EVENT_URI;
  4123. fFeatures[kFeatureIdEvent]->data = eventFt;
  4124. fFeatures[kFeatureIdHardRtCapable]->URI = LV2_CORE__hardRTCapable;
  4125. fFeatures[kFeatureIdHardRtCapable]->data = nullptr;
  4126. fFeatures[kFeatureIdInPlaceBroken]->URI = LV2_CORE__inPlaceBroken;
  4127. fFeatures[kFeatureIdInPlaceBroken]->data = nullptr;
  4128. fFeatures[kFeatureIdIsLive]->URI = LV2_CORE__isLive;
  4129. fFeatures[kFeatureIdIsLive]->data = nullptr;
  4130. fFeatures[kFeatureIdLogs]->URI = LV2_LOG__log;
  4131. fFeatures[kFeatureIdLogs]->data = logFt;
  4132. fFeatures[kFeatureIdOptions]->URI = LV2_OPTIONS__options;
  4133. fFeatures[kFeatureIdOptions]->data = fLv2Options.opts;
  4134. fFeatures[kFeatureIdPrograms]->URI = LV2_PROGRAMS__Host;
  4135. fFeatures[kFeatureIdPrograms]->data = programsFt;
  4136. fFeatures[kFeatureIdResizePort]->URI = LV2_RESIZE_PORT__resize;
  4137. fFeatures[kFeatureIdResizePort]->data = rsPortFt;
  4138. fFeatures[kFeatureIdRtMemPool]->URI = LV2_RTSAFE_MEMORY_POOL__Pool;
  4139. fFeatures[kFeatureIdRtMemPool]->data = rtMemPoolFt;
  4140. fFeatures[kFeatureIdRtMemPoolOld]->URI = LV2_RTSAFE_MEMORY_POOL_DEPRECATED_URI;
  4141. fFeatures[kFeatureIdRtMemPoolOld]->data = rtMemPoolOldFt;
  4142. fFeatures[kFeatureIdStateMakePath]->URI = LV2_STATE__makePath;
  4143. fFeatures[kFeatureIdStateMakePath]->data = stateMakePathFt;
  4144. fFeatures[kFeatureIdStateMapPath]->URI = LV2_STATE__mapPath;
  4145. fFeatures[kFeatureIdStateMapPath]->data = stateMapPathFt;
  4146. fFeatures[kFeatureIdStrictBounds]->URI = LV2_PORT_PROPS__supportsStrictBounds;
  4147. fFeatures[kFeatureIdStrictBounds]->data = nullptr;
  4148. fFeatures[kFeatureIdUriMap]->URI = LV2_URI_MAP_URI;
  4149. fFeatures[kFeatureIdUriMap]->data = uriMapFt;
  4150. fFeatures[kFeatureIdUridMap]->URI = LV2_URID__map;
  4151. fFeatures[kFeatureIdUridMap]->data = uridMapFt;
  4152. fFeatures[kFeatureIdUridUnmap]->URI = LV2_URID__unmap;
  4153. fFeatures[kFeatureIdUridUnmap]->data = uridUnmapFt;
  4154. fFeatures[kFeatureIdWorker]->URI = LV2_WORKER__schedule;
  4155. fFeatures[kFeatureIdWorker]->data = workerFt;
  4156. fFeatures[kFeatureIdInlineDisplay]->URI = LV2_INLINEDISPLAY__queue_draw;
  4157. fFeatures[kFeatureIdInlineDisplay]->data = inlineDisplay;
  4158. // ---------------------------------------------------------------
  4159. // initialize plugin
  4160. try {
  4161. fHandle = fDescriptor->instantiate(fDescriptor, pData->engine->getSampleRate(), fRdfDescriptor->Bundle, fFeatures);
  4162. } catch(...) {}
  4163. if (fHandle == nullptr)
  4164. {
  4165. pData->engine->setLastError("Plugin failed to initialize");
  4166. return false;
  4167. }
  4168. if (std::strcmp(uri, "http://hyperglitch.com/dev/VocProc") == 0)
  4169. fCanInit2 = false;
  4170. recheckExtensions();
  4171. // ---------------------------------------------------------------
  4172. // set default options
  4173. pData->options = 0x0;
  4174. if (fLatencyIndex >= 0 || getMidiOutCount() != 0 || fNeedsFixedBuffers)
  4175. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  4176. else if (options & PLUGIN_OPTION_FIXED_BUFFERS)
  4177. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  4178. if (fCanInit2)
  4179. {
  4180. if (pData->engine->getOptions().forceStereo)
  4181. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  4182. else if (options & PLUGIN_OPTION_FORCE_STEREO)
  4183. pData->options |= PLUGIN_OPTION_FORCE_STEREO;
  4184. }
  4185. if (getMidiInCount() != 0)
  4186. {
  4187. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  4188. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  4189. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  4190. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  4191. if (options & PLUGIN_OPTION_SEND_CONTROL_CHANGES)
  4192. pData->options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  4193. if (options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES)
  4194. pData->options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  4195. }
  4196. if (fExt.programs != nullptr && (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) == 0)
  4197. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  4198. // ---------------------------------------------------------------
  4199. // gui stuff
  4200. if (fRdfDescriptor->UICount != 0)
  4201. initUi();
  4202. return true;
  4203. }
  4204. // -------------------------------------------------------------------
  4205. void initUi()
  4206. {
  4207. // ---------------------------------------------------------------
  4208. // find the most appropriate ui
  4209. int eQt4, eQt5, eGtk2, eGtk3, eCocoa, eWindows, eX11, eExt, eMod, iCocoa, iWindows, iX11, iExt, iFinal;
  4210. eQt4 = eQt5 = eGtk2 = eGtk3 = eCocoa = eWindows = eX11 = eExt = eMod = iCocoa = iWindows = iX11 = iExt = iFinal = -1;
  4211. #if defined(BUILD_BRIDGE) || defined(LV2_UIS_ONLY_BRIDGES)
  4212. const bool preferUiBridges(true);
  4213. #else
  4214. const bool preferUiBridges(pData->engine->getOptions().preferUiBridges && (pData->hints & PLUGIN_IS_BRIDGE) == 0);
  4215. #endif
  4216. bool hasShowInterface = false;
  4217. for (uint32_t i=0; i < fRdfDescriptor->UICount; ++i)
  4218. {
  4219. CARLA_SAFE_ASSERT_CONTINUE(fRdfDescriptor->UIs[i].URI != nullptr);
  4220. const int ii(static_cast<int>(i));
  4221. switch (fRdfDescriptor->UIs[i].Type)
  4222. {
  4223. case LV2_UI_QT4:
  4224. if (isUiBridgeable(i))
  4225. eQt4 = ii;
  4226. break;
  4227. case LV2_UI_QT5:
  4228. if (isUiBridgeable(i))
  4229. eQt5 = ii;
  4230. break;
  4231. case LV2_UI_GTK2:
  4232. if (isUiBridgeable(i))
  4233. eGtk2 = ii;
  4234. break;
  4235. case LV2_UI_GTK3:
  4236. if (isUiBridgeable(i))
  4237. eGtk3 = ii;
  4238. break;
  4239. case LV2_UI_COCOA:
  4240. if (isUiBridgeable(i) && preferUiBridges)
  4241. eCocoa = ii;
  4242. iCocoa = ii;
  4243. break;
  4244. case LV2_UI_WINDOWS:
  4245. if (isUiBridgeable(i) && preferUiBridges)
  4246. eWindows = ii;
  4247. iWindows = ii;
  4248. break;
  4249. case LV2_UI_X11:
  4250. if (isUiBridgeable(i) && preferUiBridges)
  4251. eX11 = ii;
  4252. iX11 = ii;
  4253. break;
  4254. case LV2_UI_EXTERNAL:
  4255. case LV2_UI_OLD_EXTERNAL:
  4256. if (isUiBridgeable(i))
  4257. eExt = ii;
  4258. iExt = ii;
  4259. break;
  4260. case LV2_UI_MOD:
  4261. eMod = ii;
  4262. break;
  4263. default:
  4264. break;
  4265. }
  4266. }
  4267. if (eQt4 >= 0)
  4268. iFinal = eQt4;
  4269. else if (eQt5 >= 0)
  4270. iFinal = eQt5;
  4271. else if (eGtk2 >= 0)
  4272. iFinal = eGtk2;
  4273. else if (eGtk3 >= 0)
  4274. iFinal = eGtk3;
  4275. #ifdef CARLA_OS_MAC
  4276. else if (eCocoa >= 0)
  4277. iFinal = eCocoa;
  4278. #endif
  4279. #ifdef CARLA_OS_WIN
  4280. else if (eWindows >= 0)
  4281. iFinal = eWindows;
  4282. #endif
  4283. #ifdef HAVE_X11
  4284. else if (eX11 >= 0)
  4285. iFinal = eX11;
  4286. #endif
  4287. //else if (eExt >= 0) // TODO
  4288. // iFinal = eExt;
  4289. #ifndef LV2_UIS_ONLY_BRIDGES
  4290. # ifdef CARLA_OS_MAC
  4291. else if (iCocoa >= 0)
  4292. iFinal = iCocoa;
  4293. # endif
  4294. # ifdef CARLA_OS_WIN
  4295. else if (iWindows >= 0)
  4296. iFinal = iWindows;
  4297. # endif
  4298. # ifdef HAVE_X11
  4299. else if (iX11 >= 0)
  4300. iFinal = iX11;
  4301. # endif
  4302. #endif
  4303. else if (iExt >= 0)
  4304. iFinal = iExt;
  4305. #ifndef BUILD_BRIDGE
  4306. if (iFinal < 0)
  4307. #endif
  4308. {
  4309. // no suitable UI found, see if there's one which supports ui:showInterface
  4310. for (uint32_t i=0; i < fRdfDescriptor->UICount && ! hasShowInterface; ++i)
  4311. {
  4312. LV2_RDF_UI* const ui(&fRdfDescriptor->UIs[i]);
  4313. for (uint32_t j=0; j < ui->ExtensionCount; ++j)
  4314. {
  4315. CARLA_SAFE_ASSERT_CONTINUE(ui->Extensions[j] != nullptr);
  4316. if (std::strcmp(ui->Extensions[j], LV2_UI__showInterface) != 0)
  4317. continue;
  4318. iFinal = static_cast<int>(i);
  4319. hasShowInterface = true;
  4320. break;
  4321. }
  4322. }
  4323. if (iFinal < 0)
  4324. {
  4325. if (eMod < 0)
  4326. {
  4327. carla_stderr("Failed to find an appropriate LV2 UI for this plugin");
  4328. return;
  4329. }
  4330. // use MODGUI as last resort
  4331. iFinal = eMod;
  4332. }
  4333. }
  4334. fUI.rdfDescriptor = &fRdfDescriptor->UIs[iFinal];
  4335. // ---------------------------------------------------------------
  4336. // check supported ui features
  4337. bool canContinue = true;
  4338. bool canDelete = true;
  4339. for (uint32_t i=0; i < fUI.rdfDescriptor->FeatureCount; ++i)
  4340. {
  4341. const char* const uri(fUI.rdfDescriptor->Features[i].URI);
  4342. CARLA_SAFE_ASSERT_CONTINUE(uri != nullptr && uri[0] != '\0');
  4343. if (! is_lv2_ui_feature_supported(uri))
  4344. {
  4345. carla_stderr("Plugin UI requires a feature that is not supported:\n%s", uri);
  4346. if (fUI.rdfDescriptor->Features[i].Required)
  4347. {
  4348. canContinue = false;
  4349. break;
  4350. }
  4351. }
  4352. if (std::strcmp(uri, LV2_UI__makeResident) == 0 || std::strcmp(uri, LV2_UI__makeSONameResident) == 0)
  4353. canDelete = false;
  4354. }
  4355. if (! canContinue)
  4356. {
  4357. fUI.rdfDescriptor = nullptr;
  4358. return;
  4359. }
  4360. // ---------------------------------------------------------------
  4361. // initialize ui according to type
  4362. const LV2_Property uiType(fUI.rdfDescriptor->Type);
  4363. if (
  4364. (iFinal == eQt4 || iFinal == eQt5 || iFinal == eGtk2 || iFinal == eGtk3 ||
  4365. iFinal == eCocoa || iFinal == eWindows || iFinal == eX11 || iFinal == eExt || iFinal == eMod)
  4366. #ifdef BUILD_BRIDGE
  4367. && preferUiBridges && ! hasShowInterface
  4368. #endif
  4369. )
  4370. {
  4371. // -----------------------------------------------------------
  4372. // initialize ui-bridge
  4373. if (const char* const bridgeBinary = getUiBridgeBinary(uiType))
  4374. {
  4375. carla_stdout("Will use UI-Bridge, binary: \"%s\"", bridgeBinary);
  4376. CarlaString guiTitle(pData->name);
  4377. guiTitle += " (GUI)";
  4378. fLv2Options.windowTitle = guiTitle.dup();
  4379. fUI.type = UI::TYPE_BRIDGE;
  4380. fPipeServer.setData(bridgeBinary, fRdfDescriptor->URI, fUI.rdfDescriptor->URI);
  4381. delete[] bridgeBinary;
  4382. return;
  4383. }
  4384. if (iFinal == eQt4 || iFinal == eQt5 || iFinal == eGtk2 || iFinal == eGtk3)
  4385. {
  4386. carla_stderr2("Failed to find UI bridge binary, cannot use UI");
  4387. fUI.rdfDescriptor = nullptr;
  4388. return;
  4389. }
  4390. }
  4391. #ifdef LV2_UIS_ONLY_BRIDGES
  4392. carla_stderr2("Failed to get an UI working, canBridge:%s", bool2str(isUiBridgeable(static_cast<uint32_t>(iFinal))));
  4393. fUI.rdfDescriptor = nullptr;
  4394. return;
  4395. #endif
  4396. // ---------------------------------------------------------------
  4397. // open UI DLL
  4398. if (! pData->uiLibOpen(fUI.rdfDescriptor->Binary, canDelete))
  4399. {
  4400. carla_stderr2("Could not load UI library, error was:\n%s", pData->libError(fUI.rdfDescriptor->Binary));
  4401. fUI.rdfDescriptor = nullptr;
  4402. return;
  4403. }
  4404. // ---------------------------------------------------------------
  4405. // get UI DLL main entry
  4406. LV2UI_DescriptorFunction uiDescFn = pData->uiLibSymbol<LV2UI_DescriptorFunction>("lv2ui_descriptor");
  4407. if (uiDescFn == nullptr)
  4408. {
  4409. carla_stderr2("Could not find the LV2UI Descriptor in the UI library");
  4410. pData->uiLibClose();
  4411. fUI.rdfDescriptor = nullptr;
  4412. return;
  4413. }
  4414. // ---------------------------------------------------------------
  4415. // get UI descriptor that matches UI URI
  4416. uint32_t i = 0;
  4417. while ((fUI.descriptor = uiDescFn(i++)))
  4418. {
  4419. if (std::strcmp(fUI.descriptor->URI, fUI.rdfDescriptor->URI) == 0)
  4420. break;
  4421. }
  4422. if (fUI.descriptor == nullptr)
  4423. {
  4424. carla_stderr2("Could not find the requested GUI in the plugin UI library");
  4425. pData->uiLibClose();
  4426. fUI.rdfDescriptor = nullptr;
  4427. return;
  4428. }
  4429. // ---------------------------------------------------------------
  4430. // check if ui is usable
  4431. switch (uiType)
  4432. {
  4433. case LV2_UI_QT4:
  4434. carla_stdout("Will use LV2 Qt4 UI, NOT!");
  4435. fUI.type = UI::TYPE_EMBED;
  4436. break;
  4437. case LV2_UI_QT5:
  4438. carla_stdout("Will use LV2 Qt5 UI, NOT!");
  4439. fUI.type = UI::TYPE_EMBED;
  4440. break;
  4441. case LV2_UI_GTK2:
  4442. carla_stdout("Will use LV2 Gtk2 UI, NOT!");
  4443. fUI.type = UI::TYPE_EMBED;
  4444. break;
  4445. case LV2_UI_GTK3:
  4446. carla_stdout("Will use LV2 Gtk3 UI, NOT!");
  4447. fUI.type = UI::TYPE_EMBED;
  4448. break;
  4449. #ifdef CARLA_OS_MAC
  4450. case LV2_UI_COCOA:
  4451. carla_stdout("Will use LV2 Cocoa UI");
  4452. fUI.type = UI::TYPE_EMBED;
  4453. break;
  4454. #endif
  4455. #ifdef CARLA_OS_WIN
  4456. case LV2_UI_WINDOWS:
  4457. carla_stdout("Will use LV2 Windows UI");
  4458. fUI.type = UI::TYPE_EMBED;
  4459. break;
  4460. #endif
  4461. case LV2_UI_X11:
  4462. #ifdef HAVE_X11
  4463. carla_stdout("Will use LV2 X11 UI");
  4464. #else
  4465. carla_stdout("Will use LV2 X11 UI, NOT!");
  4466. #endif
  4467. fUI.type = UI::TYPE_EMBED;
  4468. break;
  4469. case LV2_UI_EXTERNAL:
  4470. case LV2_UI_OLD_EXTERNAL:
  4471. carla_stdout("Will use LV2 External UI");
  4472. fUI.type = UI::TYPE_EXTERNAL;
  4473. break;
  4474. }
  4475. if (fUI.type == UI::TYPE_NULL)
  4476. {
  4477. pData->uiLibClose();
  4478. fUI.descriptor = nullptr;
  4479. fUI.rdfDescriptor = nullptr;
  4480. return;
  4481. }
  4482. // ---------------------------------------------------------------
  4483. // initialize ui data
  4484. CarlaString guiTitle(pData->name);
  4485. guiTitle += " (GUI)";
  4486. fLv2Options.windowTitle = guiTitle.dup();
  4487. fLv2Options.opts[CarlaPluginLV2Options::WindowTitle].size = (uint32_t)std::strlen(fLv2Options.windowTitle);
  4488. fLv2Options.opts[CarlaPluginLV2Options::WindowTitle].value = fLv2Options.windowTitle;
  4489. // ---------------------------------------------------------------
  4490. // initialize ui features (part 1)
  4491. LV2_Extension_Data_Feature* const uiDataFt = new LV2_Extension_Data_Feature;
  4492. uiDataFt->data_access = fDescriptor->extension_data;
  4493. LV2UI_Port_Map* const uiPortMapFt = new LV2UI_Port_Map;
  4494. uiPortMapFt->handle = this;
  4495. uiPortMapFt->port_index = carla_lv2_ui_port_map;
  4496. LV2UI_Resize* const uiResizeFt = new LV2UI_Resize;
  4497. uiResizeFt->handle = this;
  4498. uiResizeFt->ui_resize = carla_lv2_ui_resize;
  4499. LV2_External_UI_Host* const uiExternalHostFt = new LV2_External_UI_Host;
  4500. uiExternalHostFt->ui_closed = carla_lv2_external_ui_closed;
  4501. uiExternalHostFt->plugin_human_id = fLv2Options.windowTitle;
  4502. // ---------------------------------------------------------------
  4503. // initialize ui features (part 2)
  4504. for (uint32_t j=kFeatureCountPlugin; j < kFeatureCountAll; ++j)
  4505. fFeatures[j] = new LV2_Feature;
  4506. fFeatures[kFeatureIdUiDataAccess]->URI = LV2_DATA_ACCESS_URI;
  4507. fFeatures[kFeatureIdUiDataAccess]->data = uiDataFt;
  4508. fFeatures[kFeatureIdUiInstanceAccess]->URI = LV2_INSTANCE_ACCESS_URI;
  4509. fFeatures[kFeatureIdUiInstanceAccess]->data = fHandle;
  4510. fFeatures[kFeatureIdUiIdleInterface]->URI = LV2_UI__idleInterface;
  4511. fFeatures[kFeatureIdUiIdleInterface]->data = nullptr;
  4512. fFeatures[kFeatureIdUiFixedSize]->URI = LV2_UI__fixedSize;
  4513. fFeatures[kFeatureIdUiFixedSize]->data = nullptr;
  4514. fFeatures[kFeatureIdUiMakeResident]->URI = LV2_UI__makeResident;
  4515. fFeatures[kFeatureIdUiMakeResident]->data = nullptr;
  4516. fFeatures[kFeatureIdUiMakeResident2]->URI = LV2_UI__makeSONameResident;
  4517. fFeatures[kFeatureIdUiMakeResident2]->data = nullptr;
  4518. fFeatures[kFeatureIdUiNoUserResize]->URI = LV2_UI__noUserResize;
  4519. fFeatures[kFeatureIdUiNoUserResize]->data = nullptr;
  4520. fFeatures[kFeatureIdUiParent]->URI = LV2_UI__parent;
  4521. fFeatures[kFeatureIdUiParent]->data = nullptr;
  4522. fFeatures[kFeatureIdUiPortMap]->URI = LV2_UI__portMap;
  4523. fFeatures[kFeatureIdUiPortMap]->data = uiPortMapFt;
  4524. fFeatures[kFeatureIdUiPortSubscribe]->URI = LV2_UI__portSubscribe;
  4525. fFeatures[kFeatureIdUiPortSubscribe]->data = nullptr;
  4526. fFeatures[kFeatureIdUiResize]->URI = LV2_UI__resize;
  4527. fFeatures[kFeatureIdUiResize]->data = uiResizeFt;
  4528. fFeatures[kFeatureIdUiTouch]->URI = LV2_UI__touch;
  4529. fFeatures[kFeatureIdUiTouch]->data = nullptr;
  4530. fFeatures[kFeatureIdExternalUi]->URI = LV2_EXTERNAL_UI__Host;
  4531. fFeatures[kFeatureIdExternalUi]->data = uiExternalHostFt;
  4532. fFeatures[kFeatureIdExternalUiOld]->URI = LV2_EXTERNAL_UI_DEPRECATED_URI;
  4533. fFeatures[kFeatureIdExternalUiOld]->data = uiExternalHostFt;
  4534. // ---------------------------------------------------------------
  4535. // initialize ui extensions
  4536. if (fUI.descriptor->extension_data == nullptr)
  4537. return;
  4538. fExt.uiidle = (const LV2UI_Idle_Interface*)fUI.descriptor->extension_data(LV2_UI__idleInterface);
  4539. fExt.uishow = (const LV2UI_Show_Interface*)fUI.descriptor->extension_data(LV2_UI__showInterface);
  4540. fExt.uiresize = (const LV2UI_Resize*)fUI.descriptor->extension_data(LV2_UI__resize);
  4541. fExt.uiprograms = (const LV2_Programs_UI_Interface*)fUI.descriptor->extension_data(LV2_PROGRAMS__UIInterface);
  4542. // check if invalid
  4543. if (fExt.uiidle != nullptr && fExt.uiidle->idle == nullptr)
  4544. fExt.uiidle = nullptr;
  4545. if (fExt.uishow != nullptr && (fExt.uishow->show == nullptr || fExt.uishow->hide == nullptr))
  4546. fExt.uishow = nullptr;
  4547. if (fExt.uiresize != nullptr && fExt.uiresize->ui_resize == nullptr)
  4548. fExt.uiresize = nullptr;
  4549. if (fExt.uiprograms != nullptr && fExt.uiprograms->select_program == nullptr)
  4550. fExt.uiprograms = nullptr;
  4551. // don't use uiidle if external
  4552. if (fUI.type == UI::TYPE_EXTERNAL)
  4553. fExt.uiidle = nullptr;
  4554. }
  4555. // -------------------------------------------------------------------
  4556. void handleTransferAtom(const uint32_t portIndex, const LV2_Atom* const atom)
  4557. {
  4558. CARLA_SAFE_ASSERT_RETURN(atom != nullptr,);
  4559. carla_debug("CarlaPluginLV2::handleTransferAtom(%i, %p)", portIndex, atom);
  4560. fAtomBufferIn.put(atom, portIndex);
  4561. }
  4562. void handleUridMap(const LV2_URID urid, const char* const uri)
  4563. {
  4564. CARLA_SAFE_ASSERT_RETURN(urid != CARLA_URI_MAP_ID_NULL,);
  4565. CARLA_SAFE_ASSERT_RETURN(uri != nullptr && uri[0] != '\0',);
  4566. carla_debug("CarlaPluginLV2::handleUridMap(%i v " P_SIZE ", \"%s\")", urid, fCustomURIDs.size()-1, uri);
  4567. const std::size_t uriCount(fCustomURIDs.size());
  4568. if (urid < uriCount)
  4569. {
  4570. const char* const ourURI(carla_lv2_urid_unmap(this, urid));
  4571. CARLA_SAFE_ASSERT_RETURN(ourURI != nullptr,);
  4572. if (std::strcmp(ourURI, uri) != 0)
  4573. {
  4574. carla_stderr2("PLUGIN :: wrong URI '%s' vs '%s'", ourURI, uri);
  4575. }
  4576. }
  4577. else
  4578. {
  4579. CARLA_SAFE_ASSERT_RETURN(urid == uriCount,);
  4580. fCustomURIDs.push_back(uri);
  4581. }
  4582. }
  4583. // -------------------------------------------------------------------
  4584. private:
  4585. LV2_Handle fHandle;
  4586. LV2_Handle fHandle2;
  4587. LV2_Feature* fFeatures[kFeatureCountAll+1];
  4588. const LV2_Descriptor* fDescriptor;
  4589. const LV2_RDF_Descriptor* fRdfDescriptor;
  4590. float** fAudioInBuffers;
  4591. float** fAudioOutBuffers;
  4592. float** fCvInBuffers;
  4593. float** fCvOutBuffers;
  4594. float* fParamBuffers;
  4595. bool fCanInit2; // some plugins don't like 2 instances
  4596. bool fNeedsFixedBuffers;
  4597. bool fNeedsUiClose;
  4598. int32_t fLatencyIndex; // -1 if invalid
  4599. int fStrictBounds; // -1 unsupported, 0 optional, 1 required
  4600. Lv2AtomRingBuffer fAtomBufferIn;
  4601. Lv2AtomRingBuffer fAtomBufferOut;
  4602. LV2_Atom_Forge fAtomForge;
  4603. uint8_t* fTmpAtomBuffer;
  4604. CarlaPluginLV2EventData fEventsIn;
  4605. CarlaPluginLV2EventData fEventsOut;
  4606. CarlaPluginLV2Options fLv2Options;
  4607. CarlaPipeServerLV2 fPipeServer;
  4608. std::vector<std::string> fCustomURIDs;
  4609. bool fFirstActive; // first process() call after activate()
  4610. void* fLastStateChunk;
  4611. EngineTimeInfo fLastTimeInfo;
  4612. struct Extensions {
  4613. const LV2_Options_Interface* options;
  4614. const LV2_State_Interface* state;
  4615. const LV2_Worker_Interface* worker;
  4616. const LV2_Inline_Display_Interface* inlineDisplay;
  4617. const LV2_Programs_Interface* programs;
  4618. const LV2UI_Idle_Interface* uiidle;
  4619. const LV2UI_Show_Interface* uishow;
  4620. const LV2UI_Resize* uiresize;
  4621. const LV2_Programs_UI_Interface* uiprograms;
  4622. Extensions()
  4623. : options(nullptr),
  4624. state(nullptr),
  4625. worker(nullptr),
  4626. inlineDisplay(nullptr),
  4627. programs(nullptr),
  4628. uiidle(nullptr),
  4629. uishow(nullptr),
  4630. uiresize(nullptr),
  4631. uiprograms(nullptr) {}
  4632. CARLA_DECLARE_NON_COPY_STRUCT(Extensions);
  4633. } fExt;
  4634. struct UI {
  4635. enum Type {
  4636. TYPE_NULL = 0,
  4637. TYPE_BRIDGE,
  4638. TYPE_EMBED,
  4639. TYPE_EXTERNAL
  4640. };
  4641. Type type;
  4642. LV2UI_Handle handle;
  4643. LV2UI_Widget widget;
  4644. const LV2UI_Descriptor* descriptor;
  4645. const LV2_RDF_UI* rdfDescriptor;
  4646. CarlaPluginUI* window;
  4647. UI()
  4648. : type(TYPE_NULL),
  4649. handle(nullptr),
  4650. widget(nullptr),
  4651. descriptor(nullptr),
  4652. rdfDescriptor(nullptr),
  4653. window(nullptr) {}
  4654. ~UI()
  4655. {
  4656. CARLA_ASSERT(handle == nullptr);
  4657. CARLA_ASSERT(widget == nullptr);
  4658. CARLA_ASSERT(descriptor == nullptr);
  4659. CARLA_ASSERT(rdfDescriptor == nullptr);
  4660. CARLA_ASSERT(window == nullptr);
  4661. }
  4662. CARLA_DECLARE_NON_COPY_STRUCT(UI);
  4663. } fUI;
  4664. // -------------------------------------------------------------------
  4665. // Event Feature
  4666. static uint32_t carla_lv2_event_ref(LV2_Event_Callback_Data callback_data, LV2_Event* event)
  4667. {
  4668. CARLA_SAFE_ASSERT_RETURN(callback_data != nullptr, 0);
  4669. CARLA_SAFE_ASSERT_RETURN(event != nullptr, 0);
  4670. carla_debug("carla_lv2_event_ref(%p, %p)", callback_data, event);
  4671. return 0;
  4672. }
  4673. static uint32_t carla_lv2_event_unref(LV2_Event_Callback_Data callback_data, LV2_Event* event)
  4674. {
  4675. CARLA_SAFE_ASSERT_RETURN(callback_data != nullptr, 0);
  4676. CARLA_SAFE_ASSERT_RETURN(event != nullptr, 0);
  4677. carla_debug("carla_lv2_event_unref(%p, %p)", callback_data, event);
  4678. return 0;
  4679. }
  4680. // -------------------------------------------------------------------
  4681. // Logs Feature
  4682. static int carla_lv2_log_printf(LV2_Log_Handle handle, LV2_URID type, const char* fmt, ...)
  4683. {
  4684. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, 0);
  4685. CARLA_SAFE_ASSERT_RETURN(type != CARLA_URI_MAP_ID_NULL, 0);
  4686. CARLA_SAFE_ASSERT_RETURN(fmt != nullptr, 0);
  4687. #ifndef DEBUG
  4688. if (type == CARLA_URI_MAP_ID_LOG_TRACE)
  4689. return 0;
  4690. #endif
  4691. va_list args;
  4692. va_start(args, fmt);
  4693. const int ret(carla_lv2_log_vprintf(handle, type, fmt, args));
  4694. va_end(args);
  4695. return ret;
  4696. }
  4697. static int carla_lv2_log_vprintf(LV2_Log_Handle handle, LV2_URID type, const char* fmt, va_list ap)
  4698. {
  4699. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, 0);
  4700. CARLA_SAFE_ASSERT_RETURN(type != CARLA_URI_MAP_ID_NULL, 0);
  4701. CARLA_SAFE_ASSERT_RETURN(fmt != nullptr, 0);
  4702. #ifndef DEBUG
  4703. if (type == CARLA_URI_MAP_ID_LOG_TRACE)
  4704. return 0;
  4705. #endif
  4706. int ret = 0;
  4707. switch (type)
  4708. {
  4709. case CARLA_URI_MAP_ID_LOG_ERROR:
  4710. std::fprintf(stderr, "\x1b[31m");
  4711. ret = std::vfprintf(stderr, fmt, ap);
  4712. std::fprintf(stderr, "\x1b[0m");
  4713. break;
  4714. case CARLA_URI_MAP_ID_LOG_NOTE:
  4715. ret = std::vfprintf(stdout, fmt, ap);
  4716. break;
  4717. case CARLA_URI_MAP_ID_LOG_TRACE:
  4718. #ifdef DEBUG
  4719. std::fprintf(stdout, "\x1b[30;1m");
  4720. ret = std::vfprintf(stdout, fmt, ap);
  4721. std::fprintf(stdout, "\x1b[0m");
  4722. #endif
  4723. break;
  4724. case CARLA_URI_MAP_ID_LOG_WARNING:
  4725. ret = std::vfprintf(stderr, fmt, ap);
  4726. break;
  4727. default:
  4728. break;
  4729. }
  4730. return ret;
  4731. }
  4732. // -------------------------------------------------------------------
  4733. // Programs Feature
  4734. static void carla_lv2_program_changed(LV2_Programs_Handle handle, int32_t index)
  4735. {
  4736. CARLA_SAFE_ASSERT_RETURN(handle != nullptr,);
  4737. carla_debug("carla_lv2_program_changed(%p, %i)", handle, index);
  4738. ((CarlaPluginLV2*)handle)->handleProgramChanged(index);
  4739. }
  4740. // -------------------------------------------------------------------
  4741. // Resize Port Feature
  4742. static LV2_Resize_Port_Status carla_lv2_resize_port(LV2_Resize_Port_Feature_Data data, uint32_t index, size_t size)
  4743. {
  4744. CARLA_SAFE_ASSERT_RETURN(data != nullptr, LV2_RESIZE_PORT_ERR_UNKNOWN);
  4745. carla_debug("carla_lv2_program_changed(%p, %i, " P_SIZE ")", data, index, size);
  4746. return ((CarlaPluginLV2*)data)->handleResizePort(index, size);
  4747. }
  4748. // -------------------------------------------------------------------
  4749. // State Feature
  4750. static char* carla_lv2_state_make_path(LV2_State_Make_Path_Handle handle, const char* path)
  4751. {
  4752. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, nullptr);
  4753. CARLA_SAFE_ASSERT_RETURN(path != nullptr && path[0] != '\0', nullptr);
  4754. carla_debug("carla_lv2_state_make_path(%p, \"%s\")", handle, path);
  4755. File file;
  4756. if (File::isAbsolutePath(path))
  4757. file = File(path);
  4758. else
  4759. file = File::getCurrentWorkingDirectory().getChildFile(path);
  4760. file.getParentDirectory().createDirectory();
  4761. return strdup(file.getFullPathName().toRawUTF8());
  4762. }
  4763. static char* carla_lv2_state_map_abstract_path(LV2_State_Map_Path_Handle handle, const char* absolute_path)
  4764. {
  4765. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, strdup(""));
  4766. CARLA_SAFE_ASSERT_RETURN(absolute_path != nullptr && absolute_path[0] != '\0', strdup(""));
  4767. carla_debug("carla_lv2_state_map_abstract_path(%p, \"%s\")", handle, absolute_path);
  4768. // may already be an abstract path
  4769. if (! File::isAbsolutePath(absolute_path))
  4770. return strdup(absolute_path);
  4771. return strdup(File(absolute_path).getRelativePathFrom(File::getCurrentWorkingDirectory()).toRawUTF8());
  4772. }
  4773. static char* carla_lv2_state_map_absolute_path(LV2_State_Map_Path_Handle handle, const char* abstract_path)
  4774. {
  4775. const char* const cwd(File::getCurrentWorkingDirectory().getFullPathName().toRawUTF8());
  4776. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, strdup(cwd));
  4777. CARLA_SAFE_ASSERT_RETURN(abstract_path != nullptr && abstract_path[0] != '\0', strdup(cwd));
  4778. carla_debug("carla_lv2_state_map_absolute_path(%p, \"%s\")", handle, abstract_path);
  4779. // may already be an absolute path
  4780. if (File::isAbsolutePath(abstract_path))
  4781. return strdup(abstract_path);
  4782. return strdup(File::getCurrentWorkingDirectory().getChildFile(abstract_path).getFullPathName().toRawUTF8());
  4783. }
  4784. 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)
  4785. {
  4786. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, LV2_STATE_ERR_UNKNOWN);
  4787. carla_debug("carla_lv2_state_store(%p, %i, %p, " P_SIZE ", %i, %i)", handle, key, value, size, type, flags);
  4788. return ((CarlaPluginLV2*)handle)->handleStateStore(key, value, size, type, flags);
  4789. }
  4790. static const void* carla_lv2_state_retrieve(LV2_State_Handle handle, uint32_t key, size_t* size, uint32_t* type, uint32_t* flags)
  4791. {
  4792. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, nullptr);
  4793. carla_debug("carla_lv2_state_retrieve(%p, %i, %p, %p, %p)", handle, key, size, type, flags);
  4794. return ((CarlaPluginLV2*)handle)->handleStateRetrieve(key, size, type, flags);
  4795. }
  4796. // -------------------------------------------------------------------
  4797. // URI-Map Feature
  4798. static uint32_t carla_lv2_uri_to_id(LV2_URI_Map_Callback_Data data, const char* map, const char* uri)
  4799. {
  4800. carla_debug("carla_lv2_uri_to_id(%p, \"%s\", \"%s\")", data, map, uri);
  4801. return carla_lv2_urid_map((LV2_URID_Map_Handle*)data, uri);
  4802. // unused
  4803. (void)map;
  4804. }
  4805. // -------------------------------------------------------------------
  4806. // URID Feature
  4807. static LV2_URID carla_lv2_urid_map(LV2_URID_Map_Handle handle, const char* uri)
  4808. {
  4809. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, CARLA_URI_MAP_ID_NULL);
  4810. CARLA_SAFE_ASSERT_RETURN(uri != nullptr && uri[0] != '\0', CARLA_URI_MAP_ID_NULL);
  4811. carla_debug("carla_lv2_urid_map(%p, \"%s\")", handle, uri);
  4812. // Atom types
  4813. if (std::strcmp(uri, LV2_ATOM__Blank) == 0)
  4814. return CARLA_URI_MAP_ID_ATOM_BLANK;
  4815. if (std::strcmp(uri, LV2_ATOM__Bool) == 0)
  4816. return CARLA_URI_MAP_ID_ATOM_BOOL;
  4817. if (std::strcmp(uri, LV2_ATOM__Chunk) == 0)
  4818. return CARLA_URI_MAP_ID_ATOM_CHUNK;
  4819. if (std::strcmp(uri, LV2_ATOM__Double) == 0)
  4820. return CARLA_URI_MAP_ID_ATOM_DOUBLE;
  4821. if (std::strcmp(uri, LV2_ATOM__Event) == 0)
  4822. return CARLA_URI_MAP_ID_ATOM_EVENT;
  4823. if (std::strcmp(uri, LV2_ATOM__Float) == 0)
  4824. return CARLA_URI_MAP_ID_ATOM_FLOAT;
  4825. if (std::strcmp(uri, LV2_ATOM__Int) == 0)
  4826. return CARLA_URI_MAP_ID_ATOM_INT;
  4827. if (std::strcmp(uri, LV2_ATOM__Literal) == 0)
  4828. return CARLA_URI_MAP_ID_ATOM_LITERAL;
  4829. if (std::strcmp(uri, LV2_ATOM__Long) == 0)
  4830. return CARLA_URI_MAP_ID_ATOM_LONG;
  4831. if (std::strcmp(uri, LV2_ATOM__Number) == 0)
  4832. return CARLA_URI_MAP_ID_ATOM_NUMBER;
  4833. if (std::strcmp(uri, LV2_ATOM__Object) == 0)
  4834. return CARLA_URI_MAP_ID_ATOM_OBJECT;
  4835. if (std::strcmp(uri, LV2_ATOM__Path) == 0)
  4836. return CARLA_URI_MAP_ID_ATOM_PATH;
  4837. if (std::strcmp(uri, LV2_ATOM__Property) == 0)
  4838. return CARLA_URI_MAP_ID_ATOM_PROPERTY;
  4839. if (std::strcmp(uri, LV2_ATOM__Resource) == 0)
  4840. return CARLA_URI_MAP_ID_ATOM_RESOURCE;
  4841. if (std::strcmp(uri, LV2_ATOM__Sequence) == 0)
  4842. return CARLA_URI_MAP_ID_ATOM_SEQUENCE;
  4843. if (std::strcmp(uri, LV2_ATOM__Sound) == 0)
  4844. return CARLA_URI_MAP_ID_ATOM_SOUND;
  4845. if (std::strcmp(uri, LV2_ATOM__String) == 0)
  4846. return CARLA_URI_MAP_ID_ATOM_STRING;
  4847. if (std::strcmp(uri, LV2_ATOM__Tuple) == 0)
  4848. return CARLA_URI_MAP_ID_ATOM_TUPLE;
  4849. if (std::strcmp(uri, LV2_ATOM__URI) == 0)
  4850. return CARLA_URI_MAP_ID_ATOM_URI;
  4851. if (std::strcmp(uri, LV2_ATOM__URID) == 0)
  4852. return CARLA_URI_MAP_ID_ATOM_URID;
  4853. if (std::strcmp(uri, LV2_ATOM__Vector) == 0)
  4854. return CARLA_URI_MAP_ID_ATOM_VECTOR;
  4855. if (std::strcmp(uri, LV2_ATOM__atomTransfer) == 0)
  4856. return CARLA_URI_MAP_ID_ATOM_TRANSFER_ATOM;
  4857. if (std::strcmp(uri, LV2_ATOM__eventTransfer) == 0)
  4858. return CARLA_URI_MAP_ID_ATOM_TRANSFER_EVENT;
  4859. // BufSize types
  4860. if (std::strcmp(uri, LV2_BUF_SIZE__maxBlockLength) == 0)
  4861. return CARLA_URI_MAP_ID_BUF_MAX_LENGTH;
  4862. if (std::strcmp(uri, LV2_BUF_SIZE__minBlockLength) == 0)
  4863. return CARLA_URI_MAP_ID_BUF_MIN_LENGTH;
  4864. if (std::strcmp(uri, LV2_BUF_SIZE__nominalBlockLength) == 0)
  4865. return CARLA_URI_MAP_ID_BUF_NOMINAL_LENGTH;
  4866. if (std::strcmp(uri, LV2_BUF_SIZE__sequenceSize) == 0)
  4867. return CARLA_URI_MAP_ID_BUF_SEQUENCE_SIZE;
  4868. // Log types
  4869. if (std::strcmp(uri, LV2_LOG__Error) == 0)
  4870. return CARLA_URI_MAP_ID_LOG_ERROR;
  4871. if (std::strcmp(uri, LV2_LOG__Note) == 0)
  4872. return CARLA_URI_MAP_ID_LOG_NOTE;
  4873. if (std::strcmp(uri, LV2_LOG__Trace) == 0)
  4874. return CARLA_URI_MAP_ID_LOG_TRACE;
  4875. if (std::strcmp(uri, LV2_LOG__Warning) == 0)
  4876. return CARLA_URI_MAP_ID_LOG_WARNING;
  4877. // Time types
  4878. if (std::strcmp(uri, LV2_TIME__Position) == 0)
  4879. return CARLA_URI_MAP_ID_TIME_POSITION;
  4880. if (std::strcmp(uri, LV2_TIME__bar) == 0)
  4881. return CARLA_URI_MAP_ID_TIME_BAR;
  4882. if (std::strcmp(uri, LV2_TIME__barBeat) == 0)
  4883. return CARLA_URI_MAP_ID_TIME_BAR_BEAT;
  4884. if (std::strcmp(uri, LV2_TIME__beat) == 0)
  4885. return CARLA_URI_MAP_ID_TIME_BEAT;
  4886. if (std::strcmp(uri, LV2_TIME__beatUnit) == 0)
  4887. return CARLA_URI_MAP_ID_TIME_BEAT_UNIT;
  4888. if (std::strcmp(uri, LV2_TIME__beatsPerBar) == 0)
  4889. return CARLA_URI_MAP_ID_TIME_BEATS_PER_BAR;
  4890. if (std::strcmp(uri, LV2_TIME__beatsPerMinute) == 0)
  4891. return CARLA_URI_MAP_ID_TIME_BEATS_PER_MINUTE;
  4892. if (std::strcmp(uri, LV2_TIME__frame) == 0)
  4893. return CARLA_URI_MAP_ID_TIME_FRAME;
  4894. if (std::strcmp(uri, LV2_TIME__framesPerSecond) == 0)
  4895. return CARLA_URI_MAP_ID_TIME_FRAMES_PER_SECOND;
  4896. if (std::strcmp(uri, LV2_TIME__speed) == 0)
  4897. return CARLA_URI_MAP_ID_TIME_SPEED;
  4898. if (std::strcmp(uri, LV2_KXSTUDIO_PROPERTIES__TimePositionTicksPerBeat) == 0)
  4899. return CARLA_URI_MAP_ID_TIME_TICKS_PER_BEAT;
  4900. // Others
  4901. if (std::strcmp(uri, LV2_MIDI__MidiEvent) == 0)
  4902. return CARLA_URI_MAP_ID_MIDI_EVENT;
  4903. if (std::strcmp(uri, LV2_PARAMETERS__sampleRate) == 0)
  4904. return CARLA_URI_MAP_ID_PARAM_SAMPLE_RATE;
  4905. if (std::strcmp(uri, LV2_UI__windowTitle) == 0)
  4906. return CARLA_URI_MAP_ID_UI_WINDOW_TITLE;
  4907. // Custom
  4908. if (std::strcmp(uri, LV2_KXSTUDIO_PROPERTIES__TransientWindowId) == 0)
  4909. return CARLA_URI_MAP_ID_CARLA_TRANSIENT_WIN_ID;
  4910. if (std::strcmp(uri, URI_CARLA_ATOM_WORKER) == 0)
  4911. return CARLA_URI_MAP_ID_CARLA_ATOM_WORKER;
  4912. // Custom types
  4913. return ((CarlaPluginLV2*)handle)->getCustomURID(uri);
  4914. }
  4915. static const char* carla_lv2_urid_unmap(LV2_URID_Map_Handle handle, LV2_URID urid)
  4916. {
  4917. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, nullptr);
  4918. CARLA_SAFE_ASSERT_RETURN(urid != CARLA_URI_MAP_ID_NULL, nullptr);
  4919. carla_debug("carla_lv2_urid_unmap(%p, %i)", handle, urid);
  4920. // Atom types
  4921. if (urid == CARLA_URI_MAP_ID_ATOM_BLANK)
  4922. return LV2_ATOM__Blank;
  4923. if (urid == CARLA_URI_MAP_ID_ATOM_BOOL)
  4924. return LV2_ATOM__Bool;
  4925. if (urid == CARLA_URI_MAP_ID_ATOM_CHUNK)
  4926. return LV2_ATOM__Chunk;
  4927. if (urid == CARLA_URI_MAP_ID_ATOM_DOUBLE)
  4928. return LV2_ATOM__Double;
  4929. if (urid == CARLA_URI_MAP_ID_ATOM_EVENT)
  4930. return LV2_ATOM__Event;
  4931. if (urid == CARLA_URI_MAP_ID_ATOM_FLOAT)
  4932. return LV2_ATOM__Float;
  4933. if (urid == CARLA_URI_MAP_ID_ATOM_INT)
  4934. return LV2_ATOM__Int;
  4935. if (urid == CARLA_URI_MAP_ID_ATOM_LITERAL)
  4936. return LV2_ATOM__Literal;
  4937. if (urid == CARLA_URI_MAP_ID_ATOM_LONG)
  4938. return LV2_ATOM__Long;
  4939. if (urid == CARLA_URI_MAP_ID_ATOM_NUMBER)
  4940. return LV2_ATOM__Number;
  4941. if (urid == CARLA_URI_MAP_ID_ATOM_OBJECT)
  4942. return LV2_ATOM__Object;
  4943. if (urid == CARLA_URI_MAP_ID_ATOM_PATH)
  4944. return LV2_ATOM__Path;
  4945. if (urid == CARLA_URI_MAP_ID_ATOM_PROPERTY)
  4946. return LV2_ATOM__Property;
  4947. if (urid == CARLA_URI_MAP_ID_ATOM_RESOURCE)
  4948. return LV2_ATOM__Resource;
  4949. if (urid == CARLA_URI_MAP_ID_ATOM_SEQUENCE)
  4950. return LV2_ATOM__Sequence;
  4951. if (urid == CARLA_URI_MAP_ID_ATOM_SOUND)
  4952. return LV2_ATOM__Sound;
  4953. if (urid == CARLA_URI_MAP_ID_ATOM_STRING)
  4954. return LV2_ATOM__String;
  4955. if (urid == CARLA_URI_MAP_ID_ATOM_TUPLE)
  4956. return LV2_ATOM__Tuple;
  4957. if (urid == CARLA_URI_MAP_ID_ATOM_URI)
  4958. return LV2_ATOM__URI;
  4959. if (urid == CARLA_URI_MAP_ID_ATOM_URID)
  4960. return LV2_ATOM__URID;
  4961. if (urid == CARLA_URI_MAP_ID_ATOM_VECTOR)
  4962. return LV2_ATOM__Vector;
  4963. if (urid == CARLA_URI_MAP_ID_ATOM_TRANSFER_ATOM)
  4964. return LV2_ATOM__atomTransfer;
  4965. if (urid == CARLA_URI_MAP_ID_ATOM_TRANSFER_EVENT)
  4966. return LV2_ATOM__eventTransfer;
  4967. // BufSize types
  4968. if (urid == CARLA_URI_MAP_ID_BUF_MAX_LENGTH)
  4969. return LV2_BUF_SIZE__maxBlockLength;
  4970. if (urid == CARLA_URI_MAP_ID_BUF_MIN_LENGTH)
  4971. return LV2_BUF_SIZE__minBlockLength;
  4972. if (urid == CARLA_URI_MAP_ID_BUF_NOMINAL_LENGTH)
  4973. return LV2_BUF_SIZE__nominalBlockLength;
  4974. if (urid == CARLA_URI_MAP_ID_BUF_SEQUENCE_SIZE)
  4975. return LV2_BUF_SIZE__sequenceSize;
  4976. // Log types
  4977. if (urid == CARLA_URI_MAP_ID_LOG_ERROR)
  4978. return LV2_LOG__Error;
  4979. if (urid == CARLA_URI_MAP_ID_LOG_NOTE)
  4980. return LV2_LOG__Note;
  4981. if (urid == CARLA_URI_MAP_ID_LOG_TRACE)
  4982. return LV2_LOG__Trace;
  4983. if (urid == CARLA_URI_MAP_ID_LOG_WARNING)
  4984. return LV2_LOG__Warning;
  4985. // Time types
  4986. if (urid == CARLA_URI_MAP_ID_TIME_POSITION)
  4987. return LV2_TIME__Position;
  4988. if (urid == CARLA_URI_MAP_ID_TIME_BAR)
  4989. return LV2_TIME__bar;
  4990. if (urid == CARLA_URI_MAP_ID_TIME_BAR_BEAT)
  4991. return LV2_TIME__barBeat;
  4992. if (urid == CARLA_URI_MAP_ID_TIME_BEAT)
  4993. return LV2_TIME__beat;
  4994. if (urid == CARLA_URI_MAP_ID_TIME_BEAT_UNIT)
  4995. return LV2_TIME__beatUnit;
  4996. if (urid == CARLA_URI_MAP_ID_TIME_BEATS_PER_BAR)
  4997. return LV2_TIME__beatsPerBar;
  4998. if (urid == CARLA_URI_MAP_ID_TIME_BEATS_PER_MINUTE)
  4999. return LV2_TIME__beatsPerMinute;
  5000. if (urid == CARLA_URI_MAP_ID_TIME_FRAME)
  5001. return LV2_TIME__frame;
  5002. if (urid == CARLA_URI_MAP_ID_TIME_FRAMES_PER_SECOND)
  5003. return LV2_TIME__framesPerSecond;
  5004. if (urid == CARLA_URI_MAP_ID_TIME_SPEED)
  5005. return LV2_TIME__speed;
  5006. if (urid == CARLA_URI_MAP_ID_TIME_TICKS_PER_BEAT)
  5007. return LV2_KXSTUDIO_PROPERTIES__TimePositionTicksPerBeat;
  5008. // Others
  5009. if (urid == CARLA_URI_MAP_ID_MIDI_EVENT)
  5010. return LV2_MIDI__MidiEvent;
  5011. if (urid == CARLA_URI_MAP_ID_PARAM_SAMPLE_RATE)
  5012. return LV2_PARAMETERS__sampleRate;
  5013. if (urid == CARLA_URI_MAP_ID_UI_WINDOW_TITLE)
  5014. return LV2_UI__windowTitle;
  5015. // Custom
  5016. if (urid == CARLA_URI_MAP_ID_CARLA_ATOM_WORKER)
  5017. return URI_CARLA_ATOM_WORKER;
  5018. if (urid == CARLA_URI_MAP_ID_CARLA_TRANSIENT_WIN_ID)
  5019. return LV2_KXSTUDIO_PROPERTIES__TransientWindowId;
  5020. // Custom types
  5021. return ((CarlaPluginLV2*)handle)->getCustomURIDString(urid);
  5022. }
  5023. // -------------------------------------------------------------------
  5024. // Worker Feature
  5025. static LV2_Worker_Status carla_lv2_worker_schedule(LV2_Worker_Schedule_Handle handle, uint32_t size, const void* data)
  5026. {
  5027. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, LV2_WORKER_ERR_UNKNOWN);
  5028. carla_debug("carla_lv2_worker_schedule(%p, %i, %p)", handle, size, data);
  5029. return ((CarlaPluginLV2*)handle)->handleWorkerSchedule(size, data);
  5030. }
  5031. static LV2_Worker_Status carla_lv2_worker_respond(LV2_Worker_Respond_Handle handle, uint32_t size, const void* data)
  5032. {
  5033. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, LV2_WORKER_ERR_UNKNOWN);
  5034. carla_debug("carla_lv2_worker_respond(%p, %i, %p)", handle, size, data);
  5035. return ((CarlaPluginLV2*)handle)->handleWorkerRespond(size, data);
  5036. }
  5037. // -------------------------------------------------------------------
  5038. // Inline Display Feature
  5039. static void carla_lv2_inline_display_queue_draw(LV2_Inline_Display_Handle handle)
  5040. {
  5041. CARLA_SAFE_ASSERT_RETURN(handle != nullptr,);
  5042. carla_debug("carla_lv2_inline_display_queue_draw(%p)", handle);
  5043. ((CarlaPluginLV2*)handle)->handleInlineDisplayQueueRedraw();
  5044. }
  5045. // -------------------------------------------------------------------
  5046. // External UI Feature
  5047. static void carla_lv2_external_ui_closed(LV2UI_Controller controller)
  5048. {
  5049. CARLA_SAFE_ASSERT_RETURN(controller != nullptr,);
  5050. carla_debug("carla_lv2_external_ui_closed(%p)", controller);
  5051. ((CarlaPluginLV2*)controller)->handleExternalUIClosed();
  5052. }
  5053. // -------------------------------------------------------------------
  5054. // UI Port-Map Feature
  5055. static uint32_t carla_lv2_ui_port_map(LV2UI_Feature_Handle handle, const char* symbol)
  5056. {
  5057. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, LV2UI_INVALID_PORT_INDEX);
  5058. carla_debug("carla_lv2_ui_port_map(%p, \"%s\")", handle, symbol);
  5059. return ((CarlaPluginLV2*)handle)->handleUIPortMap(symbol);
  5060. }
  5061. // -------------------------------------------------------------------
  5062. // UI Resize Feature
  5063. static int carla_lv2_ui_resize(LV2UI_Feature_Handle handle, int width, int height)
  5064. {
  5065. CARLA_SAFE_ASSERT_RETURN(handle != nullptr, 1);
  5066. carla_debug("carla_lv2_ui_resize(%p, %i, %i)", handle, width, height);
  5067. return ((CarlaPluginLV2*)handle)->handleUIResize(width, height);
  5068. }
  5069. // -------------------------------------------------------------------
  5070. // UI Extension
  5071. static void carla_lv2_ui_write_function(LV2UI_Controller controller, uint32_t port_index, uint32_t buffer_size, uint32_t format, const void* buffer)
  5072. {
  5073. CARLA_SAFE_ASSERT_RETURN(controller != nullptr,);
  5074. carla_debug("carla_lv2_ui_write_function(%p, %i, %i, %i, %p)", controller, port_index, buffer_size, format, buffer);
  5075. ((CarlaPluginLV2*)controller)->handleUIWrite(port_index, buffer_size, format, buffer);
  5076. }
  5077. // -------------------------------------------------------------------
  5078. // Lilv State
  5079. static void carla_lilv_set_port_value(const char* port_symbol, void* user_data, const void* value, uint32_t size, uint32_t type)
  5080. {
  5081. CARLA_SAFE_ASSERT_RETURN(user_data != nullptr,);
  5082. carla_debug("carla_lilv_set_port_value(\"%s\", %p, %p, %i, %i", port_symbol, user_data, value, size, type);
  5083. ((CarlaPluginLV2*)user_data)->handleLilvSetPortValue(port_symbol, value, size, type);
  5084. }
  5085. // -------------------------------------------------------------------
  5086. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginLV2)
  5087. };
  5088. // -------------------------------------------------------------------------------------------------------------------
  5089. bool CarlaPipeServerLV2::msgReceived(const char* const msg) noexcept
  5090. {
  5091. if (std::strcmp(msg, "exiting") == 0)
  5092. {
  5093. closePipeServer();
  5094. fUiState = UiHide;
  5095. return true;
  5096. }
  5097. if (std::strcmp(msg, "control") == 0)
  5098. {
  5099. uint32_t index;
  5100. float value;
  5101. CARLA_SAFE_ASSERT_RETURN(readNextLineAsUInt(index), true);
  5102. CARLA_SAFE_ASSERT_RETURN(readNextLineAsFloat(value), true);
  5103. try {
  5104. kPlugin->handleUIWrite(index, sizeof(float), CARLA_URI_MAP_ID_NULL, &value);
  5105. } CARLA_SAFE_EXCEPTION("magReceived control");
  5106. return true;
  5107. }
  5108. if (std::strcmp(msg, "atom") == 0)
  5109. {
  5110. uint32_t index, size;
  5111. const char* base64atom;
  5112. CARLA_SAFE_ASSERT_RETURN(readNextLineAsUInt(index), true);
  5113. CARLA_SAFE_ASSERT_RETURN(readNextLineAsUInt(size), true);
  5114. CARLA_SAFE_ASSERT_RETURN(readNextLineAsString(base64atom), true);
  5115. std::vector<uint8_t> chunk(carla_getChunkFromBase64String(base64atom));
  5116. delete[] base64atom;
  5117. CARLA_SAFE_ASSERT_RETURN(chunk.size() >= sizeof(LV2_Atom), true);
  5118. const LV2_Atom* const atom((const LV2_Atom*)chunk.data());
  5119. CARLA_SAFE_ASSERT_RETURN(lv2_atom_total_size(atom) == chunk.size(), true);
  5120. try {
  5121. kPlugin->handleUIWrite(index, lv2_atom_total_size(atom), CARLA_URI_MAP_ID_ATOM_TRANSFER_EVENT, atom);
  5122. } CARLA_SAFE_EXCEPTION("magReceived atom");
  5123. return true;
  5124. }
  5125. if (std::strcmp(msg, "program") == 0)
  5126. {
  5127. uint32_t index;
  5128. CARLA_SAFE_ASSERT_RETURN(readNextLineAsUInt(index), true);
  5129. try {
  5130. kPlugin->setMidiProgram(static_cast<int32_t>(index), false, true, true);
  5131. } CARLA_SAFE_EXCEPTION("msgReceived program");
  5132. return true;
  5133. }
  5134. if (std::strcmp(msg, "urid") == 0)
  5135. {
  5136. uint32_t urid;
  5137. const char* uri;
  5138. CARLA_SAFE_ASSERT_RETURN(readNextLineAsUInt(urid), true);
  5139. CARLA_SAFE_ASSERT_RETURN(readNextLineAsString(uri), true);
  5140. if (urid != 0)
  5141. {
  5142. try {
  5143. kPlugin->handleUridMap(urid, uri);
  5144. } CARLA_SAFE_EXCEPTION("msgReceived urid");
  5145. }
  5146. delete[] uri;
  5147. return true;
  5148. }
  5149. return false;
  5150. }
  5151. // -------------------------------------------------------------------------------------------------------------------
  5152. CarlaPlugin* CarlaPlugin::newLV2(const Initializer& init)
  5153. {
  5154. carla_debug("CarlaPlugin::newLV2({%p, \"%s\", \"%s\", " P_INT64 "})", init.engine, init.name, init.label, init.uniqueId);
  5155. CarlaPluginLV2* const plugin(new CarlaPluginLV2(init.engine, init.id));
  5156. if (! plugin->init(init.name, init.label, init.options))
  5157. {
  5158. delete plugin;
  5159. return nullptr;
  5160. }
  5161. return plugin;
  5162. }
  5163. void* carla_render_inline_display_lv2(CarlaPlugin* plugin, int width, int height)
  5164. {
  5165. CarlaPluginLV2* const lv2Plugin = (CarlaPluginLV2*)plugin;
  5166. return lv2Plugin->renderInlineDisplay(width, height);
  5167. }
  5168. // -------------------------------------------------------------------------------------------------------------------
  5169. CARLA_BACKEND_END_NAMESPACE