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.

6351 lines
235KB

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