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.

6623 lines
242KB

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