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.

6696 lines
244KB

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