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.

6331 lines
234KB

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