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.

6344 lines
240KB

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