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.

3452 lines
118KB

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