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.

6395 lines
236KB

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