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.

3069 lines
104KB

  1. /*
  2. * Carla CLAP Plugin
  3. * Copyright (C) 2022 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. #include "CarlaPluginInternal.hpp"
  18. #include "CarlaEngine.hpp"
  19. #include "CarlaBackendUtils.hpp"
  20. #include "CarlaClapUtils.hpp"
  21. #include "CarlaMathUtils.hpp"
  22. #include "CarlaPluginUI.hpp"
  23. #ifdef CARLA_OS_MAC
  24. # include "CarlaMacUtils.hpp"
  25. # import <Foundation/Foundation.h>
  26. #endif
  27. #include "water/files/File.h"
  28. #include "water/misc/Time.h"
  29. #ifdef _POSIX_VERSION
  30. # include <sys/epoll.h>
  31. # include <sys/socket.h>
  32. #endif
  33. // FIXME
  34. // #ifndef CLAP_WINDOW_API_NATIVE
  35. // #define CLAP_WINDOW_API_NATIVE ""
  36. // #define HAVE_X11 1
  37. // #endif
  38. CARLA_BACKEND_START_NAMESPACE
  39. // --------------------------------------------------------------------------------------------------------------------
  40. struct ClapEventData {
  41. uint16_t clapPortIndex;
  42. uint32_t supportedDialects;
  43. CarlaEngineEventPort* port;
  44. };
  45. struct CarlaPluginClapEventData {
  46. uint32_t portCount;
  47. ClapEventData* portData;
  48. ClapEventData* defaultPort; // either this->portData[x] or pData->portIn/Out
  49. CarlaPluginClapEventData() noexcept
  50. : portCount(0),
  51. portData(nullptr),
  52. defaultPort(nullptr) {}
  53. ~CarlaPluginClapEventData() noexcept
  54. {
  55. CARLA_SAFE_ASSERT_INT(portCount == 0, portCount);
  56. CARLA_SAFE_ASSERT(portData == nullptr);
  57. CARLA_SAFE_ASSERT(defaultPort == nullptr);
  58. }
  59. void createNew(const uint32_t newCount)
  60. {
  61. CARLA_SAFE_ASSERT_INT(portCount == 0, portCount);
  62. CARLA_SAFE_ASSERT_RETURN(portData == nullptr,);
  63. CARLA_SAFE_ASSERT_RETURN(defaultPort == nullptr,);
  64. CARLA_SAFE_ASSERT_RETURN(newCount > 0,);
  65. portData = new ClapEventData[newCount];
  66. portCount = newCount;
  67. defaultPort = nullptr;
  68. }
  69. void clear(CarlaEngineEventPort* const portToIgnore) noexcept
  70. {
  71. if (portData != nullptr)
  72. {
  73. for (uint32_t i=0; i < portCount; ++i)
  74. {
  75. if (portData[i].port != nullptr)
  76. {
  77. if (portData[i].port != portToIgnore)
  78. delete portData[i].port;
  79. portData[i].port = nullptr;
  80. }
  81. }
  82. delete[] portData;
  83. portData = nullptr;
  84. }
  85. portCount = 0;
  86. defaultPort = nullptr;
  87. }
  88. void initBuffers() const noexcept
  89. {
  90. for (uint32_t i=0; i < portCount; ++i)
  91. {
  92. if (portData[i].port != nullptr && (defaultPort == nullptr || portData[i].port != defaultPort->port))
  93. portData[i].port->initBuffer();
  94. }
  95. }
  96. CARLA_DECLARE_NON_COPYABLE(CarlaPluginClapEventData)
  97. };
  98. #ifdef _POSIX_VERSION
  99. // --------------------------------------------------------------------------------------------------------------------
  100. struct HostPosixFileDescriptorDetails {
  101. int hostFd;
  102. int pluginFd;
  103. clap_posix_fd_flags_t flags;
  104. };
  105. static constexpr const HostPosixFileDescriptorDetails kPosixFileDescriptorFallback = { -1, -1, 0x0 };
  106. static /* */ HostPosixFileDescriptorDetails kPosixFileDescriptorFallbackNC = { -1, -1, 0x0 };
  107. #endif
  108. // --------------------------------------------------------------------------------------------------------------------
  109. struct HostTimerDetails {
  110. clap_id clapId;
  111. uint32_t periodInMs;
  112. uint32_t lastCallTimeInMs;
  113. };
  114. static constexpr const HostTimerDetails kTimerFallback = { CLAP_INVALID_ID, 0, 0 };
  115. static /* */ HostTimerDetails kTimerFallbackNC = { CLAP_INVALID_ID, 0, 0 };
  116. // --------------------------------------------------------------------------------------------------------------------
  117. struct carla_clap_host : clap_host_t {
  118. class Callbacks {
  119. public:
  120. virtual ~Callbacks() {}
  121. virtual void clapRequestRestart() = 0;
  122. virtual void clapRequestProcess() = 0;
  123. virtual void clapRequestCallback() = 0;
  124. virtual void clapMarkDirty() = 0;
  125. #ifdef CLAP_WINDOW_API_NATIVE
  126. // gui
  127. virtual void clapGuiResizeHintsChanged() = 0;
  128. virtual bool clapGuiRequestResize(uint width, uint height) = 0;
  129. virtual bool clapGuiRequestShow() = 0;
  130. virtual bool clapGuiRequestHide() = 0;
  131. virtual void clapGuiClosed(bool wasDestroyed) = 0;
  132. #ifdef _POSIX_VERSION
  133. // posix fd
  134. virtual bool clapRegisterPosixFD(int fd, clap_posix_fd_flags_t flags) = 0;
  135. virtual bool clapModifyPosixFD(int fd, clap_posix_fd_flags_t flags) = 0;
  136. virtual bool clapUnregisterPosixFD(int fd) = 0;
  137. #endif
  138. // timer
  139. virtual bool clapRegisterTimer(uint32_t periodInMs, clap_id* timerId) = 0;
  140. virtual bool clapUnregisterTimer(clap_id timerId) = 0;
  141. #endif
  142. };
  143. Callbacks* const hostCallbacks;
  144. clap_host_state_t state;
  145. #ifdef CLAP_WINDOW_API_NATIVE
  146. clap_host_gui_t gui;
  147. #ifdef _POSIX_VERSION
  148. clap_host_posix_fd_support_t posixFD;
  149. #endif
  150. clap_host_timer_support_t timer;
  151. #endif
  152. carla_clap_host(Callbacks* const hostCb)
  153. : hostCallbacks(hostCb)
  154. {
  155. clap_version = CLAP_VERSION;
  156. host_data = this;
  157. name = "Carla";
  158. vendor = "falkTX";
  159. url = "https://kx.studio/carla";
  160. version = CARLA_VERSION_STRING;
  161. get_extension = carla_get_extension;
  162. request_restart = carla_request_restart;
  163. request_process = carla_request_process;
  164. request_callback = carla_request_callback;
  165. state.mark_dirty = carla_mark_dirty;
  166. #ifdef CLAP_WINDOW_API_NATIVE
  167. gui.resize_hints_changed = carla_resize_hints_changed;
  168. gui.request_resize = carla_request_resize;
  169. gui.request_show = carla_request_show;
  170. gui.request_hide = carla_request_hide;
  171. gui.closed = carla_closed;
  172. #ifdef _POSIX_VERSION
  173. posixFD.register_fd = carla_register_fd;
  174. posixFD.modify_fd = carla_modify_fd;
  175. posixFD.unregister_fd = carla_unregister_fd;
  176. #endif
  177. timer.register_timer = carla_register_timer;
  178. timer.unregister_timer = carla_unregister_timer;
  179. #endif
  180. }
  181. static CLAP_ABI const void* carla_get_extension(const clap_host_t* const host, const char* const extension_id)
  182. {
  183. carla_clap_host* const self = static_cast<carla_clap_host*>(host->host_data);
  184. if (std::strcmp(extension_id, CLAP_EXT_STATE) == 0)
  185. return &self->state;
  186. #ifdef CLAP_WINDOW_API_NATIVE
  187. if (std::strcmp(extension_id, CLAP_EXT_GUI) == 0)
  188. return &self->gui;
  189. #ifdef _POSIX_VERSION
  190. if (std::strcmp(extension_id, CLAP_EXT_POSIX_FD_SUPPORT) == 0)
  191. return &self->posixFD;
  192. #endif
  193. if (std::strcmp(extension_id, CLAP_EXT_TIMER_SUPPORT) == 0)
  194. return &self->timer;
  195. #endif
  196. carla_stderr("Plugin requested unsupported CLAP extension '%s'", extension_id);
  197. return nullptr;
  198. }
  199. static CLAP_ABI void carla_request_restart(const clap_host_t* const host)
  200. {
  201. static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapRequestRestart();
  202. }
  203. static CLAP_ABI void carla_request_process(const clap_host_t* const host)
  204. {
  205. static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapRequestProcess();
  206. }
  207. static CLAP_ABI void carla_request_callback(const clap_host_t* const host)
  208. {
  209. static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapRequestCallback();
  210. }
  211. static CLAP_ABI void carla_mark_dirty(const clap_host_t* const host)
  212. {
  213. static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapMarkDirty();
  214. }
  215. #ifdef CLAP_WINDOW_API_NATIVE
  216. static CLAP_ABI void carla_resize_hints_changed(const clap_host_t* const host)
  217. {
  218. static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapGuiResizeHintsChanged();
  219. }
  220. static CLAP_ABI bool carla_request_resize(const clap_host_t* const host, const uint32_t width, const uint32_t height)
  221. {
  222. return static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapGuiRequestResize(width, height);
  223. }
  224. static CLAP_ABI bool carla_request_show(const clap_host_t* const host)
  225. {
  226. return static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapGuiRequestShow();
  227. }
  228. static CLAP_ABI bool carla_request_hide(const clap_host_t* const host)
  229. {
  230. return static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapGuiRequestHide();
  231. }
  232. static CLAP_ABI void carla_closed(const clap_host_t* const host, bool was_destroyed)
  233. {
  234. static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapGuiClosed(was_destroyed);
  235. }
  236. #ifdef _POSIX_VERSION
  237. static CLAP_ABI bool carla_register_fd(const clap_host_t* const host, const int fd, const clap_posix_fd_flags_t flags)
  238. {
  239. return static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapRegisterPosixFD(fd, flags);
  240. }
  241. static CLAP_ABI bool carla_modify_fd(const clap_host_t* const host, const int fd, const clap_posix_fd_flags_t flags)
  242. {
  243. return static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapModifyPosixFD(fd, flags);
  244. }
  245. static CLAP_ABI bool carla_unregister_fd(const clap_host_t* const host, const int fd)
  246. {
  247. return static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapUnregisterPosixFD(fd);
  248. }
  249. #endif
  250. static CLAP_ABI bool carla_register_timer(const clap_host_t* const host, const uint32_t period_ms, clap_id* const timer_id)
  251. {
  252. return static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapRegisterTimer(period_ms, timer_id);
  253. }
  254. static CLAP_ABI bool carla_unregister_timer(const clap_host_t* const host, const clap_id timer_id)
  255. {
  256. return static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapUnregisterTimer(timer_id);
  257. }
  258. #endif
  259. };
  260. // --------------------------------------------------------------------------------------------------------------------
  261. struct carla_clap_input_audio_buffers {
  262. clap_audio_buffer_const_with_offset_t* buffers;
  263. uint32_t count;
  264. carla_clap_input_audio_buffers() noexcept
  265. : buffers(nullptr),
  266. count(0) {}
  267. ~carla_clap_input_audio_buffers()
  268. {
  269. delete[] buffers;
  270. }
  271. void realloc(const uint32_t portCount)
  272. {
  273. delete[] buffers;
  274. count = portCount;
  275. if (portCount != 0)
  276. {
  277. buffers = new clap_audio_buffer_const_with_offset_t[portCount];
  278. carla_zeroStructs(buffers, portCount);
  279. }
  280. else
  281. {
  282. buffers = nullptr;
  283. }
  284. }
  285. const clap_audio_buffer_t* cast() const noexcept
  286. {
  287. return static_cast<const clap_audio_buffer_t*>(static_cast<const void*>(buffers));
  288. }
  289. };
  290. struct carla_clap_output_audio_buffers {
  291. clap_audio_buffer_with_offset_t* buffers;
  292. uint32_t count;
  293. carla_clap_output_audio_buffers() noexcept
  294. : buffers(nullptr),
  295. count(0) {}
  296. ~carla_clap_output_audio_buffers()
  297. {
  298. delete[] buffers;
  299. }
  300. void realloc(const uint32_t portCount)
  301. {
  302. delete[] buffers;
  303. count = portCount;
  304. if (portCount != 0)
  305. {
  306. buffers = new clap_audio_buffer_with_offset_t[portCount];
  307. carla_zeroStructs(buffers, portCount);
  308. }
  309. else
  310. {
  311. buffers = nullptr;
  312. }
  313. }
  314. clap_audio_buffer_t* cast() noexcept
  315. {
  316. return static_cast<clap_audio_buffer_t*>(static_cast<void*>(buffers));
  317. }
  318. };
  319. // --------------------------------------------------------------------------------------------------------------------
  320. struct carla_clap_input_events : clap_input_events_t, CarlaPluginClapEventData {
  321. union Event {
  322. clap_event_header_t header;
  323. clap_event_param_value_t param;
  324. clap_event_param_gesture_t gesture;
  325. clap_event_midi_t midi;
  326. clap_event_note_t note;
  327. clap_event_midi_sysex_t sysex;
  328. };
  329. struct ScheduledParameterUpdate {
  330. bool updated;
  331. double value;
  332. clap_id clapId;
  333. void* cookie;
  334. ScheduledParameterUpdate()
  335. : updated(false),
  336. value(0.f),
  337. clapId(0),
  338. cookie(0) {}
  339. };
  340. Event* events;
  341. ScheduledParameterUpdate* updatedParams;
  342. uint32_t numEventsAllocated;
  343. uint32_t numEventsUsed;
  344. uint32_t numParams;
  345. carla_clap_input_events()
  346. : CarlaPluginClapEventData(),
  347. events(nullptr),
  348. updatedParams(nullptr),
  349. numEventsAllocated(0),
  350. numEventsUsed(0),
  351. numParams(0)
  352. {
  353. ctx = this;
  354. size = carla_size;
  355. get = carla_get;
  356. }
  357. ~carla_clap_input_events()
  358. {
  359. delete[] events;
  360. delete[] updatedParams;
  361. }
  362. // called on plugin reload
  363. // NOTE: clapId and cookie must be separately set outside this function
  364. void realloc(CarlaEngineEventPort* const defPortIn, const uint32_t portCount, const uint32_t paramCount)
  365. {
  366. numEventsUsed = 0;
  367. numParams = paramCount;
  368. delete[] events;
  369. delete[] updatedParams;
  370. if (portCount != 0 || paramCount != 0)
  371. {
  372. static_assert(kPluginMaxMidiEvents > MAX_MIDI_NOTE, "Enough space for input events");
  373. numEventsAllocated = paramCount * 2 + kPluginMaxMidiEvents * std::max(1u, portCount);
  374. events = new Event[numEventsAllocated];
  375. updatedParams = new ScheduledParameterUpdate[paramCount];
  376. }
  377. else
  378. {
  379. numEventsAllocated = 0;
  380. events = nullptr;
  381. updatedParams = nullptr;
  382. }
  383. CarlaPluginClapEventData::clear(defPortIn);
  384. if (portCount != 0)
  385. CarlaPluginClapEventData::createNew(portCount);
  386. }
  387. const clap_input_events_t* cast() const noexcept
  388. {
  389. return static_cast<const clap_input_events_t*>(this);
  390. }
  391. // called just before plugin processing
  392. void handleScheduledParameterUpdates()
  393. {
  394. uint32_t count = 0;
  395. for (uint32_t i=0; i<numParams; ++i)
  396. {
  397. if (updatedParams[i].updated)
  398. {
  399. events[count++].param = {
  400. { sizeof(clap_event_param_value_t), 0, 0, CLAP_EVENT_PARAM_VALUE, 0 },
  401. updatedParams[i].clapId,
  402. updatedParams[i].cookie,
  403. -1, -1, -1, -1,
  404. updatedParams[i].value
  405. };
  406. updatedParams[i].updated = false;
  407. }
  408. }
  409. numEventsUsed = count;
  410. }
  411. // called when a parameter is set from non-rt thread
  412. void setParamValue(const uint32_t index, const float value) noexcept
  413. {
  414. CARLA_SAFE_ASSERT_RETURN(index < numParams,);
  415. updatedParams[index].value = value;
  416. updatedParams[index].updated = true;
  417. }
  418. // called when a parameter is set from rt thread
  419. void setParamValueRT(const uint32_t index, const float value, const uint32_t frameOffset) noexcept
  420. {
  421. CARLA_SAFE_ASSERT_RETURN(index < numParams,);
  422. if (numEventsUsed == numEventsAllocated)
  423. return;
  424. events[numEventsUsed++].param = {
  425. { sizeof(clap_event_param_value_t), frameOffset, 0, CLAP_EVENT_PARAM_VALUE, CLAP_EVENT_IS_LIVE },
  426. updatedParams[index].clapId,
  427. updatedParams[index].cookie,
  428. -1, -1, -1, -1,
  429. value
  430. };
  431. }
  432. void addSimpleMidiEvent(const bool isLive, const uint16_t port, const uint32_t frameOffset, const uint8_t data[3])
  433. {
  434. if (numEventsUsed == numEventsAllocated)
  435. return;
  436. events[numEventsUsed++].midi = {
  437. { sizeof(clap_event_midi_t), frameOffset, 0, CLAP_EVENT_MIDI, isLive ? (uint32_t)CLAP_EVENT_IS_LIVE : 0u },
  438. port,
  439. { data[0], data[1], data[2] }
  440. };
  441. }
  442. void addSimpleNoteEvent(const bool isLive, const int16_t port, const uint32_t frameOffset,
  443. const uint8_t channel, const uint8_t key, const uint8_t velocity)
  444. {
  445. if (numEventsUsed == numEventsAllocated)
  446. return;
  447. const uint16_t eventType = velocity > 0 ? CLAP_EVENT_NOTE_ON : CLAP_EVENT_NOTE_OFF;
  448. events[numEventsUsed++].note = {
  449. { sizeof(clap_event_note_t), frameOffset, 0, eventType, isLive ? (uint32_t)CLAP_EVENT_IS_LIVE : 0u },
  450. -1,
  451. port,
  452. channel,
  453. key,
  454. static_cast<double>(velocity) / 127.0
  455. };
  456. }
  457. static CLAP_ABI uint32_t carla_size(const clap_input_events_t* const list) noexcept
  458. {
  459. return static_cast<const carla_clap_input_events*>(list->ctx)->numEventsUsed;
  460. }
  461. static CLAP_ABI const clap_event_header_t* carla_get(const clap_input_events_t* const list, const uint32_t index) noexcept
  462. {
  463. return &static_cast<const carla_clap_input_events*>(list->ctx)->events[index].header;
  464. }
  465. };
  466. // --------------------------------------------------------------------------------------------------------------------
  467. struct carla_clap_output_events : clap_output_events_t, CarlaPluginClapEventData {
  468. union Event {
  469. clap_event_header_t header;
  470. clap_event_param_value_t param;
  471. clap_event_midi_t midi;
  472. };
  473. Event* events;
  474. uint32_t numEventsAllocated;
  475. uint32_t numEventsUsed;
  476. carla_clap_output_events()
  477. : events(nullptr),
  478. numEventsAllocated(0),
  479. numEventsUsed(0)
  480. {
  481. ctx = this;
  482. try_push = carla_try_push;
  483. }
  484. ~carla_clap_output_events()
  485. {
  486. delete[] events;
  487. }
  488. // called on plugin reload
  489. void realloc(CarlaEngineEventPort* const defPortOut, const uint32_t portCount, const uint32_t paramCount)
  490. {
  491. numEventsUsed = 0;
  492. delete[] events;
  493. if (portCount != 0 || paramCount != 0)
  494. {
  495. numEventsAllocated = paramCount + kPluginMaxMidiEvents * std::max(1u, portCount);
  496. events = new Event[numEventsAllocated];
  497. }
  498. else
  499. {
  500. numEventsAllocated = 0;
  501. events = nullptr;
  502. }
  503. CarlaPluginClapEventData::clear(defPortOut);
  504. if (portCount != 0)
  505. CarlaPluginClapEventData::createNew(portCount);
  506. }
  507. const clap_output_events_t* cast() const noexcept
  508. {
  509. return static_cast<const clap_output_events_t*>(this);
  510. }
  511. bool tryPush(const clap_event_header_t* const event)
  512. {
  513. if (numEventsUsed == numEventsAllocated)
  514. return false;
  515. Event e;
  516. switch (event->type)
  517. {
  518. case CLAP_EVENT_PARAM_VALUE:
  519. e.param = *static_cast<const clap_event_param_value_t*>(static_cast<const void*>(event));
  520. break;
  521. case CLAP_EVENT_MIDI:
  522. e.midi = *static_cast<const clap_event_midi_t*>(static_cast<const void*>(event));
  523. break;
  524. default:
  525. return false;
  526. }
  527. events[numEventsUsed++] = e;
  528. return true;
  529. }
  530. static CLAP_ABI bool carla_try_push(const clap_output_events_t* const list, const clap_event_header_t* const event)
  531. {
  532. return static_cast<carla_clap_output_events*>(list->ctx)->tryPush(event);
  533. }
  534. };
  535. // --------------------------------------------------------------------------------------------------------------------
  536. class CarlaPluginCLAP : public CarlaPlugin,
  537. private CarlaPluginUI::Callback,
  538. private carla_clap_host::Callbacks
  539. {
  540. public:
  541. CarlaPluginCLAP(CarlaEngine* const engine, const uint id)
  542. : CarlaPlugin(engine, id),
  543. fPlugin(nullptr),
  544. fPluginDescriptor(nullptr),
  545. fPluginEntry(nullptr),
  546. fHost(this),
  547. fExtensions(),
  548. fInputAudioBuffers(),
  549. fOutputAudioBuffers(),
  550. fInputEvents(),
  551. fOutputEvents(),
  552. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  553. fAudioOutBuffers(nullptr),
  554. #endif
  555. fLastChunk(nullptr),
  556. fNeedsIdleCallback(false)
  557. {
  558. carla_debug("CarlaPluginCLAP::CarlaPluginCLAP(%p, %i)", engine, id);
  559. }
  560. ~CarlaPluginCLAP() override
  561. {
  562. carla_debug("CarlaPluginCLAP::~CarlaPluginCLAP()");
  563. runIdleCallbacksAsNeeded();
  564. #ifdef CLAP_WINDOW_API_NATIVE
  565. // close UI
  566. if (fUI.isCreated)
  567. showCustomUI(false);
  568. #endif
  569. pData->singleMutex.lock();
  570. pData->masterMutex.lock();
  571. if (pData->client != nullptr && pData->client->isActive())
  572. pData->client->deactivate(true);
  573. if (pData->active)
  574. {
  575. deactivate();
  576. pData->active = false;
  577. }
  578. if (fPlugin != nullptr)
  579. {
  580. fPlugin->destroy(fPlugin);
  581. fPlugin = nullptr;
  582. }
  583. if (fLastChunk != nullptr)
  584. {
  585. std::free(fLastChunk);
  586. fLastChunk = nullptr;
  587. }
  588. clearBuffers();
  589. if (fPluginEntry != nullptr)
  590. {
  591. fPluginEntry->deinit();
  592. fPluginEntry = nullptr;
  593. }
  594. }
  595. // -------------------------------------------------------------------
  596. // Information (base)
  597. PluginType getType() const noexcept override
  598. {
  599. return PLUGIN_CLAP;
  600. }
  601. PluginCategory getCategory() const noexcept override
  602. {
  603. CARLA_SAFE_ASSERT_RETURN(fPluginDescriptor != nullptr, PLUGIN_CATEGORY_NONE);
  604. if (fPluginDescriptor->features == nullptr)
  605. return PLUGIN_CATEGORY_NONE;
  606. return getPluginCategoryFromClapFeatures(fPluginDescriptor->features);
  607. }
  608. /*
  609. uint32_t getLatencyInFrames() const noexcept override
  610. {
  611. }
  612. */
  613. // -------------------------------------------------------------------
  614. // Information (count)
  615. uint32_t getMidiInCount() const noexcept override
  616. {
  617. return fInputEvents.portCount;
  618. }
  619. uint32_t getMidiOutCount() const noexcept override
  620. {
  621. return fOutputEvents.portCount;
  622. }
  623. // -------------------------------------------------------------------
  624. // Information (current data)
  625. uint getAudioPortHints(const bool isOutput, const uint32_t portIndex) const noexcept override
  626. {
  627. uint hints = 0x0;
  628. if (isOutput)
  629. {
  630. for (uint32_t i=0, j=0; i<fOutputAudioBuffers.count; ++i, j+=fOutputAudioBuffers.buffers[i].channel_count)
  631. {
  632. if (j != portIndex)
  633. continue;
  634. if (!fOutputAudioBuffers.buffers[i].isMain)
  635. hints |= AUDIO_PORT_IS_SIDECHAIN;
  636. }
  637. }
  638. else
  639. {
  640. for (uint32_t i=0, j=0; i<fInputAudioBuffers.count; ++i, j+=fInputAudioBuffers.buffers[i].channel_count)
  641. {
  642. if (j != portIndex)
  643. continue;
  644. if (!fInputAudioBuffers.buffers[i].isMain)
  645. hints |= AUDIO_PORT_IS_SIDECHAIN;
  646. }
  647. }
  648. return hints;
  649. }
  650. std::size_t getChunkData(void** const dataPtr) noexcept override
  651. {
  652. CARLA_SAFE_ASSERT_RETURN(pData->options & PLUGIN_OPTION_USE_CHUNKS, 0);
  653. CARLA_SAFE_ASSERT_RETURN(fExtensions.state != nullptr, 0);
  654. CARLA_SAFE_ASSERT_RETURN(dataPtr != nullptr, 0);
  655. std::free(fLastChunk);
  656. clap_ostream_impl stream;
  657. if (fExtensions.state->save(fPlugin, &stream))
  658. {
  659. *dataPtr = fLastChunk = stream.buffer;
  660. runIdleCallbacksAsNeeded();
  661. return stream.size;
  662. }
  663. else
  664. {
  665. *dataPtr = fLastChunk = nullptr;
  666. runIdleCallbacksAsNeeded();
  667. return 0;
  668. }
  669. }
  670. // -------------------------------------------------------------------
  671. // Information (per-plugin data)
  672. uint getOptionsAvailable() const noexcept override
  673. {
  674. uint options = 0x0;
  675. if (fExtensions.state != nullptr)
  676. options |= PLUGIN_OPTION_USE_CHUNKS;
  677. // TODO alternative if plugin does not support CLAP_NOTE_DIALECT_MIDI
  678. if (fInputEvents.portCount != 0)
  679. {
  680. options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  681. options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  682. options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  683. options |= PLUGIN_OPTION_SEND_PITCHBEND;
  684. options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  685. options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  686. options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  687. }
  688. return options;
  689. }
  690. float getParameterValue(const uint32_t parameterId) const noexcept override
  691. {
  692. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr, 0.f);
  693. CARLA_SAFE_ASSERT_RETURN(fExtensions.params != nullptr, 0.f);
  694. const clap_id clapId = pData->param.data[parameterId].rindex;
  695. double value;
  696. CARLA_SAFE_ASSERT_RETURN(fExtensions.params->get_value(fPlugin, clapId, &value), 0.f);
  697. return value;
  698. }
  699. bool getLabel(char* const strBuf) const noexcept override
  700. {
  701. CARLA_SAFE_ASSERT_RETURN(fPluginDescriptor != nullptr, false);
  702. std::strncpy(strBuf, fPluginDescriptor->id, STR_MAX);
  703. return true;
  704. }
  705. bool getMaker(char* const strBuf) const noexcept override
  706. {
  707. CARLA_SAFE_ASSERT_RETURN(fPluginDescriptor != nullptr, false);
  708. std::strncpy(strBuf, fPluginDescriptor->vendor, STR_MAX);
  709. return true;
  710. }
  711. bool getCopyright(char* const strBuf) const noexcept override
  712. {
  713. return getMaker(strBuf);
  714. }
  715. bool getRealName(char* const strBuf) const noexcept override
  716. {
  717. CARLA_SAFE_ASSERT_RETURN(fPluginDescriptor != nullptr, false);
  718. std::strncpy(strBuf, fPluginDescriptor->name, STR_MAX);
  719. return true;
  720. }
  721. bool getParameterName(const uint32_t parameterId, char* const strBuf) const noexcept override
  722. {
  723. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr, false);
  724. CARLA_SAFE_ASSERT_RETURN(fExtensions.params != nullptr, false);
  725. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  726. clap_param_info_t paramInfo = {};
  727. CARLA_SAFE_ASSERT_RETURN(fExtensions.params->get_info(fPlugin, parameterId, &paramInfo), false);
  728. std::strncpy(strBuf, paramInfo.name, STR_MAX);
  729. return true;
  730. }
  731. bool getParameterSymbol(const uint32_t parameterId, char* const strBuf) const noexcept override
  732. {
  733. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  734. const clap_id clapId = pData->param.data[parameterId].rindex;
  735. std::snprintf(strBuf, STR_MAX, "%u", clapId);
  736. return true;
  737. }
  738. bool getParameterText(const uint32_t parameterId, char* const strBuf) noexcept override
  739. {
  740. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr, false);
  741. CARLA_SAFE_ASSERT_RETURN(fExtensions.params != nullptr, false);
  742. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  743. const clap_id clapId = pData->param.data[parameterId].rindex;
  744. double value;
  745. CARLA_SAFE_ASSERT_RETURN(fExtensions.params->get_value(fPlugin, clapId, &value), false);
  746. return fExtensions.params->value_to_text(fPlugin, clapId, value, strBuf, STR_MAX);
  747. }
  748. bool getParameterGroupName(const uint32_t parameterId, char* const strBuf) const noexcept override
  749. {
  750. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr, false);
  751. CARLA_SAFE_ASSERT_RETURN(fExtensions.params != nullptr, false);
  752. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  753. clap_param_info_t paramInfo = {};
  754. CARLA_SAFE_ASSERT_RETURN(fExtensions.params->get_info(fPlugin, parameterId, &paramInfo), false);
  755. if (paramInfo.module[0] == '\0')
  756. return false;
  757. if (char* const sep = std::strrchr(paramInfo.module, '/'))
  758. {
  759. paramInfo.module[STR_MAX/2-2] = sep[0] = '\0';
  760. std::snprintf(strBuf, STR_MAX, "%s:%s", paramInfo.module, paramInfo.module);
  761. return true;
  762. }
  763. return false;
  764. }
  765. // -------------------------------------------------------------------
  766. // Set data (state)
  767. // nothing
  768. // -------------------------------------------------------------------
  769. // Set data (internal stuff)
  770. #ifdef CLAP_WINDOW_API_NATIVE
  771. void setName(const char* const newName) override
  772. {
  773. CarlaPlugin::setName(newName);
  774. if (fUI.isCreated && pData->uiTitle.isEmpty())
  775. setWindowTitle(nullptr);
  776. }
  777. #endif
  778. // -------------------------------------------------------------------
  779. // Set data (plugin-specific stuff)
  780. void setParameterValue(const uint32_t parameterId, const float value, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  781. {
  782. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr,);
  783. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  784. const float fixedValue = pData->param.getFixedValue(parameterId, value);
  785. fInputEvents.setParamValue(parameterId, fixedValue);
  786. CarlaPlugin::setParameterValue(parameterId, fixedValue, sendGui, sendOsc, sendCallback);
  787. }
  788. void setParameterValueRT(const uint32_t parameterId, const float value, const uint32_t frameOffset, const bool sendCallbackLater) noexcept override
  789. {
  790. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr,);
  791. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  792. const float fixedValue = pData->param.getFixedValue(parameterId, value);
  793. fInputEvents.setParamValueRT(parameterId, fixedValue, frameOffset);
  794. CarlaPlugin::setParameterValueRT(parameterId, fixedValue, frameOffset, sendCallbackLater);
  795. }
  796. void setChunkData(const void* const data, const std::size_t dataSize) override
  797. {
  798. CARLA_SAFE_ASSERT_RETURN(pData->options & PLUGIN_OPTION_USE_CHUNKS,);
  799. CARLA_SAFE_ASSERT_RETURN(fExtensions.state != nullptr,);
  800. CARLA_SAFE_ASSERT_RETURN(data != nullptr,);
  801. CARLA_SAFE_ASSERT_RETURN(dataSize > 0,);
  802. const clap_istream_impl stream(data, dataSize);
  803. if (fExtensions.state->load(fPlugin, &stream))
  804. pData->updateParameterValues(this, true, true, false);
  805. runIdleCallbacksAsNeeded();
  806. }
  807. // -------------------------------------------------------------------
  808. // Set ui stuff
  809. #ifdef CLAP_WINDOW_API_NATIVE
  810. void setWindowTitle(const char* const title) noexcept
  811. {
  812. if (!fUI.isCreated)
  813. return;
  814. CarlaString uiTitle;
  815. if (title != nullptr)
  816. {
  817. uiTitle = title;
  818. }
  819. else
  820. {
  821. uiTitle = pData->name;
  822. uiTitle += " (GUI)";
  823. }
  824. if (fUI.isEmbed)
  825. {
  826. if (fUI.window != nullptr)
  827. fUI.window->setTitle(uiTitle.buffer());
  828. }
  829. else
  830. {
  831. fExtensions.gui->suggest_title(fPlugin, uiTitle.buffer());
  832. }
  833. }
  834. void setCustomUITitle(const char* const title) noexcept override
  835. {
  836. setWindowTitle(title);
  837. CarlaPlugin::setCustomUITitle(title);
  838. }
  839. void showCustomUI(const bool yesNo) override
  840. {
  841. CARLA_SAFE_ASSERT_RETURN(fExtensions.gui != nullptr,);
  842. if (yesNo)
  843. {
  844. if (fUI.isVisible)
  845. {
  846. fExtensions.gui->show(fPlugin);
  847. if (fUI.isEmbed)
  848. {
  849. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  850. fUI.window->show();
  851. fUI.window->focus();
  852. }
  853. runIdleCallbacksAsNeeded();
  854. return;
  855. }
  856. const EngineOptions& opts(pData->engine->getOptions());
  857. if (!fUI.initalized)
  858. {
  859. fUI.isEmbed = fExtensions.gui->is_api_supported(fPlugin, CLAP_WINDOW_API_NATIVE, false);
  860. fUI.initalized = true;
  861. }
  862. if (!fUI.isCreated)
  863. {
  864. if (!fExtensions.gui->create(fPlugin, CLAP_WINDOW_API_NATIVE, !fUI.isEmbed))
  865. {
  866. pData->engine->callback(true, true,
  867. ENGINE_CALLBACK_UI_STATE_CHANGED,
  868. pData->id,
  869. -1,
  870. 0, 0, 0.0f,
  871. "Plugin refused to open its own UI");
  872. return;
  873. }
  874. fUI.isCreated = true;
  875. }
  876. const bool resizable = fExtensions.gui->can_resize(fPlugin);
  877. #if defined(CARLA_OS_WIN)
  878. fUI.window = CarlaPluginUI::newWindows(this, opts.frontendWinId, opts.pluginsAreStandalone, resizable);
  879. #elif defined(CARLA_OS_MAC)
  880. fUI.window = CarlaPluginUI::newCocoa(this, opts.frontendWinId, opts.pluginsAreStandalone, resizable);
  881. #elif defined(HAVE_X11)
  882. fUI.window = CarlaPluginUI::newX11(this, opts.frontendWinId, opts.pluginsAreStandalone, resizable, false);
  883. #else
  884. #error why is CLAP_WINDOW_API_NATIVE defined??
  885. #endif
  886. if (carla_isNotZero(opts.uiScale))
  887. fExtensions.gui->set_scale(fPlugin, opts.uiScale);
  888. setWindowTitle(nullptr);
  889. if (fUI.isEmbed)
  890. {
  891. clap_window_t win = { CLAP_WINDOW_API_NATIVE, {} };
  892. win.ptr = fUI.window->getPtr();
  893. fExtensions.gui->set_parent(fPlugin, &win);
  894. uint32_t width, height;
  895. if (fExtensions.gui->get_size(fPlugin, &width, &height))
  896. fUI.window->setSize(width, height, false);
  897. fExtensions.gui->show(fPlugin);
  898. fUI.window->show();
  899. }
  900. else
  901. {
  902. clap_window_t win = { CLAP_WINDOW_API_NATIVE, {} };
  903. win.uptr = opts.frontendWinId;
  904. fExtensions.gui->set_transient(fPlugin, &win);
  905. fExtensions.gui->show(fPlugin);
  906. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  907. pData->tryTransient();
  908. #endif
  909. }
  910. fUI.isVisible = true;
  911. }
  912. else
  913. {
  914. fUI.isVisible = false;
  915. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  916. pData->transientTryCounter = 0;
  917. #endif
  918. if (fUI.window != nullptr)
  919. fUI.window->hide();
  920. fExtensions.gui->hide(fPlugin);
  921. if (fUI.isCreated)
  922. {
  923. fExtensions.gui->destroy(fPlugin);
  924. fUI.isCreated = false;
  925. }
  926. if (fUI.window != nullptr)
  927. {
  928. delete fUI.window;
  929. fUI.window = nullptr;
  930. }
  931. }
  932. runIdleCallbacksAsNeeded();
  933. }
  934. #endif
  935. /*
  936. void* embedCustomUI(void* const ptr) override
  937. {
  938. }
  939. */
  940. void idle() override
  941. {
  942. CarlaPlugin::idle();
  943. }
  944. void uiIdle() override
  945. {
  946. runIdleCallbacksAsNeeded();
  947. CarlaPlugin::uiIdle();
  948. }
  949. // -------------------------------------------------------------------
  950. // Plugin state
  951. void reload() override
  952. {
  953. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  954. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr,);
  955. carla_debug("CarlaPluginCLAP::reload() - start");
  956. // Safely disable plugin for reload
  957. const ScopedDisabler sd(this);
  958. if (pData->active)
  959. deactivate();
  960. clearBuffers();
  961. const clap_plugin_audio_ports_t* audioPortsExt = static_cast<const clap_plugin_audio_ports_t*>(
  962. fPlugin->get_extension(fPlugin, CLAP_EXT_AUDIO_PORTS));
  963. const clap_plugin_note_ports_t* notePortsExt = static_cast<const clap_plugin_note_ports_t*>(
  964. fPlugin->get_extension(fPlugin, CLAP_EXT_NOTE_PORTS));
  965. const clap_plugin_params_t* paramsExt = static_cast<const clap_plugin_params_t*>(
  966. fPlugin->get_extension(fPlugin, CLAP_EXT_PARAMS));
  967. #ifdef _POSIX_VERSION
  968. const clap_plugin_posix_fd_support_t* posixFdExt = static_cast<const clap_plugin_posix_fd_support_t*>(
  969. fPlugin->get_extension(fPlugin, CLAP_EXT_POSIX_FD_SUPPORT));
  970. #endif
  971. const clap_plugin_state_t* stateExt = static_cast<const clap_plugin_state_t*>(
  972. fPlugin->get_extension(fPlugin, CLAP_EXT_STATE));
  973. const clap_plugin_timer_support_t* timerExt = static_cast<const clap_plugin_timer_support_t*>(
  974. fPlugin->get_extension(fPlugin, CLAP_EXT_TIMER_SUPPORT));
  975. if (audioPortsExt != nullptr && (audioPortsExt->count == nullptr || audioPortsExt->get == nullptr))
  976. audioPortsExt = nullptr;
  977. if (notePortsExt != nullptr && (notePortsExt->count == nullptr || notePortsExt->get == nullptr))
  978. notePortsExt = nullptr;
  979. if (paramsExt != nullptr && (paramsExt->count == nullptr || paramsExt->get_info == nullptr))
  980. paramsExt = nullptr;
  981. #ifdef _POSIX_VERSION
  982. if (posixFdExt != nullptr && (posixFdExt->on_fd == nullptr))
  983. posixFdExt = nullptr;
  984. #endif
  985. if (stateExt != nullptr && (stateExt->save == nullptr || stateExt->load == nullptr))
  986. stateExt = nullptr;
  987. if (timerExt != nullptr && (timerExt->on_timer == nullptr))
  988. timerExt = nullptr;
  989. fExtensions.params = paramsExt;
  990. #ifdef _POSIX_VERSION
  991. fExtensions.posixFD = posixFdExt;
  992. #endif
  993. fExtensions.state = stateExt;
  994. fExtensions.timer = timerExt;
  995. #ifdef CLAP_WINDOW_API_NATIVE
  996. const clap_plugin_gui_t* guiExt = static_cast<const clap_plugin_gui_t*>(
  997. fPlugin->get_extension(fPlugin, CLAP_EXT_GUI));
  998. if (guiExt != nullptr && (guiExt->is_api_supported == nullptr
  999. || guiExt->create == nullptr
  1000. || guiExt->destroy == nullptr
  1001. || guiExt->set_scale == nullptr
  1002. || guiExt->get_size == nullptr
  1003. || guiExt->can_resize == nullptr
  1004. || guiExt->get_resize_hints == nullptr
  1005. || guiExt->adjust_size == nullptr
  1006. || guiExt->set_size == nullptr
  1007. || guiExt->set_parent == nullptr
  1008. || guiExt->set_transient == nullptr
  1009. || guiExt->suggest_title == nullptr
  1010. || guiExt->show == nullptr
  1011. || guiExt->hide == nullptr))
  1012. guiExt = nullptr;
  1013. fExtensions.gui = guiExt;
  1014. #endif
  1015. const uint32_t numAudioInputPorts = audioPortsExt != nullptr ? audioPortsExt->count(fPlugin, true) : 0;
  1016. const uint32_t numAudioOutputPorts = audioPortsExt != nullptr ? audioPortsExt->count(fPlugin, false) : 0;
  1017. const uint32_t numNoteInputPorts = notePortsExt != nullptr ? notePortsExt->count(fPlugin, true) : 0;
  1018. const uint32_t numNoteOutputPorts = notePortsExt != nullptr ? notePortsExt->count(fPlugin, false) : 0;
  1019. const uint32_t numParameters = paramsExt != nullptr ? paramsExt->count(fPlugin) : 0;
  1020. uint32_t aIns, aOuts, mIns, mOuts, params;
  1021. aIns = aOuts = mIns = mOuts = params = 0;
  1022. bool needsCtrlIn, needsCtrlOut;
  1023. needsCtrlIn = needsCtrlOut = false;
  1024. fInputAudioBuffers.realloc(numAudioInputPorts);
  1025. fOutputAudioBuffers.realloc(numAudioOutputPorts);
  1026. for (uint32_t i=0; i<numAudioInputPorts; ++i)
  1027. {
  1028. clap_audio_port_info_t portInfo = {};
  1029. CARLA_SAFE_ASSERT_BREAK(audioPortsExt->get(fPlugin, i, true, &portInfo));
  1030. fInputAudioBuffers.buffers[i].channel_count = portInfo.channel_count;
  1031. fInputAudioBuffers.buffers[i].offset = aIns;
  1032. fInputAudioBuffers.buffers[i].isMain = portInfo.flags & CLAP_AUDIO_PORT_IS_MAIN;
  1033. aIns += portInfo.channel_count;
  1034. }
  1035. for (uint32_t i=0; i<numAudioOutputPorts; ++i)
  1036. {
  1037. clap_audio_port_info_t portInfo = {};
  1038. CARLA_SAFE_ASSERT_BREAK(audioPortsExt->get(fPlugin, i, false, &portInfo));
  1039. fOutputAudioBuffers.buffers[i].channel_count = portInfo.channel_count;
  1040. fOutputAudioBuffers.buffers[i].offset = aOuts;
  1041. fOutputAudioBuffers.buffers[i].isMain = portInfo.flags & CLAP_AUDIO_PORT_IS_MAIN;
  1042. for (uint32_t j=0; j<portInfo.channel_count; ++j)
  1043. fOutputAudioBuffers.buffers[i].constant_mask |= (1 << j);
  1044. aOuts += portInfo.channel_count;
  1045. }
  1046. for (uint32_t i=0; i<numNoteInputPorts; ++i)
  1047. {
  1048. clap_note_port_info_t portInfo = {};
  1049. CARLA_SAFE_ASSERT_BREAK(notePortsExt->get(fPlugin, i, true, &portInfo));
  1050. if (portInfo.supported_dialects & (CLAP_NOTE_DIALECT_CLAP|CLAP_NOTE_DIALECT_MIDI))
  1051. ++mIns;
  1052. }
  1053. for (uint32_t i=0; i<numNoteOutputPorts; ++i)
  1054. {
  1055. clap_note_port_info_t portInfo = {};
  1056. CARLA_SAFE_ASSERT_BREAK(notePortsExt->get(fPlugin, i, false, &portInfo));
  1057. if (portInfo.supported_dialects & CLAP_NOTE_DIALECT_MIDI)
  1058. ++mOuts;
  1059. }
  1060. for (uint32_t i=0; i<numParameters; ++i, ++params)
  1061. {
  1062. clap_param_info_t paramInfo = {};
  1063. CARLA_SAFE_ASSERT_BREAK(paramsExt->get_info(fPlugin, i, &paramInfo));
  1064. }
  1065. if (aIns > 0)
  1066. {
  1067. pData->audioIn.createNew(aIns);
  1068. }
  1069. if (aOuts > 0)
  1070. {
  1071. pData->audioOut.createNew(aOuts);
  1072. needsCtrlIn = true;
  1073. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1074. fAudioOutBuffers = new float*[aOuts];
  1075. for (uint32_t i=0; i < aOuts; ++i)
  1076. fAudioOutBuffers[i] = nullptr;
  1077. #endif
  1078. }
  1079. if (mIns == 1)
  1080. needsCtrlIn = true;
  1081. if (mOuts == 1)
  1082. needsCtrlOut = true;
  1083. if (params > 0)
  1084. {
  1085. pData->param.createNew(params, false);
  1086. needsCtrlIn = true;
  1087. }
  1088. fInputEvents.realloc(pData->event.portIn, mIns, params);
  1089. fOutputEvents.realloc(pData->event.portOut, mOuts, params);
  1090. const EngineProcessMode processMode = pData->engine->getProccessMode();
  1091. const uint portNameSize = pData->engine->getMaxPortNameSize();
  1092. CarlaString portName;
  1093. // Audio Ins
  1094. for (uint32_t j=0; j < aIns; ++j)
  1095. {
  1096. portName.clear();
  1097. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1098. {
  1099. portName = pData->name;
  1100. portName += ":";
  1101. }
  1102. if (aIns > 1)
  1103. {
  1104. portName += "input_";
  1105. portName += CarlaString(j+1);
  1106. }
  1107. else
  1108. portName += "input";
  1109. portName.truncate(portNameSize);
  1110. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true, j);
  1111. pData->audioIn.ports[j].rindex = j;
  1112. }
  1113. // Audio Outs
  1114. for (uint32_t j=0; j < aOuts; ++j)
  1115. {
  1116. portName.clear();
  1117. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1118. {
  1119. portName = pData->name;
  1120. portName += ":";
  1121. }
  1122. if (aOuts > 1)
  1123. {
  1124. portName += "output_";
  1125. portName += CarlaString(j+1);
  1126. }
  1127. else
  1128. portName += "output";
  1129. portName.truncate(portNameSize);
  1130. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, j);
  1131. pData->audioOut.ports[j].rindex = j;
  1132. }
  1133. // MIDI Ins
  1134. for (uint32_t i=0, j=0; i<numNoteInputPorts; ++i)
  1135. {
  1136. clap_note_port_info_t portInfo = {};
  1137. CARLA_SAFE_ASSERT_BREAK(notePortsExt->get(fPlugin, i, true, &portInfo));
  1138. if ((portInfo.supported_dialects & (CLAP_NOTE_DIALECT_CLAP|CLAP_NOTE_DIALECT_MIDI)) == 0x0)
  1139. continue;
  1140. CARLA_SAFE_ASSERT_UINT2_BREAK(j < mIns, j, mIns);
  1141. fInputEvents.portData[j].clapPortIndex = i;
  1142. fInputEvents.portData[j].supportedDialects = portInfo.supported_dialects;
  1143. if (mIns > 1)
  1144. {
  1145. portName.clear();
  1146. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1147. {
  1148. portName = pData->name;
  1149. portName += ":";
  1150. }
  1151. portName += portInfo.name;
  1152. portName.truncate(portNameSize);
  1153. fInputEvents.portData[j].port = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, j);
  1154. }
  1155. else
  1156. {
  1157. fInputEvents.portData[j].port = nullptr;
  1158. fInputEvents.defaultPort = &fInputEvents.portData[0];
  1159. }
  1160. ++j;
  1161. }
  1162. // MIDI Outs
  1163. for (uint32_t i=0, j=0; i<numNoteOutputPorts; ++i)
  1164. {
  1165. clap_note_port_info_t portInfo = {};
  1166. CARLA_SAFE_ASSERT_BREAK(notePortsExt->get(fPlugin, i, false, &portInfo));
  1167. if ((portInfo.supported_dialects & CLAP_NOTE_DIALECT_MIDI) == 0x0)
  1168. continue;
  1169. CARLA_SAFE_ASSERT_UINT2_BREAK(j < mOuts, j, mOuts);
  1170. fOutputEvents.portData[j].clapPortIndex = i;
  1171. fOutputEvents.portData[j].supportedDialects = portInfo.supported_dialects;
  1172. if (mOuts > 1)
  1173. {
  1174. portName.clear();
  1175. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1176. {
  1177. portName = pData->name;
  1178. portName += ":";
  1179. }
  1180. portName += portInfo.name;
  1181. portName.truncate(portNameSize);
  1182. fOutputEvents.portData[j].port = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, j);
  1183. }
  1184. else
  1185. {
  1186. fOutputEvents.portData[j].port = nullptr;
  1187. fOutputEvents.defaultPort = &fOutputEvents.portData[0];
  1188. }
  1189. ++j;
  1190. }
  1191. // Parameters
  1192. for (uint32_t i=0; i<numParameters; ++i)
  1193. {
  1194. clap_param_info_t paramInfo = {};
  1195. CARLA_SAFE_ASSERT_BREAK(paramsExt->get_info(fPlugin, i, &paramInfo));
  1196. CARLA_SAFE_ASSERT_BREAK(i < params);
  1197. pData->param.data[i].index = i;
  1198. pData->param.data[i].rindex = static_cast<int32_t>(paramInfo.id);
  1199. double min, max, def, step, stepSmall, stepLarge;
  1200. min = paramInfo.min_value;
  1201. max = paramInfo.max_value;
  1202. def = paramInfo.default_value;
  1203. if (min >= max)
  1204. max = min + 0.1;
  1205. if (def < min)
  1206. def = min;
  1207. else if (def > max)
  1208. def = max;
  1209. if (paramInfo.flags & (CLAP_PARAM_IS_HIDDEN|CLAP_PARAM_IS_BYPASS))
  1210. {
  1211. pData->param.data[i].type = PARAMETER_UNKNOWN;
  1212. }
  1213. else if (paramInfo.flags & CLAP_PARAM_IS_READONLY)
  1214. {
  1215. pData->param.data[i].type = PARAMETER_OUTPUT;
  1216. needsCtrlOut = true;
  1217. }
  1218. else
  1219. {
  1220. pData->param.data[i].type = PARAMETER_INPUT;
  1221. }
  1222. if (paramInfo.flags & CLAP_PARAM_IS_STEPPED)
  1223. {
  1224. if (carla_isEqual(max - min, 1.0))
  1225. {
  1226. step = stepSmall = stepLarge = 1.0;
  1227. pData->param.data[i].hints |= PARAMETER_IS_BOOLEAN;
  1228. }
  1229. else
  1230. {
  1231. step = 1.0;
  1232. stepSmall = 1.0;
  1233. stepLarge = std::min(max - min, 10.0);
  1234. }
  1235. pData->param.data[i].hints |= PARAMETER_IS_INTEGER;
  1236. }
  1237. else
  1238. {
  1239. double range = max - min;
  1240. step = range/100.0;
  1241. stepSmall = range/1000.0;
  1242. stepLarge = range/10.0;
  1243. }
  1244. if (pData->param.data[i].type != PARAMETER_UNKNOWN)
  1245. {
  1246. pData->param.data[i].hints |= PARAMETER_IS_ENABLED;
  1247. pData->param.data[i].hints |= PARAMETER_USES_CUSTOM_TEXT;
  1248. if (paramInfo.flags & CLAP_PARAM_IS_AUTOMATABLE)
  1249. {
  1250. pData->param.data[i].hints |= PARAMETER_IS_AUTOMATABLE;
  1251. if ((paramInfo.flags & CLAP_PARAM_IS_STEPPED) == 0x0)
  1252. pData->param.data[i].hints |= PARAMETER_CAN_BE_CV_CONTROLLED;
  1253. }
  1254. }
  1255. pData->param.ranges[i].min = min;
  1256. pData->param.ranges[i].max = max;
  1257. pData->param.ranges[i].def = def;
  1258. pData->param.ranges[i].step = step;
  1259. pData->param.ranges[i].stepSmall = stepSmall;
  1260. pData->param.ranges[i].stepLarge = stepLarge;
  1261. fInputEvents.updatedParams[i].clapId = paramInfo.id;
  1262. fInputEvents.updatedParams[i].cookie = paramInfo.cookie;
  1263. }
  1264. if (needsCtrlIn)
  1265. {
  1266. portName.clear();
  1267. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1268. {
  1269. portName = pData->name;
  1270. portName += ":";
  1271. }
  1272. portName += "events-in";
  1273. portName.truncate(portNameSize);
  1274. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, 0);
  1275. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1276. pData->event.cvSourcePorts = pData->client->createCVSourcePorts();
  1277. #endif
  1278. if (mIns == 1)
  1279. fInputEvents.portData[0].port = pData->event.portIn;
  1280. }
  1281. if (needsCtrlOut)
  1282. {
  1283. portName.clear();
  1284. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1285. {
  1286. portName = pData->name;
  1287. portName += ":";
  1288. }
  1289. portName += "events-out";
  1290. portName.truncate(portNameSize);
  1291. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, 0);
  1292. if (mOuts == 1)
  1293. fOutputEvents.portData[0].port = pData->event.portOut;
  1294. }
  1295. // plugin hints
  1296. pData->hints = 0x0;
  1297. if (clapFeaturesContainInstrument(fPluginDescriptor->features))
  1298. pData->hints |= PLUGIN_IS_SYNTH;
  1299. #ifdef CLAP_WINDOW_API_NATIVE
  1300. if (guiExt != nullptr)
  1301. {
  1302. if (guiExt->is_api_supported(fPlugin, CLAP_WINDOW_API_NATIVE, false))
  1303. {
  1304. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  1305. pData->hints |= PLUGIN_HAS_CUSTOM_EMBED_UI;
  1306. pData->hints |= PLUGIN_NEEDS_UI_MAIN_THREAD;
  1307. }
  1308. else if (guiExt->is_api_supported(fPlugin, CLAP_WINDOW_API_NATIVE, true))
  1309. {
  1310. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  1311. pData->hints |= PLUGIN_NEEDS_UI_MAIN_THREAD;
  1312. }
  1313. }
  1314. #endif
  1315. if (aOuts > 0 && (aIns == aOuts || aIns == 1))
  1316. pData->hints |= PLUGIN_CAN_DRYWET;
  1317. if (aOuts > 0)
  1318. pData->hints |= PLUGIN_CAN_VOLUME;
  1319. if (aOuts >= 2 && aOuts % 2 == 0)
  1320. pData->hints |= PLUGIN_CAN_BALANCE;
  1321. // extra plugin hints
  1322. pData->extraHints = 0x0;
  1323. bufferSizeChanged(pData->engine->getBufferSize());
  1324. reloadPrograms(true);
  1325. if (pData->active)
  1326. activate();
  1327. else
  1328. runIdleCallbacksAsNeeded();
  1329. carla_debug("CarlaPluginCLAP::reload() - end");
  1330. }
  1331. void reloadPrograms(const bool doInit) override
  1332. {
  1333. carla_debug("CarlaPluginCLAP::reloadPrograms(%s)", bool2str(doInit));
  1334. }
  1335. // -------------------------------------------------------------------
  1336. // Plugin processing
  1337. void activate() noexcept override
  1338. {
  1339. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr,);
  1340. // FIXME check return status
  1341. fPlugin->activate(fPlugin, pData->engine->getSampleRate(), 1, pData->engine->getBufferSize());
  1342. fPlugin->start_processing(fPlugin);
  1343. runIdleCallbacksAsNeeded();
  1344. }
  1345. void deactivate() noexcept override
  1346. {
  1347. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr,);
  1348. // FIXME check return status
  1349. fPlugin->stop_processing(fPlugin);
  1350. fPlugin->deactivate(fPlugin);
  1351. runIdleCallbacksAsNeeded();
  1352. }
  1353. void process(const float* const* const audioIn,
  1354. float** const audioOut,
  1355. const float* const* const cvIn,
  1356. float** const,
  1357. const uint32_t frames) override
  1358. {
  1359. // --------------------------------------------------------------------------------------------------------
  1360. // Check if active
  1361. if (! pData->active)
  1362. {
  1363. // disable any output sound
  1364. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1365. carla_zeroFloats(audioOut[i], frames);
  1366. return;
  1367. }
  1368. // --------------------------------------------------------------------------------------------------------
  1369. // Check buffers
  1370. CARLA_SAFE_ASSERT_RETURN(frames > 0,);
  1371. if (pData->audioIn.count > 0)
  1372. {
  1373. CARLA_SAFE_ASSERT_RETURN(audioIn != nullptr,);
  1374. }
  1375. if (pData->audioOut.count > 0)
  1376. {
  1377. CARLA_SAFE_ASSERT_RETURN(audioOut != nullptr,);
  1378. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1379. CARLA_SAFE_ASSERT_RETURN(fAudioOutBuffers != nullptr,);
  1380. #endif
  1381. }
  1382. // --------------------------------------------------------------------------------------------------------
  1383. // Set audio buffers
  1384. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1385. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1386. carla_zeroFloats(fAudioOutBuffers[i], frames);
  1387. #endif
  1388. // --------------------------------------------------------------------------------------------------------
  1389. // Try lock, silence otherwise
  1390. if (pData->engine->isOffline())
  1391. {
  1392. pData->singleMutex.lock();
  1393. }
  1394. else if (! pData->singleMutex.tryLock())
  1395. {
  1396. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1397. carla_zeroFloats(audioOut[i], frames);
  1398. return;
  1399. }
  1400. // --------------------------------------------------------------------------------------------------------
  1401. fInputEvents.handleScheduledParameterUpdates();
  1402. // --------------------------------------------------------------------------------------------------------
  1403. // Check if needs reset
  1404. if (pData->needsReset)
  1405. {
  1406. // TODO alternative if plugin does not support CLAP_NOTE_DIALECT_MIDI
  1407. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1408. {
  1409. for (uint32_t p=0; p<fInputEvents.portCount; ++p)
  1410. {
  1411. const uint16_t port = fInputEvents.portData[p].clapPortIndex;
  1412. for (uint8_t i=0, k=fInputEvents.numEventsUsed; i < MAX_MIDI_CHANNELS; ++i)
  1413. {
  1414. fInputEvents.events[k + i].midi = {
  1415. { sizeof(clap_event_midi_t), 0, 0, CLAP_EVENT_MIDI, 0 },
  1416. port,
  1417. {
  1418. uint8_t(MIDI_STATUS_CONTROL_CHANGE | (i & MIDI_CHANNEL_BIT)),
  1419. MIDI_CONTROL_ALL_NOTES_OFF, 0
  1420. }
  1421. };
  1422. fInputEvents.events[k + MAX_MIDI_CHANNELS + i].midi = {
  1423. { sizeof(clap_event_midi_t), 0, 0, CLAP_EVENT_MIDI, 0 },
  1424. port,
  1425. {
  1426. uint8_t(MIDI_STATUS_CONTROL_CHANGE | (i & MIDI_CHANNEL_BIT)),
  1427. MIDI_CONTROL_ALL_SOUND_OFF, 0
  1428. }
  1429. };
  1430. }
  1431. fInputEvents.numEventsUsed += MAX_MIDI_CHANNELS * 2;
  1432. }
  1433. }
  1434. else if (pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  1435. {
  1436. for (uint32_t p=0; p<fInputEvents.portCount; ++p)
  1437. {
  1438. const uint16_t port = fInputEvents.portData[p].clapPortIndex;
  1439. for (uint8_t i=0, k=fInputEvents.numEventsUsed; i < MAX_MIDI_NOTE; ++i)
  1440. {
  1441. fInputEvents.events[k + i].midi = {
  1442. { sizeof(clap_event_midi_t), 0, 0, CLAP_EVENT_MIDI, 0 },
  1443. port,
  1444. {
  1445. uint8_t(MIDI_STATUS_NOTE_OFF | (pData->ctrlChannel & MIDI_CHANNEL_BIT)),
  1446. i, 0
  1447. }
  1448. };
  1449. }
  1450. fInputEvents.numEventsUsed += MAX_MIDI_NOTE;
  1451. }
  1452. }
  1453. pData->needsReset = false;
  1454. }
  1455. // --------------------------------------------------------------------------------------------------------
  1456. // Set TimeInfo
  1457. const EngineTimeInfo timeInfo(pData->engine->getTimeInfo());
  1458. clap_event_transport_t clapTransport = {
  1459. { sizeof(clap_event_transport_t), 0, 0, CLAP_EVENT_TRANSPORT, 0 },
  1460. 0x0, // flags
  1461. 0, // song_pos_beats, position in beats
  1462. 0, // song_pos_seconds, position in seconds
  1463. 0.0, // tempo, in bpm
  1464. 0.0, // tempo_inc, tempo increment for each samples and until the next time info event
  1465. 0, // loop_start_beats;
  1466. 0, // loop_end_beats;
  1467. 0, // loop_start_seconds;
  1468. 0, // loop_end_seconds;
  1469. 0, // bar_start, start pos of the current bar
  1470. 0, // bar_number, bar at song pos 0 has the number 0
  1471. 0, // tsig_num, time signature numerator
  1472. 0, // tsig_denom, time signature denominator
  1473. };
  1474. if (timeInfo.playing)
  1475. clapTransport.flags |= CLAP_TRANSPORT_IS_PLAYING;
  1476. // TODO song_pos_seconds (based on frame and sample rate)
  1477. if (timeInfo.bbt.valid)
  1478. {
  1479. // TODO song_pos_beats
  1480. // Tempo
  1481. clapTransport.tempo = timeInfo.bbt.beatsPerMinute;
  1482. clapTransport.flags |= CLAP_TRANSPORT_HAS_TEMPO;
  1483. // Bar
  1484. // TODO bar_start
  1485. clapTransport.bar_number = timeInfo.bbt.bar - 1;
  1486. // Time Signature
  1487. clapTransport.tsig_num = static_cast<uint16_t>(timeInfo.bbt.beatsPerBar + 0.5f);
  1488. clapTransport.tsig_denom = static_cast<uint16_t>(timeInfo.bbt.beatType + 0.5f);
  1489. clapTransport.flags |= CLAP_TRANSPORT_HAS_TIME_SIGNATURE;
  1490. }
  1491. else
  1492. {
  1493. // Tempo
  1494. clapTransport.tempo = 120.0;
  1495. clapTransport.flags |= CLAP_TRANSPORT_HAS_TEMPO;
  1496. // Time Signature
  1497. clapTransport.tsig_num = 4;
  1498. clapTransport.tsig_denom = 4;
  1499. clapTransport.flags |= CLAP_TRANSPORT_HAS_TIME_SIGNATURE;
  1500. }
  1501. // --------------------------------------------------------------------------------------------------------
  1502. // Event Input (main port)
  1503. if (pData->event.portIn != nullptr)
  1504. {
  1505. // ----------------------------------------------------------------------------------------------------
  1506. // MIDI Input (External)
  1507. if (pData->extNotes.mutex.tryLock())
  1508. {
  1509. if (fInputEvents.portCount == 0)
  1510. {
  1511. // does not handle MIDI
  1512. pData->extNotes.data.clear();
  1513. }
  1514. else
  1515. {
  1516. ExternalMidiNote note = { -1, 0, 0 };
  1517. const uint16_t p = fInputEvents.portData[0].clapPortIndex;
  1518. for (; fInputEvents.numEventsUsed < fInputEvents.numEventsAllocated && ! pData->extNotes.data.isEmpty();)
  1519. {
  1520. note = pData->extNotes.data.getFirst(note, true);
  1521. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  1522. if (fInputEvents.portData[0].supportedDialects & CLAP_NOTE_DIALECT_MIDI)
  1523. {
  1524. const uint8_t data[3] = {
  1525. uint8_t((note.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT)),
  1526. note.note,
  1527. note.velo
  1528. };
  1529. fInputEvents.addSimpleMidiEvent(true, p, 0, data);
  1530. }
  1531. else
  1532. {
  1533. fInputEvents.addSimpleNoteEvent(true, -1, 0, note.channel, note.note, note.velo);
  1534. }
  1535. }
  1536. }
  1537. pData->extNotes.mutex.unlock();
  1538. } // End of MIDI Input (External)
  1539. // ----------------------------------------------------------------------------------------------------
  1540. // Event Input (System)
  1541. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1542. bool allNotesOffSent = false;
  1543. #endif
  1544. uint32_t previousEventTime = 0;
  1545. uint32_t nextBankId;
  1546. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0)
  1547. nextBankId = pData->midiprog.data[pData->midiprog.current].bank;
  1548. else
  1549. nextBankId = 0;
  1550. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1551. if (cvIn != nullptr && pData->event.cvSourcePorts != nullptr)
  1552. pData->event.cvSourcePorts->initPortBuffers(cvIn + pData->cvIn.count, frames, true, pData->event.portIn);
  1553. #endif
  1554. const uint32_t numSysEvents = pData->event.portIn->getEventCount();
  1555. for (uint32_t i=0; i < numSysEvents; ++i)
  1556. {
  1557. EngineEvent& event(fInputEvents.defaultPort->port->getEvent(i));
  1558. uint32_t eventTime = event.time;
  1559. CARLA_SAFE_ASSERT_UINT2_CONTINUE(eventTime < frames, eventTime, frames);
  1560. if (eventTime < previousEventTime)
  1561. {
  1562. carla_stderr2("Timing error, eventTime:%u < previousEventTime:%u for '%s'",
  1563. eventTime, previousEventTime, pData->name);
  1564. eventTime = previousEventTime;
  1565. }
  1566. previousEventTime = eventTime;
  1567. switch (event.type)
  1568. {
  1569. case kEngineEventTypeNull:
  1570. break;
  1571. case kEngineEventTypeControl: {
  1572. EngineControlEvent& ctrlEvent(event.ctrl);
  1573. switch (ctrlEvent.type)
  1574. {
  1575. case kEngineControlEventTypeNull:
  1576. break;
  1577. case kEngineControlEventTypeParameter: {
  1578. float value;
  1579. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1580. // non-midi
  1581. if (event.channel == kEngineEventNonMidiChannel)
  1582. {
  1583. const uint32_t k = ctrlEvent.param;
  1584. CARLA_SAFE_ASSERT_CONTINUE(k < pData->param.count);
  1585. ctrlEvent.handled = true;
  1586. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  1587. setParameterValueRT(k, value, event.time, true);
  1588. continue;
  1589. }
  1590. // Control backend stuff
  1591. if (event.channel == pData->ctrlChannel)
  1592. {
  1593. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  1594. {
  1595. ctrlEvent.handled = true;
  1596. value = ctrlEvent.normalizedValue;
  1597. setDryWetRT(value, true);
  1598. }
  1599. else if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  1600. {
  1601. ctrlEvent.handled = true;
  1602. value = ctrlEvent.normalizedValue*127.0f/100.0f;
  1603. setVolumeRT(value, true);
  1604. }
  1605. else if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  1606. {
  1607. float left, right;
  1608. value = ctrlEvent.normalizedValue/0.5f - 1.0f;
  1609. if (value < 0.0f)
  1610. {
  1611. left = -1.0f;
  1612. right = (value*2.0f)+1.0f;
  1613. }
  1614. else if (value > 0.0f)
  1615. {
  1616. left = (value*2.0f)-1.0f;
  1617. right = 1.0f;
  1618. }
  1619. else
  1620. {
  1621. left = -1.0f;
  1622. right = 1.0f;
  1623. }
  1624. ctrlEvent.handled = true;
  1625. setBalanceLeftRT(left, true);
  1626. setBalanceRightRT(right, true);
  1627. }
  1628. }
  1629. #endif
  1630. // Control plugin parameters
  1631. uint32_t k;
  1632. for (k=0; k < pData->param.count; ++k)
  1633. {
  1634. if (pData->param.data[k].midiChannel != event.channel)
  1635. continue;
  1636. if (pData->param.data[k].mappedControlIndex != ctrlEvent.param)
  1637. continue;
  1638. if (pData->param.data[k].type != PARAMETER_INPUT)
  1639. continue;
  1640. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMATABLE) == 0)
  1641. continue;
  1642. ctrlEvent.handled = true;
  1643. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  1644. setParameterValueRT(k, value, event.time, true);
  1645. }
  1646. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param < MAX_MIDI_VALUE)
  1647. {
  1648. uint8_t midiData[3];
  1649. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1650. midiData[1] = uint8_t(ctrlEvent.param);
  1651. midiData[2] = uint8_t(ctrlEvent.normalizedValue*127.0f + 0.5f);
  1652. fInputEvents.addSimpleMidiEvent(true, 0, eventTime, midiData);
  1653. }
  1654. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1655. if (! ctrlEvent.handled)
  1656. checkForMidiLearn(event);
  1657. #endif
  1658. break;
  1659. } // case kEngineControlEventTypeParameter
  1660. case kEngineControlEventTypeMidiBank:
  1661. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  1662. {
  1663. if (event.channel == pData->ctrlChannel)
  1664. nextBankId = ctrlEvent.param;
  1665. }
  1666. else if (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES)
  1667. {
  1668. uint8_t midiData[3];
  1669. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1670. midiData[1] = MIDI_CONTROL_BANK_SELECT;
  1671. midiData[2] = uint8_t(ctrlEvent.param);
  1672. fInputEvents.addSimpleMidiEvent(true, 0, eventTime, midiData);
  1673. }
  1674. break;
  1675. case kEngineControlEventTypeMidiProgram:
  1676. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  1677. {
  1678. if (event.channel == pData->ctrlChannel)
  1679. {
  1680. const uint32_t nextProgramId(ctrlEvent.param);
  1681. for (uint32_t k=0; k < pData->midiprog.count; ++k)
  1682. {
  1683. if (pData->midiprog.data[k].bank == nextBankId && pData->midiprog.data[k].program == nextProgramId)
  1684. {
  1685. setMidiProgramRT(k, true);
  1686. break;
  1687. }
  1688. }
  1689. }
  1690. }
  1691. else if (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES)
  1692. {
  1693. uint8_t midiData[3];
  1694. midiData[0] = uint8_t(MIDI_STATUS_PROGRAM_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1695. midiData[1] = uint8_t(ctrlEvent.param);
  1696. midiData[2] = 0;
  1697. fInputEvents.addSimpleMidiEvent(true, 0, eventTime, midiData);
  1698. }
  1699. break;
  1700. case kEngineControlEventTypeAllSoundOff:
  1701. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1702. {
  1703. uint8_t midiData[3];
  1704. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1705. midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  1706. midiData[2] = 0;
  1707. fInputEvents.addSimpleMidiEvent(true, 0, eventTime, midiData);
  1708. }
  1709. break;
  1710. case kEngineControlEventTypeAllNotesOff:
  1711. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1712. {
  1713. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1714. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  1715. {
  1716. allNotesOffSent = true;
  1717. postponeRtAllNotesOff();
  1718. }
  1719. #endif
  1720. uint8_t midiData[3];
  1721. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1722. midiData[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  1723. midiData[2] = 0;
  1724. fInputEvents.addSimpleMidiEvent(true, 0, eventTime, midiData);
  1725. }
  1726. break;
  1727. } // switch (ctrlEvent.type)
  1728. break;
  1729. } // case kEngineEventTypeControl
  1730. case kEngineEventTypeMidi: {
  1731. const EngineMidiEvent& midiEvent(event.midi);
  1732. if (midiEvent.size > sizeof(clap_event_midi::data)/sizeof(clap_event_midi::data[0]))
  1733. continue;
  1734. CARLA_SAFE_ASSERT_BREAK(midiEvent.port < fInputEvents.portCount);
  1735. const uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiEvent.data));
  1736. if (status == MIDI_STATUS_NOTE_OFF || status == MIDI_STATUS_NOTE_ON)
  1737. {
  1738. if (pData->options & PLUGIN_OPTION_SKIP_SENDING_NOTES)
  1739. continue;
  1740. // plugin does not support MIDI, send a simple note instead
  1741. if ((fInputEvents.portData[midiEvent.port].supportedDialects & CLAP_NOTE_DIALECT_MIDI) == 0x0)
  1742. {
  1743. fInputEvents.addSimpleNoteEvent(true, midiEvent.port, event.time,
  1744. event.channel, midiEvent.data[1], midiEvent.data[2]);
  1745. }
  1746. }
  1747. if (fInputEvents.portData[midiEvent.port].supportedDialects & CLAP_NOTE_DIALECT_MIDI)
  1748. {
  1749. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  1750. continue;
  1751. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  1752. continue;
  1753. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  1754. continue;
  1755. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  1756. continue;
  1757. // put back channel in data
  1758. uint8_t midiData[3] = { uint8_t(status | (event.channel & MIDI_CHANNEL_BIT)), 0, 0 };
  1759. switch (midiEvent.size)
  1760. {
  1761. case 3:
  1762. midiData[2] = midiEvent.data[2];
  1763. // fall through
  1764. case 2:
  1765. midiData[1] = midiEvent.data[1];
  1766. break;
  1767. }
  1768. fInputEvents.addSimpleMidiEvent(true, midiEvent.port, eventTime, midiData);
  1769. }
  1770. switch (status)
  1771. {
  1772. case MIDI_STATUS_NOTE_ON:
  1773. if (midiEvent.data[2] != 0)
  1774. {
  1775. pData->postponeNoteOnRtEvent(true, event.channel, midiEvent.data[1], midiEvent.data[2]);
  1776. break;
  1777. }
  1778. // fall through
  1779. case MIDI_STATUS_NOTE_OFF:
  1780. pData->postponeNoteOffRtEvent(true, event.channel, midiEvent.data[1]);
  1781. break;
  1782. }
  1783. } break;
  1784. } // switch (event.type)
  1785. }
  1786. pData->postRtEvents.trySplice();
  1787. } // End of Event Input (main port)
  1788. // --------------------------------------------------------------------------------------------------------
  1789. // Event input (multi MIDI port)
  1790. if (fInputEvents.portCount > 1)
  1791. {
  1792. // TODO
  1793. }
  1794. // --------------------------------------------------------------------------------------------------------
  1795. // Plugin processing
  1796. for (uint32_t i=0; i<fInputAudioBuffers.count; ++i)
  1797. fInputAudioBuffers.buffers[i].data32 = audioIn + fInputAudioBuffers.buffers[i].offset;
  1798. for (uint32_t i=0; i<fOutputAudioBuffers.count; ++i)
  1799. {
  1800. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1801. fOutputAudioBuffers.buffers[i].data32 = fAudioOutBuffers + fOutputAudioBuffers.buffers[i].offset;
  1802. #else
  1803. fOutputAudioBuffers.buffers[i].data32 = audioOut + fOutputAudioBuffers.buffers[i].offset;
  1804. #endif
  1805. }
  1806. const clap_process_t process = {
  1807. static_cast<int64_t>(timeInfo.frame),
  1808. frames,
  1809. &clapTransport,
  1810. fInputAudioBuffers.cast(),
  1811. fOutputAudioBuffers.cast(), // audio_outputs
  1812. fInputAudioBuffers.count, // audio_inputs_count
  1813. fOutputAudioBuffers.count, // audio_outputs_count
  1814. fInputEvents.cast(),
  1815. fOutputEvents.cast()
  1816. };
  1817. fPlugin->process(fPlugin, &process);
  1818. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1819. // --------------------------------------------------------------------------------------------------------
  1820. // Post-processing (dry/wet, volume and balance)
  1821. {
  1822. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  1823. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  1824. const bool isMono = (pData->audioIn.count == 1);
  1825. bool isPair;
  1826. float bufValue, oldBufLeft[doBalance ? frames : 1];
  1827. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1828. {
  1829. // Dry/Wet
  1830. if (doDryWet)
  1831. {
  1832. const uint32_t c = isMono ? 0 : i;
  1833. for (uint32_t k=0; k < frames; ++k)
  1834. {
  1835. bufValue = audioIn[c][k];
  1836. fAudioOutBuffers[i][k] = (fAudioOutBuffers[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  1837. }
  1838. }
  1839. // Balance
  1840. if (doBalance)
  1841. {
  1842. isPair = (i % 2 == 0);
  1843. if (isPair)
  1844. {
  1845. CARLA_ASSERT(i+1 < pData->audioOut.count);
  1846. carla_copyFloats(oldBufLeft, fAudioOutBuffers[i], frames);
  1847. }
  1848. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  1849. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  1850. for (uint32_t k=0; k < frames; ++k)
  1851. {
  1852. if (isPair)
  1853. {
  1854. // left
  1855. fAudioOutBuffers[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  1856. fAudioOutBuffers[i][k] += fAudioOutBuffers[i+1][k] * (1.0f - balRangeR);
  1857. }
  1858. else
  1859. {
  1860. // right
  1861. fAudioOutBuffers[i][k] = fAudioOutBuffers[i][k] * balRangeR;
  1862. fAudioOutBuffers[i][k] += oldBufLeft[k] * balRangeL;
  1863. }
  1864. }
  1865. }
  1866. // Volume (and buffer copy)
  1867. {
  1868. for (uint32_t k=0; k < frames; ++k)
  1869. audioOut[i][k] = fAudioOutBuffers[i][k] * pData->postProc.volume;
  1870. }
  1871. }
  1872. } // End of Post-processing
  1873. #endif // BUILD_BRIDGE_ALTERNATIVE_ARCH
  1874. // --------------------------------------------------------------------------------------------------------
  1875. pData->singleMutex.unlock();
  1876. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1877. // --------------------------------------------------------------------------------------------------------
  1878. // Control Output
  1879. if (pData->event.portOut != nullptr && fExtensions.params != nullptr)
  1880. {
  1881. uint8_t channel;
  1882. uint16_t param;
  1883. double value;
  1884. for (uint32_t k=0; k < pData->param.count; ++k)
  1885. {
  1886. if (pData->param.data[k].type != PARAMETER_OUTPUT)
  1887. continue;
  1888. if (pData->param.data[k].mappedControlIndex <= 0)
  1889. continue;
  1890. if (!fExtensions.params->get_value(fPlugin, pData->param.data[k].rindex, &value))
  1891. continue;
  1892. channel = pData->param.data[k].midiChannel;
  1893. param = static_cast<uint16_t>(pData->param.data[k].mappedControlIndex);
  1894. value = pData->param.ranges[k].getNormalizedValue(value);
  1895. pData->event.portOut->writeControlEvent(0, channel,
  1896. kEngineControlEventTypeParameter, param, -1,
  1897. value);
  1898. }
  1899. } // End of Control Output
  1900. #endif
  1901. // --------------------------------------------------------------------------------------------------------
  1902. // Events/MIDI Output
  1903. for (uint32_t i=0; i<fOutputEvents.numEventsUsed; ++i)
  1904. {
  1905. const carla_clap_output_events::Event& ev(fOutputEvents.events[i]);
  1906. switch (ev.header.type)
  1907. {
  1908. case CLAP_EVENT_PARAM_VALUE:
  1909. for (uint32_t j=0; j<pData->param.count; ++j)
  1910. {
  1911. if (pData->param.data[j].rindex != static_cast<int32_t>(ev.param.param_id))
  1912. continue;
  1913. pData->postponeParameterChangeRtEvent(true, static_cast<int32_t>(j), ev.param.value);
  1914. break;
  1915. }
  1916. break;
  1917. case CLAP_EVENT_MIDI:
  1918. for (uint32_t j=0; j<fOutputEvents.portCount; ++j)
  1919. {
  1920. if (fOutputEvents.portData[j].clapPortIndex != ev.midi.port_index)
  1921. continue;
  1922. fOutputEvents.portData[j].port->writeMidiEvent(ev.midi.header.time, 3, ev.midi.data);
  1923. break;
  1924. }
  1925. break;
  1926. }
  1927. }
  1928. fOutputEvents.numEventsUsed = 0;
  1929. // --------------------------------------------------------------------------------------------------------
  1930. #ifdef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1931. return;
  1932. // unused
  1933. (void)cvIn;
  1934. #endif
  1935. }
  1936. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1937. void bufferSizeChanged(const uint32_t newBufferSize) override
  1938. {
  1939. CARLA_ASSERT_INT(newBufferSize > 0, newBufferSize);
  1940. carla_debug("CarlaPluginCLAP::bufferSizeChanged(%i)", newBufferSize);
  1941. if (pData->active)
  1942. deactivate();
  1943. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1944. {
  1945. if (fAudioOutBuffers[i] != nullptr)
  1946. delete[] fAudioOutBuffers[i];
  1947. fAudioOutBuffers[i] = new float[newBufferSize];
  1948. }
  1949. if (pData->active)
  1950. activate();
  1951. }
  1952. #endif
  1953. // -------------------------------------------------------------------
  1954. // Plugin buffers
  1955. void initBuffers() const noexcept override
  1956. {
  1957. fInputEvents.initBuffers();
  1958. fOutputEvents.initBuffers();
  1959. CarlaPlugin::initBuffers();
  1960. }
  1961. void clearBuffers() noexcept override
  1962. {
  1963. carla_debug("CarlaPluginCLAP::clearBuffers() - start");
  1964. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1965. if (fAudioOutBuffers != nullptr)
  1966. {
  1967. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1968. {
  1969. if (fAudioOutBuffers[i] != nullptr)
  1970. {
  1971. delete[] fAudioOutBuffers[i];
  1972. fAudioOutBuffers[i] = nullptr;
  1973. }
  1974. }
  1975. delete[] fAudioOutBuffers;
  1976. fAudioOutBuffers = nullptr;
  1977. }
  1978. #endif
  1979. fInputEvents.clear(pData->event.portIn);
  1980. fOutputEvents.clear(pData->event.portOut);
  1981. CarlaPlugin::clearBuffers();
  1982. carla_debug("CarlaPluginCLAP::clearBuffers() - end");
  1983. }
  1984. // -------------------------------------------------------------------
  1985. // Post-poned UI Stuff
  1986. // nothing
  1987. // -------------------------------------------------------------------
  1988. protected:
  1989. #ifdef CLAP_WINDOW_API_NATIVE
  1990. void handlePluginUIClosed() override
  1991. {
  1992. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  1993. carla_debug("CarlaPluginCLAP::handlePluginUIClosed()");
  1994. showCustomUI(false);
  1995. pData->engine->callback(true, true,
  1996. ENGINE_CALLBACK_UI_STATE_CHANGED,
  1997. pData->id,
  1998. 0,
  1999. 0, 0, 0.0f, nullptr);
  2000. }
  2001. void handlePluginUIResized(const uint width, const uint height) override
  2002. {
  2003. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  2004. carla_debug("CarlaPluginCLAP::handlePluginUIResized(%u, %u)", width, height);
  2005. if (fExtensions.gui != nullptr)
  2006. fExtensions.gui->set_size(fPlugin, width, height);
  2007. }
  2008. #endif
  2009. // -------------------------------------------------------------------
  2010. void clapRequestRestart() override
  2011. {
  2012. carla_stdout("CarlaPluginCLAP::clapRequestRestart()");
  2013. }
  2014. void clapRequestProcess() override
  2015. {
  2016. carla_stdout("CarlaPluginCLAP::clapRequestProcess()");
  2017. }
  2018. void clapRequestCallback() override
  2019. {
  2020. carla_stdout("CarlaPluginCLAP::clapRequestCallback()");
  2021. if (fPlugin->on_main_thread != nullptr)
  2022. fNeedsIdleCallback = true;
  2023. }
  2024. // -------------------------------------------------------------------
  2025. void clapMarkDirty() override
  2026. {
  2027. carla_stdout("CarlaPluginCLAP::clapMarkDirty()");
  2028. }
  2029. // -------------------------------------------------------------------
  2030. #ifdef CLAP_WINDOW_API_NATIVE
  2031. void clapGuiResizeHintsChanged() override
  2032. {
  2033. carla_stdout("CarlaPluginCLAP::clapGuiResizeHintsChanged()");
  2034. }
  2035. bool clapGuiRequestResize(const uint width, const uint height) override
  2036. {
  2037. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr, false);
  2038. carla_stdout("CarlaPluginCLAP::hostRequestResize(%u, %u)", width, height);
  2039. fUI.window->setSize(width, height, true);
  2040. return true;
  2041. }
  2042. bool clapGuiRequestShow() override
  2043. {
  2044. carla_stdout("CarlaPluginCLAP::clapGuiRequestShow()");
  2045. return false;
  2046. }
  2047. bool clapGuiRequestHide() override
  2048. {
  2049. carla_stdout("CarlaPluginCLAP::clapGuiRequestHide()");
  2050. return false;
  2051. }
  2052. void clapGuiClosed(const bool wasDestroyed) override
  2053. {
  2054. carla_stdout("CarlaPluginCLAP::clapGuiClosed(%s)", bool2str(wasDestroyed));
  2055. CARLA_SAFE_ASSERT_RETURN(!fUI.isEmbed,);
  2056. CARLA_SAFE_ASSERT_RETURN(fUI.isVisible,);
  2057. fUI.isVisible = false;
  2058. if (wasDestroyed)
  2059. {
  2060. CARLA_SAFE_ASSERT_RETURN(fUI.isCreated,);
  2061. fExtensions.gui->destroy(fPlugin);
  2062. fUI.isCreated = false;
  2063. }
  2064. pData->engine->callback(true, true,
  2065. ENGINE_CALLBACK_UI_STATE_CHANGED,
  2066. pData->id,
  2067. 0,
  2068. 0, 0, 0.0f, nullptr);
  2069. }
  2070. // -------------------------------------------------------------------
  2071. #ifdef _POSIX_VERSION
  2072. bool clapRegisterPosixFD(const int fd, const clap_posix_fd_flags_t flags) override
  2073. {
  2074. carla_stdout("CarlaPluginCLAP::clapRegisterPosixFD(%i, %x)", fd, flags);
  2075. // NOTE some plugins wont have their posix fd extension ready when first loaded, so try again here
  2076. if (fExtensions.posixFD == nullptr)
  2077. {
  2078. const clap_plugin_posix_fd_support_t* const posixFdExt = static_cast<const clap_plugin_posix_fd_support_t*>(
  2079. fPlugin->get_extension(fPlugin, CLAP_EXT_POSIX_FD_SUPPORT));
  2080. if (posixFdExt != nullptr && posixFdExt->on_fd != nullptr)
  2081. fExtensions.posixFD = posixFdExt;
  2082. }
  2083. CARLA_SAFE_ASSERT_RETURN(fExtensions.posixFD != nullptr, false);
  2084. // FIXME events only driven as long as UI is open
  2085. // CARLA_SAFE_ASSERT_RETURN(fUI.isCreated, false);
  2086. if (flags & (CLAP_POSIX_FD_READ|CLAP_POSIX_FD_WRITE))
  2087. {
  2088. const int epollfd = ::epoll_create1(0);
  2089. CARLA_SAFE_ASSERT_RETURN(epollfd >= 0, false);
  2090. epoll_event ev = {};
  2091. if (flags & CLAP_POSIX_FD_READ)
  2092. ev.events |= EPOLLIN;
  2093. if (flags & CLAP_POSIX_FD_WRITE)
  2094. ev.events |= EPOLLOUT;
  2095. ev.data.fd = fd;
  2096. if (::epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &ev) < 0)
  2097. {
  2098. ::close(epollfd);
  2099. return false;
  2100. }
  2101. const HostPosixFileDescriptorDetails posixFD = {
  2102. epollfd,
  2103. fd,
  2104. flags,
  2105. };
  2106. fPosixFileDescriptors.append(posixFD);
  2107. return true;
  2108. }
  2109. return false;
  2110. }
  2111. bool clapModifyPosixFD(const int fd, const clap_posix_fd_flags_t flags) override
  2112. {
  2113. carla_stdout("CarlaPluginCLAP::clapTimerUnregister(%i, %x)", fd, flags);
  2114. for (LinkedList<HostPosixFileDescriptorDetails>::Itenerator it = fPosixFileDescriptors.begin2(); it.valid(); it.next())
  2115. {
  2116. HostPosixFileDescriptorDetails& posixFD(it.getValue(kPosixFileDescriptorFallbackNC));
  2117. if (posixFD.pluginFd == fd)
  2118. {
  2119. if (posixFD.flags == flags)
  2120. return true;
  2121. epoll_event ev = {};
  2122. if (flags & CLAP_POSIX_FD_READ)
  2123. ev.events |= EPOLLIN;
  2124. if (flags & CLAP_POSIX_FD_WRITE)
  2125. ev.events |= EPOLLOUT;
  2126. ev.data.fd = fd;
  2127. if (::epoll_ctl(posixFD.hostFd, EPOLL_CTL_MOD, fd, &ev) < 0)
  2128. return false;
  2129. posixFD.flags = flags;
  2130. return true;
  2131. }
  2132. }
  2133. return false;
  2134. }
  2135. bool clapUnregisterPosixFD(const int fd) override
  2136. {
  2137. carla_stdout("CarlaPluginCLAP::clapTimerUnregister(%i)", fd);
  2138. for (LinkedList<HostPosixFileDescriptorDetails>::Itenerator it = fPosixFileDescriptors.begin2(); it.valid(); it.next())
  2139. {
  2140. const HostPosixFileDescriptorDetails& posixFD(it.getValue(kPosixFileDescriptorFallback));
  2141. if (posixFD.pluginFd == fd)
  2142. {
  2143. ::epoll_ctl(posixFD.hostFd, EPOLL_CTL_DEL, fd, nullptr);
  2144. ::close(posixFD.hostFd);
  2145. fPosixFileDescriptors.remove(it);
  2146. return true;
  2147. }
  2148. }
  2149. return false;
  2150. }
  2151. #endif
  2152. // -------------------------------------------------------------------
  2153. bool clapRegisterTimer(const uint32_t periodInMs, clap_id* const timerId) override
  2154. {
  2155. carla_stdout("CarlaPluginCLAP::clapTimerRegister(%u, %p)", periodInMs, timerId);
  2156. // NOTE some plugins wont have their timer extension ready when first loaded, so try again here
  2157. if (fExtensions.timer == nullptr)
  2158. {
  2159. const clap_plugin_timer_support_t* const timerExt = static_cast<const clap_plugin_timer_support_t*>(
  2160. fPlugin->get_extension(fPlugin, CLAP_EXT_TIMER_SUPPORT));
  2161. if (timerExt != nullptr && timerExt->on_timer != nullptr)
  2162. fExtensions.timer = timerExt;
  2163. }
  2164. CARLA_SAFE_ASSERT_RETURN(fExtensions.timer != nullptr, false);
  2165. // FIXME events only driven as long as UI is open
  2166. // CARLA_SAFE_ASSERT_RETURN(fUI.isCreated, false);
  2167. const HostTimerDetails timer = {
  2168. fTimers.isNotEmpty() ? fTimers.getLast(kTimerFallback).clapId + 1 : 1,
  2169. periodInMs,
  2170. 0
  2171. };
  2172. fTimers.append(timer);
  2173. *timerId = timer.clapId;
  2174. return true;
  2175. }
  2176. bool clapUnregisterTimer(const clap_id timerId) override
  2177. {
  2178. carla_stdout("CarlaPluginCLAP::clapTimerUnregister(%u)", timerId);
  2179. for (LinkedList<HostTimerDetails>::Itenerator it = fTimers.begin2(); it.valid(); it.next())
  2180. {
  2181. const HostTimerDetails& timer(it.getValue(kTimerFallback));
  2182. if (timer.clapId == timerId)
  2183. {
  2184. fTimers.remove(it);
  2185. return true;
  2186. }
  2187. }
  2188. return false;
  2189. }
  2190. #endif
  2191. // -------------------------------------------------------------------
  2192. public:
  2193. bool init(const CarlaPluginPtr plugin,
  2194. const char* const filename, const char* const name, const char* const id, const uint options)
  2195. {
  2196. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  2197. // ---------------------------------------------------------------
  2198. // first checks
  2199. if (pData->client != nullptr)
  2200. {
  2201. pData->engine->setLastError("Plugin client is already registered");
  2202. return false;
  2203. }
  2204. if (filename == nullptr || filename[0] == '\0')
  2205. {
  2206. pData->engine->setLastError("null filename");
  2207. return false;
  2208. }
  2209. // ---------------------------------------------------------------
  2210. const clap_plugin_entry_t* entry;
  2211. #ifdef CARLA_OS_MAC
  2212. if (!water::File(filename).existsAsFile())
  2213. {
  2214. if (! fBundleLoader.load(filename))
  2215. {
  2216. pData->engine->setLastError("Failed to load CLAP bundle executable");
  2217. return false;
  2218. }
  2219. entry = fBundleLoader.getSymbol<const clap_plugin_entry_t*>(CFSTR("clap_entry"));
  2220. }
  2221. else
  2222. #endif
  2223. {
  2224. if (! pData->libOpen(filename))
  2225. {
  2226. pData->engine->setLastError(pData->libError(filename));
  2227. return false;
  2228. }
  2229. entry = pData->libSymbol<const clap_plugin_entry_t*>("clap_entry");
  2230. }
  2231. if (entry == nullptr)
  2232. {
  2233. pData->engine->setLastError("Could not find the CLAP entry in the plugin library");
  2234. return false;
  2235. }
  2236. if (entry->init == nullptr || entry->deinit == nullptr || entry->get_factory == nullptr)
  2237. {
  2238. pData->engine->setLastError("CLAP factory entries are null");
  2239. return false;
  2240. }
  2241. if (!clap_version_is_compatible(entry->clap_version))
  2242. {
  2243. pData->engine->setLastError("Incompatible CLAP plugin");
  2244. return false;
  2245. }
  2246. // ---------------------------------------------------------------
  2247. const water::String pluginPath(water::File(filename).getParentDirectory().getFullPathName());
  2248. if (!entry->init(pluginPath.toRawUTF8()))
  2249. {
  2250. pData->engine->setLastError("Plugin entry failed to initialize");
  2251. return false;
  2252. }
  2253. fPluginEntry = entry;
  2254. // ---------------------------------------------------------------
  2255. const clap_plugin_factory_t* const factory = static_cast<const clap_plugin_factory_t*>(
  2256. entry->get_factory(CLAP_PLUGIN_FACTORY_ID));
  2257. if (factory == nullptr
  2258. || factory->get_plugin_count == nullptr
  2259. || factory->get_plugin_descriptor == nullptr
  2260. || factory->create_plugin == nullptr)
  2261. {
  2262. pData->engine->setLastError("Plugin is missing factory methods");
  2263. return false;
  2264. }
  2265. // ---------------------------------------------------------------
  2266. if (const uint32_t count = factory->get_plugin_count(factory))
  2267. {
  2268. // null id requested, use first available plugin
  2269. if (id == nullptr || id[0] == '\0')
  2270. {
  2271. fPluginDescriptor = factory->get_plugin_descriptor(factory, 0);
  2272. if (fPluginDescriptor == nullptr)
  2273. {
  2274. pData->engine->setLastError("Plugin library does not contain a valid first plugin");
  2275. return false;
  2276. }
  2277. }
  2278. else
  2279. {
  2280. for (uint32_t i=0; i<count; ++i)
  2281. {
  2282. const clap_plugin_descriptor_t* const desc = factory->get_plugin_descriptor(factory, i);
  2283. CARLA_SAFE_ASSERT_CONTINUE(desc != nullptr);
  2284. CARLA_SAFE_ASSERT_CONTINUE(desc->id != nullptr);
  2285. if (std::strcmp(desc->id, id) == 0)
  2286. {
  2287. fPluginDescriptor = desc;
  2288. break;
  2289. }
  2290. }
  2291. if (fPluginDescriptor == nullptr)
  2292. {
  2293. pData->engine->setLastError("Plugin library does not contain the requested plugin");
  2294. return false;
  2295. }
  2296. }
  2297. }
  2298. else
  2299. {
  2300. pData->engine->setLastError("Plugin library contains no plugins");
  2301. return false;
  2302. }
  2303. // ---------------------------------------------------------------
  2304. fPlugin = factory->create_plugin(factory, &fHost, fPluginDescriptor->id);
  2305. if (fPlugin == nullptr)
  2306. {
  2307. pData->engine->setLastError("Failed to create CLAP plugin instance");
  2308. return false;
  2309. }
  2310. if (!fPlugin->init(fPlugin))
  2311. {
  2312. pData->engine->setLastError("Failed to initialize CLAP plugin instance");
  2313. return false;
  2314. }
  2315. // ---------------------------------------------------------------
  2316. // get info
  2317. pData->name = pData->engine->getUniquePluginName(name != nullptr && name[0] != '\0' ? name
  2318. : fPluginDescriptor->name);
  2319. pData->filename = carla_strdup(filename);
  2320. // ---------------------------------------------------------------
  2321. // register client
  2322. pData->client = pData->engine->addClient(plugin);
  2323. if (pData->client == nullptr || ! pData->client->isOk())
  2324. {
  2325. pData->engine->setLastError("Failed to register plugin client");
  2326. return false;
  2327. }
  2328. // ---------------------------------------------------------------
  2329. // set default options
  2330. pData->options = PLUGIN_OPTION_FIXED_BUFFERS;
  2331. if (const clap_plugin_state_t* const stateExt =
  2332. static_cast<const clap_plugin_state_t*>(fPlugin->get_extension(fPlugin, CLAP_EXT_STATE)))
  2333. {
  2334. if (stateExt->save != nullptr && stateExt->load != nullptr)
  2335. if (isPluginOptionEnabled(options, PLUGIN_OPTION_USE_CHUNKS))
  2336. pData->options |= PLUGIN_OPTION_USE_CHUNKS;
  2337. }
  2338. if (const clap_plugin_note_ports_t* const notePortsExt =
  2339. static_cast<const clap_plugin_note_ports_t*>(fPlugin->get_extension(fPlugin, CLAP_EXT_NOTE_PORTS)))
  2340. {
  2341. const uint32_t numNoteInputPorts = notePortsExt->count != nullptr && notePortsExt->get != nullptr
  2342. ? notePortsExt->count(fPlugin, true) : 0;
  2343. for (uint32_t i=0; i<numNoteInputPorts; ++i)
  2344. {
  2345. clap_note_port_info_t portInfo = {};
  2346. CARLA_SAFE_ASSERT_BREAK(notePortsExt->get(fPlugin, i, true, &portInfo));
  2347. // TODO alternative if plugin does not support CLAP_NOTE_DIALECT_MIDI
  2348. if (portInfo.supported_dialects & CLAP_NOTE_DIALECT_MIDI)
  2349. {
  2350. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CONTROL_CHANGES))
  2351. pData->options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  2352. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CHANNEL_PRESSURE))
  2353. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  2354. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH))
  2355. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  2356. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PITCHBEND))
  2357. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  2358. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_ALL_SOUND_OFF))
  2359. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  2360. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PROGRAM_CHANGES))
  2361. pData->options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  2362. if (isPluginOptionInverseEnabled(options, PLUGIN_OPTION_SKIP_SENDING_NOTES))
  2363. pData->options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  2364. break;
  2365. }
  2366. }
  2367. }
  2368. // if (fEffect->numPrograms > 1 && (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) == 0)
  2369. // if (isPluginOptionEnabled(options, PLUGIN_OPTION_MAP_PROGRAM_CHANGES))
  2370. // pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  2371. return true;
  2372. }
  2373. private:
  2374. const clap_plugin_t* fPlugin;
  2375. const clap_plugin_descriptor_t* fPluginDescriptor;
  2376. const clap_plugin_entry_t* fPluginEntry;
  2377. const carla_clap_host fHost;
  2378. struct Extensions {
  2379. const clap_plugin_params_t* params;
  2380. #ifdef CLAP_WINDOW_API_NATIVE
  2381. const clap_plugin_gui_t* gui;
  2382. #endif
  2383. #ifdef _POSIX_VERSION
  2384. const clap_plugin_posix_fd_support_t* posixFD;
  2385. #endif
  2386. const clap_plugin_state_t* state;
  2387. const clap_plugin_timer_support_t* timer;
  2388. Extensions()
  2389. : params(nullptr),
  2390. #ifdef CLAP_WINDOW_API_NATIVE
  2391. gui(nullptr),
  2392. #endif
  2393. #ifdef _POSIX_VERSION
  2394. posixFD(nullptr),
  2395. #endif
  2396. state(nullptr),
  2397. timer(nullptr) {}
  2398. CARLA_DECLARE_NON_COPYABLE(Extensions)
  2399. } fExtensions;
  2400. #ifdef CLAP_WINDOW_API_NATIVE
  2401. struct UI {
  2402. bool initalized;
  2403. bool isCreated;
  2404. bool isEmbed;
  2405. bool isVisible;
  2406. CarlaPluginUI* window;
  2407. UI()
  2408. : initalized(false),
  2409. isCreated(false),
  2410. isEmbed(false),
  2411. isVisible(false),
  2412. window(nullptr) {}
  2413. ~UI()
  2414. {
  2415. CARLA_SAFE_ASSERT(window == nullptr);
  2416. }
  2417. } fUI;
  2418. #ifdef _POSIX_VERSION
  2419. LinkedList<HostPosixFileDescriptorDetails> fPosixFileDescriptors;
  2420. #endif
  2421. LinkedList<HostTimerDetails> fTimers;
  2422. #endif
  2423. carla_clap_input_audio_buffers fInputAudioBuffers;
  2424. carla_clap_output_audio_buffers fOutputAudioBuffers;
  2425. carla_clap_input_events fInputEvents;
  2426. carla_clap_output_events fOutputEvents;
  2427. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2428. float** fAudioOutBuffers;
  2429. #endif
  2430. void* fLastChunk;
  2431. bool fNeedsIdleCallback;
  2432. #ifdef CARLA_OS_MAC
  2433. BundleLoader fBundleLoader;
  2434. #endif
  2435. void runIdleCallbacksAsNeeded()
  2436. {
  2437. if (fNeedsIdleCallback)
  2438. {
  2439. fNeedsIdleCallback = false;
  2440. fPlugin->on_main_thread(fPlugin);
  2441. }
  2442. #ifdef CLAP_WINDOW_API_NATIVE
  2443. #ifdef _POSIX_VERSION
  2444. for (LinkedList<HostPosixFileDescriptorDetails>::Itenerator it = fPosixFileDescriptors.begin2(); it.valid(); it.next())
  2445. {
  2446. const HostPosixFileDescriptorDetails& posixFD(it.getValue(kPosixFileDescriptorFallback));
  2447. epoll_event events;
  2448. for (int i=0; i<50; ++i)
  2449. {
  2450. switch (::epoll_wait(posixFD.hostFd, &events, 1, 0))
  2451. {
  2452. case 1:
  2453. fExtensions.posixFD->on_fd(fPlugin, posixFD.pluginFd, posixFD.flags);
  2454. break;
  2455. case -1:
  2456. fExtensions.posixFD->on_fd(fPlugin, posixFD.pluginFd, posixFD.flags | CLAP_POSIX_FD_ERROR);
  2457. // fall through
  2458. case 0:
  2459. i = 50;
  2460. break;
  2461. }
  2462. }
  2463. }
  2464. #endif
  2465. const uint32_t currentTimeInMs = water::Time::getMillisecondCounter();
  2466. for (LinkedList<HostTimerDetails>::Itenerator it = fTimers.begin2(); it.valid(); it.next())
  2467. {
  2468. HostTimerDetails& timer(it.getValue(kTimerFallbackNC));
  2469. if (currentTimeInMs > timer.lastCallTimeInMs + timer.periodInMs)
  2470. {
  2471. timer.lastCallTimeInMs = currentTimeInMs;
  2472. fExtensions.timer->on_timer(fPlugin, timer.clapId);
  2473. }
  2474. }
  2475. #endif
  2476. }
  2477. };
  2478. // --------------------------------------------------------------------------------------------------------------------
  2479. CarlaPluginPtr CarlaPlugin::newCLAP(const Initializer& init)
  2480. {
  2481. carla_debug("CarlaPlugin::newCLAP({%p, \"%s\", \"%s\", \"%s\"})",
  2482. init.engine, init.filename, init.name, init.label);
  2483. std::shared_ptr<CarlaPluginCLAP> plugin(new CarlaPluginCLAP(init.engine, init.id));
  2484. if (! plugin->init(plugin, init.filename, init.name, init.label, init.options))
  2485. return nullptr;
  2486. return plugin;
  2487. }
  2488. // -------------------------------------------------------------------------------------------------------------------
  2489. CARLA_BACKEND_END_NAMESPACE