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.

6490 lines
237KB

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