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.

6481 lines
237KB

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