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.

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