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.

6398 lines
236KB

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