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.

6428 lines
236KB

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