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.

3418 lines
116KB

  1. /*
  2. * Carla CLAP Plugin
  3. * Copyright (C) 2022 Filipe Coelho <falktx@falktx.com>
  4. *
  5. * This program is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU General Public License as
  7. * published by the Free Software Foundation; either version 2 of
  8. * the License, or any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * For a full copy of the GNU General Public License see the doc/GPL.txt file.
  16. */
  17. #include "CarlaPluginInternal.hpp"
  18. #include "CarlaEngine.hpp"
  19. #include "CarlaBackendUtils.hpp"
  20. #include "CarlaClapUtils.hpp"
  21. #include "CarlaMathUtils.hpp"
  22. #include "CarlaPluginUI.hpp"
  23. #ifdef CARLA_OS_MAC
  24. # include "CarlaMacUtils.hpp"
  25. # import <Foundation/Foundation.h>
  26. #endif
  27. #include "water/files/File.h"
  28. #include "water/misc/Time.h"
  29. #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 CLAP_ABI const void* 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 CLAP_ABI void 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 CLAP_ABI void 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 CLAP_ABI void 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 CLAP_ABI void 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 CLAP_ABI void 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 CLAP_ABI void 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 CLAP_ABI bool 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 CLAP_ABI bool 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 CLAP_ABI bool 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 CLAP_ABI void 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 CLAP_ABI bool 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 CLAP_ABI bool 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 CLAP_ABI bool 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 CLAP_ABI bool 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 CLAP_ABI bool 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 CLAP_ABI uint32_t 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 CLAP_ABI const clap_event_header_t* 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 CLAP_ABI bool 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. return true;
  799. }
  800. bool getParameterSymbol(const uint32_t parameterId, char* const strBuf) const noexcept override
  801. {
  802. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  803. const clap_id clapId = pData->param.data[parameterId].rindex;
  804. std::snprintf(strBuf, STR_MAX, "%u", clapId);
  805. return true;
  806. }
  807. bool getParameterText(const uint32_t parameterId, char* const strBuf) noexcept override
  808. {
  809. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr, false);
  810. CARLA_SAFE_ASSERT_RETURN(fExtensions.params != nullptr, false);
  811. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  812. const clap_id clapId = pData->param.data[parameterId].rindex;
  813. const double value = getBestParameterValue(parameterId, clapId);
  814. return fExtensions.params->value_to_text(fPlugin, clapId, value, strBuf, STR_MAX);
  815. }
  816. bool getParameterGroupName(const uint32_t parameterId, char* const strBuf) const noexcept override
  817. {
  818. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr, false);
  819. CARLA_SAFE_ASSERT_RETURN(fExtensions.params != nullptr, false);
  820. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  821. clap_param_info_t paramInfo = {};
  822. CARLA_SAFE_ASSERT_RETURN(fExtensions.params->get_info(fPlugin, parameterId, &paramInfo), false);
  823. if (paramInfo.module[0] == '\0')
  824. return false;
  825. if (char* const sep = std::strrchr(paramInfo.module, '/'))
  826. {
  827. paramInfo.module[STR_MAX/2-2] = sep[0] = '\0';
  828. std::snprintf(strBuf, STR_MAX, "%s:%s", paramInfo.module, paramInfo.module);
  829. return true;
  830. }
  831. return false;
  832. }
  833. // -------------------------------------------------------------------
  834. // Set data (state)
  835. // nothing
  836. // -------------------------------------------------------------------
  837. // Set data (internal stuff)
  838. #ifdef CLAP_WINDOW_API_NATIVE
  839. void setName(const char* const newName) override
  840. {
  841. CarlaPlugin::setName(newName);
  842. if (fUI.isCreated && pData->uiTitle.isEmpty())
  843. setWindowTitle(nullptr);
  844. }
  845. #endif
  846. // -------------------------------------------------------------------
  847. // Set data (plugin-specific stuff)
  848. void setParameterValue(const uint32_t parameterId, const float value, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  849. {
  850. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr,);
  851. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  852. const float fixedValue = pData->param.getFixedValue(parameterId, value);
  853. fInputEvents.setParamValue(parameterId, fixedValue);
  854. if (!pData->active && fExtensions.params->flush != nullptr)
  855. fNeedsParamFlush = true;
  856. CarlaPlugin::setParameterValue(parameterId, fixedValue, sendGui, sendOsc, sendCallback);
  857. }
  858. void setParameterValueRT(const uint32_t parameterId, const float value, const uint32_t frameOffset, const bool sendCallbackLater) noexcept override
  859. {
  860. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr,);
  861. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  862. const float fixedValue = pData->param.getFixedValue(parameterId, value);
  863. fInputEvents.setParamValueRT(parameterId, fixedValue, frameOffset);
  864. CarlaPlugin::setParameterValueRT(parameterId, fixedValue, frameOffset, sendCallbackLater);
  865. }
  866. void setChunkData(const void* const data, const std::size_t dataSize) override
  867. {
  868. CARLA_SAFE_ASSERT_RETURN(pData->options & PLUGIN_OPTION_USE_CHUNKS,);
  869. CARLA_SAFE_ASSERT_RETURN(fExtensions.state != nullptr,);
  870. CARLA_SAFE_ASSERT_RETURN(data != nullptr,);
  871. CARLA_SAFE_ASSERT_RETURN(dataSize > 0,);
  872. const clap_istream_impl stream(data, dataSize);
  873. if (fExtensions.state->load(fPlugin, &stream))
  874. pData->updateParameterValues(this, true, true, false);
  875. runIdleCallbacksAsNeeded(false);
  876. }
  877. // -------------------------------------------------------------------
  878. // Set ui stuff
  879. #ifdef CLAP_WINDOW_API_NATIVE
  880. void setWindowTitle(const char* const title) noexcept
  881. {
  882. if (!fUI.isCreated)
  883. return;
  884. CarlaString uiTitle;
  885. if (title != nullptr)
  886. {
  887. uiTitle = title;
  888. }
  889. else
  890. {
  891. uiTitle = pData->name;
  892. uiTitle += " (GUI)";
  893. }
  894. if (fUI.isEmbed)
  895. {
  896. if (fUI.window != nullptr)
  897. fUI.window->setTitle(uiTitle.buffer());
  898. }
  899. else
  900. {
  901. fExtensions.gui->suggest_title(fPlugin, uiTitle.buffer());
  902. }
  903. }
  904. void setCustomUITitle(const char* const title) noexcept override
  905. {
  906. setWindowTitle(title);
  907. CarlaPlugin::setCustomUITitle(title);
  908. }
  909. void showCustomUI(const bool yesNo) override
  910. {
  911. CARLA_SAFE_ASSERT_RETURN(fExtensions.gui != nullptr,);
  912. if (yesNo)
  913. {
  914. if (fUI.isVisible)
  915. {
  916. fExtensions.gui->show(fPlugin);
  917. if (fUI.isEmbed)
  918. {
  919. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  920. fUI.window->show();
  921. fUI.window->focus();
  922. }
  923. runIdleCallbacksAsNeeded(false);
  924. return;
  925. }
  926. if (!fUI.initalized)
  927. {
  928. fUI.isEmbed = fExtensions.gui->is_api_supported(fPlugin, CLAP_WINDOW_API_NATIVE, false);
  929. fUI.initalized = true;
  930. }
  931. if (!fUI.isCreated)
  932. {
  933. if (!fExtensions.gui->create(fPlugin, CLAP_WINDOW_API_NATIVE, !fUI.isEmbed))
  934. {
  935. pData->engine->callback(true, true,
  936. ENGINE_CALLBACK_UI_STATE_CHANGED,
  937. pData->id,
  938. -1,
  939. 0, 0, 0.0f,
  940. "Plugin refused to open its own UI");
  941. return;
  942. }
  943. fUI.isCreated = true;
  944. }
  945. const bool resizable = fExtensions.gui->can_resize(fPlugin);
  946. const EngineOptions& opts(pData->engine->getOptions());
  947. #if defined(CARLA_OS_WIN)
  948. fUI.window = CarlaPluginUI::newWindows(this, opts.frontendWinId, opts.pluginsAreStandalone, resizable);
  949. #elif defined(CARLA_OS_MAC)
  950. fUI.window = CarlaPluginUI::newCocoa(this, opts.frontendWinId, opts.pluginsAreStandalone, resizable);
  951. #elif defined(HAVE_X11)
  952. fUI.window = CarlaPluginUI::newX11(this, opts.frontendWinId, opts.pluginsAreStandalone, resizable, false);
  953. #else
  954. #error why is CLAP_WINDOW_API_NATIVE defined??
  955. #endif
  956. #ifndef CARLA_OS_MAC
  957. if (carla_isNotZero(opts.uiScale))
  958. fExtensions.gui->set_scale(fPlugin, opts.uiScale);
  959. #endif
  960. setWindowTitle(nullptr);
  961. if (fUI.isEmbed)
  962. {
  963. clap_window_t win = { CLAP_WINDOW_API_NATIVE, {} };
  964. win.ptr = fUI.window->getPtr();
  965. fExtensions.gui->set_parent(fPlugin, &win);
  966. uint32_t width, height;
  967. if (fExtensions.gui->get_size(fPlugin, &width, &height))
  968. {
  969. fUI.isResizingFromInit = true;
  970. fUI.width = width;
  971. fUI.height = height;
  972. fUI.window->setSize(width, height, true, true);
  973. }
  974. fExtensions.gui->show(fPlugin);
  975. fUI.window->show();
  976. }
  977. else
  978. {
  979. clap_window_t win = { CLAP_WINDOW_API_NATIVE, {} };
  980. win.uptr = opts.frontendWinId;
  981. fExtensions.gui->set_transient(fPlugin, &win);
  982. fExtensions.gui->show(fPlugin);
  983. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  984. pData->tryTransient();
  985. #endif
  986. }
  987. fUI.isVisible = true;
  988. }
  989. else
  990. {
  991. fUI.isVisible = false;
  992. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  993. pData->transientTryCounter = 0;
  994. #endif
  995. if (fUI.window != nullptr)
  996. fUI.window->hide();
  997. fExtensions.gui->hide(fPlugin);
  998. if (fUI.isCreated)
  999. {
  1000. fExtensions.gui->destroy(fPlugin);
  1001. fUI.isCreated = false;
  1002. }
  1003. if (fUI.window != nullptr)
  1004. {
  1005. delete fUI.window;
  1006. fUI.window = nullptr;
  1007. }
  1008. }
  1009. runIdleCallbacksAsNeeded(false);
  1010. }
  1011. void* embedCustomUI(void* const ptr) override
  1012. {
  1013. CARLA_SAFE_ASSERT_RETURN(fUI.window == nullptr, nullptr);
  1014. if (!fUI.initalized)
  1015. {
  1016. fUI.isEmbed = fExtensions.gui->is_api_supported(fPlugin, CLAP_WINDOW_API_NATIVE, false);
  1017. fUI.initalized = true;
  1018. }
  1019. if (!fUI.isCreated)
  1020. {
  1021. if (!fExtensions.gui->create(fPlugin, CLAP_WINDOW_API_NATIVE, false))
  1022. {
  1023. pData->engine->callback(true, true,
  1024. ENGINE_CALLBACK_UI_STATE_CHANGED,
  1025. pData->id,
  1026. -1,
  1027. 0, 0, 0.0f,
  1028. "Plugin refused to open its own UI");
  1029. return nullptr;
  1030. }
  1031. fUI.isCreated = true;
  1032. }
  1033. fUI.isVisible = true;
  1034. #ifndef CARLA_OS_MAC
  1035. const EngineOptions& opts(pData->engine->getOptions());
  1036. if (carla_isNotZero(opts.uiScale))
  1037. fExtensions.gui->set_scale(fPlugin, opts.uiScale);
  1038. #endif
  1039. clap_window_t win = { CLAP_WINDOW_API_NATIVE, {} };
  1040. win.ptr = ptr;
  1041. fExtensions.gui->set_parent(fPlugin, &win);
  1042. uint32_t width, height;
  1043. if (fExtensions.gui->get_size(fPlugin, &width, &height))
  1044. {
  1045. fUI.isResizingFromInit = true;
  1046. fUI.width = width;
  1047. fUI.height = height;
  1048. pData->engine->callback(true, true,
  1049. ENGINE_CALLBACK_EMBED_UI_RESIZED,
  1050. pData->id, width, height,
  1051. 0, 0.0f, nullptr);
  1052. }
  1053. fExtensions.gui->show(fPlugin);
  1054. return nullptr;
  1055. }
  1056. #endif
  1057. void idle() override
  1058. {
  1059. if (kEngineHasIdleOnMainThread)
  1060. runIdleCallbacksAsNeeded(true);
  1061. CarlaPlugin::idle();
  1062. }
  1063. void uiIdle() override
  1064. {
  1065. #ifdef CLAP_WINDOW_API_NATIVE
  1066. if (fUI.shouldClose)
  1067. {
  1068. fUI.shouldClose = false;
  1069. fUI.isResizingFromHost = fUI.isResizingFromInit = false;
  1070. fUI.isResizingFromPlugin = 0;
  1071. showCustomUI(false);
  1072. pData->engine->callback(true, true,
  1073. ENGINE_CALLBACK_UI_STATE_CHANGED,
  1074. pData->id,
  1075. 0,
  1076. 0, 0, 0.0f, nullptr);
  1077. }
  1078. if (fUI.isResizingFromHost)
  1079. {
  1080. fUI.isResizingFromHost = false;
  1081. if (fUI.isResizingFromPlugin == 0 && !fUI.isResizingFromInit == false)
  1082. {
  1083. carla_stdout("Host resize restarted");
  1084. fExtensions.gui->set_size(fPlugin, fUI.width, fUI.height);
  1085. }
  1086. }
  1087. if (fUI.window != nullptr)
  1088. fUI.window->idle();
  1089. if (fUI.isResizingFromPlugin == 2)
  1090. {
  1091. fUI.isResizingFromPlugin = 1;
  1092. }
  1093. else if (fUI.isResizingFromPlugin == 1)
  1094. {
  1095. fUI.isResizingFromPlugin = 0;
  1096. carla_stdout("Plugin resize stopped");
  1097. }
  1098. #endif
  1099. if (!kEngineHasIdleOnMainThread)
  1100. runIdleCallbacksAsNeeded(true);
  1101. CarlaPlugin::uiIdle();
  1102. }
  1103. // -------------------------------------------------------------------
  1104. // Plugin state
  1105. void reload() override
  1106. {
  1107. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  1108. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr,);
  1109. carla_debug("CarlaPluginCLAP::reload() - start");
  1110. // Safely disable plugin for reload
  1111. const ScopedDisabler sd(this);
  1112. if (pData->active)
  1113. deactivate();
  1114. clearBuffers();
  1115. const clap_plugin_audio_ports_t* audioPortsExt = static_cast<const clap_plugin_audio_ports_t*>(
  1116. fPlugin->get_extension(fPlugin, CLAP_EXT_AUDIO_PORTS));
  1117. const clap_plugin_latency_t* latencyExt = static_cast<const clap_plugin_latency_t*>(
  1118. fPlugin->get_extension(fPlugin, CLAP_EXT_LATENCY));
  1119. const clap_plugin_note_ports_t* notePortsExt = static_cast<const clap_plugin_note_ports_t*>(
  1120. fPlugin->get_extension(fPlugin, CLAP_EXT_NOTE_PORTS));
  1121. const clap_plugin_params_t* paramsExt = static_cast<const clap_plugin_params_t*>(
  1122. fPlugin->get_extension(fPlugin, CLAP_EXT_PARAMS));
  1123. const clap_plugin_state_t* stateExt = static_cast<const clap_plugin_state_t*>(
  1124. fPlugin->get_extension(fPlugin, CLAP_EXT_STATE));
  1125. const clap_plugin_timer_support_t* timerExt = static_cast<const clap_plugin_timer_support_t*>(
  1126. fPlugin->get_extension(fPlugin, CLAP_EXT_TIMER_SUPPORT));
  1127. if (audioPortsExt != nullptr && (audioPortsExt->count == nullptr || audioPortsExt->get == nullptr))
  1128. audioPortsExt = nullptr;
  1129. if (latencyExt != nullptr && latencyExt->get == nullptr)
  1130. latencyExt = nullptr;
  1131. if (notePortsExt != nullptr && (notePortsExt->count == nullptr || notePortsExt->get == nullptr))
  1132. notePortsExt = nullptr;
  1133. if (paramsExt != nullptr && (paramsExt->count == nullptr || paramsExt->get_info == nullptr))
  1134. paramsExt = nullptr;
  1135. if (stateExt != nullptr && (stateExt->save == nullptr || stateExt->load == nullptr))
  1136. stateExt = nullptr;
  1137. if (timerExt != nullptr && timerExt->on_timer == nullptr)
  1138. timerExt = nullptr;
  1139. fExtensions.latency = latencyExt;
  1140. fExtensions.params = paramsExt;
  1141. fExtensions.state = stateExt;
  1142. fExtensions.timer = timerExt;
  1143. #ifdef CLAP_WINDOW_API_NATIVE
  1144. const clap_plugin_gui_t* guiExt = static_cast<const clap_plugin_gui_t*>(
  1145. fPlugin->get_extension(fPlugin, CLAP_EXT_GUI));
  1146. if (guiExt != nullptr && (guiExt->is_api_supported == nullptr
  1147. || guiExt->create == nullptr
  1148. || guiExt->destroy == nullptr
  1149. || guiExt->set_scale == nullptr
  1150. || guiExt->get_size == nullptr
  1151. || guiExt->can_resize == nullptr
  1152. || guiExt->get_resize_hints == nullptr
  1153. || guiExt->adjust_size == nullptr
  1154. || guiExt->set_size == nullptr
  1155. || guiExt->set_parent == nullptr
  1156. || guiExt->set_transient == nullptr
  1157. || guiExt->suggest_title == nullptr
  1158. || guiExt->show == nullptr
  1159. || guiExt->hide == nullptr))
  1160. guiExt = nullptr;
  1161. fExtensions.gui = guiExt;
  1162. #endif
  1163. #if defined(CLAP_WINDOW_API_NATIVE) && defined(_POSIX_VERSION)
  1164. const clap_plugin_posix_fd_support_t* posixFdExt = static_cast<const clap_plugin_posix_fd_support_t*>(
  1165. fPlugin->get_extension(fPlugin, CLAP_EXT_POSIX_FD_SUPPORT));
  1166. if (posixFdExt != nullptr && posixFdExt->on_fd == nullptr)
  1167. posixFdExt = nullptr;
  1168. fExtensions.posixFD = posixFdExt;
  1169. #endif
  1170. const uint32_t numAudioInputPorts = audioPortsExt != nullptr ? audioPortsExt->count(fPlugin, true) : 0;
  1171. const uint32_t numAudioOutputPorts = audioPortsExt != nullptr ? audioPortsExt->count(fPlugin, false) : 0;
  1172. const uint32_t numNoteInputPorts = notePortsExt != nullptr ? notePortsExt->count(fPlugin, true) : 0;
  1173. const uint32_t numNoteOutputPorts = notePortsExt != nullptr ? notePortsExt->count(fPlugin, false) : 0;
  1174. const uint32_t numParameters = paramsExt != nullptr ? paramsExt->count(fPlugin) : 0;
  1175. uint32_t aIns, aOuts, mIns, mOuts, params;
  1176. aIns = aOuts = mIns = mOuts = params = 0;
  1177. bool needsCtrlIn, needsCtrlOut;
  1178. needsCtrlIn = needsCtrlOut = false;
  1179. fInputAudioBuffers.realloc(numAudioInputPorts);
  1180. fOutputAudioBuffers.realloc(numAudioOutputPorts);
  1181. for (uint32_t i=0; i<numAudioInputPorts; ++i)
  1182. {
  1183. clap_audio_port_info_t portInfo = {};
  1184. CARLA_SAFE_ASSERT_BREAK(audioPortsExt->get(fPlugin, i, true, &portInfo));
  1185. CARLA_SAFE_ASSERT(portInfo.channel_count != 0);
  1186. fInputAudioBuffers.buffers[i].channel_count = portInfo.channel_count;
  1187. fInputAudioBuffers.extra[i].offset = aIns;
  1188. fInputAudioBuffers.extra[i].isMain = portInfo.flags & CLAP_AUDIO_PORT_IS_MAIN;
  1189. aIns += portInfo.channel_count;
  1190. }
  1191. for (uint32_t i=0; i<numAudioOutputPorts; ++i)
  1192. {
  1193. clap_audio_port_info_t portInfo = {};
  1194. CARLA_SAFE_ASSERT_BREAK(audioPortsExt->get(fPlugin, i, false, &portInfo));
  1195. CARLA_SAFE_ASSERT(portInfo.channel_count != 0);
  1196. fOutputAudioBuffers.buffers[i].channel_count = portInfo.channel_count;
  1197. fOutputAudioBuffers.extra[i].offset = aOuts;
  1198. fOutputAudioBuffers.extra[i].isMain = portInfo.flags & CLAP_AUDIO_PORT_IS_MAIN;
  1199. for (uint32_t j=0; j<portInfo.channel_count; ++j)
  1200. fOutputAudioBuffers.buffers[i].constant_mask |= (1 << j);
  1201. aOuts += portInfo.channel_count;
  1202. }
  1203. for (uint32_t i=0; i<numNoteInputPorts; ++i)
  1204. {
  1205. clap_note_port_info_t portInfo = {};
  1206. CARLA_SAFE_ASSERT_BREAK(notePortsExt->get(fPlugin, i, true, &portInfo));
  1207. if (portInfo.supported_dialects & (CLAP_NOTE_DIALECT_CLAP|CLAP_NOTE_DIALECT_MIDI))
  1208. ++mIns;
  1209. }
  1210. for (uint32_t i=0; i<numNoteOutputPorts; ++i)
  1211. {
  1212. clap_note_port_info_t portInfo = {};
  1213. CARLA_SAFE_ASSERT_BREAK(notePortsExt->get(fPlugin, i, false, &portInfo));
  1214. if (portInfo.supported_dialects & CLAP_NOTE_DIALECT_MIDI)
  1215. ++mOuts;
  1216. }
  1217. for (uint32_t i=0; i<numParameters; ++i, ++params)
  1218. {
  1219. clap_param_info_t paramInfo = {};
  1220. CARLA_SAFE_ASSERT_BREAK(paramsExt->get_info(fPlugin, i, &paramInfo));
  1221. }
  1222. if (aIns > 0)
  1223. {
  1224. pData->audioIn.createNew(aIns);
  1225. }
  1226. if (aOuts > 0)
  1227. {
  1228. pData->audioOut.createNew(aOuts);
  1229. needsCtrlIn = true;
  1230. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1231. fAudioOutBuffers = new float*[aOuts];
  1232. for (uint32_t i=0; i < aOuts; ++i)
  1233. fAudioOutBuffers[i] = nullptr;
  1234. #endif
  1235. }
  1236. if (mIns == 1)
  1237. needsCtrlIn = true;
  1238. if (mOuts == 1)
  1239. needsCtrlOut = true;
  1240. if (params > 0)
  1241. {
  1242. pData->param.createNew(params, false);
  1243. needsCtrlIn = true;
  1244. }
  1245. fInputEvents.realloc(pData->event.portIn, mIns, params);
  1246. fOutputEvents.realloc(pData->event.portOut, mOuts, params);
  1247. const EngineProcessMode processMode = pData->engine->getProccessMode();
  1248. const uint portNameSize = pData->engine->getMaxPortNameSize();
  1249. CarlaString portName;
  1250. // Audio Ins
  1251. for (uint32_t j=0; j < aIns; ++j)
  1252. {
  1253. portName.clear();
  1254. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1255. {
  1256. portName = pData->name;
  1257. portName += ":";
  1258. }
  1259. if (aIns > 1)
  1260. {
  1261. portName += "input_";
  1262. portName += CarlaString(j+1);
  1263. }
  1264. else
  1265. portName += "input";
  1266. portName.truncate(portNameSize);
  1267. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true, j);
  1268. pData->audioIn.ports[j].rindex = j;
  1269. }
  1270. // Audio Outs
  1271. for (uint32_t j=0; j < aOuts; ++j)
  1272. {
  1273. portName.clear();
  1274. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1275. {
  1276. portName = pData->name;
  1277. portName += ":";
  1278. }
  1279. if (aOuts > 1)
  1280. {
  1281. portName += "output_";
  1282. portName += CarlaString(j+1);
  1283. }
  1284. else
  1285. portName += "output";
  1286. portName.truncate(portNameSize);
  1287. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, j);
  1288. pData->audioOut.ports[j].rindex = j;
  1289. }
  1290. // MIDI Ins
  1291. for (uint32_t i=0, j=0; i<numNoteInputPorts; ++i)
  1292. {
  1293. clap_note_port_info_t portInfo = {};
  1294. CARLA_SAFE_ASSERT_BREAK(notePortsExt->get(fPlugin, i, true, &portInfo));
  1295. if ((portInfo.supported_dialects & (CLAP_NOTE_DIALECT_CLAP|CLAP_NOTE_DIALECT_MIDI)) == 0x0)
  1296. continue;
  1297. CARLA_SAFE_ASSERT_UINT2_BREAK(j < mIns, j, mIns);
  1298. fInputEvents.portData[j].clapPortIndex = i;
  1299. fInputEvents.portData[j].supportedDialects = portInfo.supported_dialects;
  1300. if (mIns > 1)
  1301. {
  1302. portName.clear();
  1303. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1304. {
  1305. portName = pData->name;
  1306. portName += ":";
  1307. }
  1308. portName += portInfo.name;
  1309. portName.truncate(portNameSize);
  1310. fInputEvents.portData[j].port = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, j);
  1311. }
  1312. else
  1313. {
  1314. fInputEvents.portData[j].port = nullptr;
  1315. fInputEvents.defaultPort = &fInputEvents.portData[0];
  1316. }
  1317. ++j;
  1318. }
  1319. // MIDI Outs
  1320. for (uint32_t i=0, j=0; i<numNoteOutputPorts; ++i)
  1321. {
  1322. clap_note_port_info_t portInfo = {};
  1323. CARLA_SAFE_ASSERT_BREAK(notePortsExt->get(fPlugin, i, false, &portInfo));
  1324. if ((portInfo.supported_dialects & CLAP_NOTE_DIALECT_MIDI) == 0x0)
  1325. continue;
  1326. CARLA_SAFE_ASSERT_UINT2_BREAK(j < mOuts, j, mOuts);
  1327. fOutputEvents.portData[j].clapPortIndex = i;
  1328. fOutputEvents.portData[j].supportedDialects = portInfo.supported_dialects;
  1329. if (mOuts > 1)
  1330. {
  1331. portName.clear();
  1332. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1333. {
  1334. portName = pData->name;
  1335. portName += ":";
  1336. }
  1337. portName += portInfo.name;
  1338. portName.truncate(portNameSize);
  1339. fOutputEvents.portData[j].port = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, j);
  1340. }
  1341. else
  1342. {
  1343. fOutputEvents.portData[j].port = nullptr;
  1344. fOutputEvents.defaultPort = &fOutputEvents.portData[0];
  1345. }
  1346. ++j;
  1347. }
  1348. // Parameters
  1349. for (uint32_t i=0; i<numParameters; ++i)
  1350. {
  1351. clap_param_info_t paramInfo = {};
  1352. CARLA_SAFE_ASSERT_BREAK(paramsExt->get_info(fPlugin, i, &paramInfo));
  1353. CARLA_SAFE_ASSERT_BREAK(i < params);
  1354. pData->param.data[i].index = i;
  1355. pData->param.data[i].rindex = static_cast<int32_t>(paramInfo.id);
  1356. double min, max, def, step, stepSmall, stepLarge;
  1357. min = paramInfo.min_value;
  1358. max = paramInfo.max_value;
  1359. def = paramInfo.default_value;
  1360. if (min >= max)
  1361. max = min + 0.1;
  1362. if (def < min)
  1363. def = min;
  1364. else if (def > max)
  1365. def = max;
  1366. if (paramInfo.flags & (CLAP_PARAM_IS_HIDDEN|CLAP_PARAM_IS_BYPASS))
  1367. {
  1368. pData->param.data[i].type = PARAMETER_UNKNOWN;
  1369. }
  1370. else if (paramInfo.flags & CLAP_PARAM_IS_READONLY)
  1371. {
  1372. pData->param.data[i].type = PARAMETER_OUTPUT;
  1373. needsCtrlOut = true;
  1374. }
  1375. else
  1376. {
  1377. pData->param.data[i].type = PARAMETER_INPUT;
  1378. }
  1379. if (paramInfo.flags & CLAP_PARAM_IS_STEPPED)
  1380. {
  1381. if (carla_isEqual(max - min, 1.0))
  1382. {
  1383. step = stepSmall = stepLarge = 1.0;
  1384. pData->param.data[i].hints |= PARAMETER_IS_BOOLEAN;
  1385. }
  1386. else
  1387. {
  1388. step = 1.0;
  1389. stepSmall = 1.0;
  1390. stepLarge = std::min(max - min, 10.0);
  1391. }
  1392. pData->param.data[i].hints |= PARAMETER_IS_INTEGER;
  1393. }
  1394. else
  1395. {
  1396. double range = max - min;
  1397. step = range/100.0;
  1398. stepSmall = range/1000.0;
  1399. stepLarge = range/10.0;
  1400. }
  1401. if (pData->param.data[i].type != PARAMETER_UNKNOWN)
  1402. {
  1403. pData->param.data[i].hints |= PARAMETER_IS_ENABLED;
  1404. pData->param.data[i].hints |= PARAMETER_USES_CUSTOM_TEXT;
  1405. if (paramInfo.flags & CLAP_PARAM_IS_AUTOMATABLE)
  1406. {
  1407. pData->param.data[i].hints |= PARAMETER_IS_AUTOMATABLE;
  1408. if ((paramInfo.flags & CLAP_PARAM_IS_STEPPED) == 0x0)
  1409. pData->param.data[i].hints |= PARAMETER_CAN_BE_CV_CONTROLLED;
  1410. }
  1411. }
  1412. pData->param.ranges[i].min = min;
  1413. pData->param.ranges[i].max = max;
  1414. pData->param.ranges[i].def = def;
  1415. pData->param.ranges[i].step = step;
  1416. pData->param.ranges[i].stepSmall = stepSmall;
  1417. pData->param.ranges[i].stepLarge = stepLarge;
  1418. fInputEvents.updatedParams[i].clapId = paramInfo.id;
  1419. fInputEvents.updatedParams[i].cookie = paramInfo.cookie;
  1420. }
  1421. if (needsCtrlIn)
  1422. {
  1423. portName.clear();
  1424. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1425. {
  1426. portName = pData->name;
  1427. portName += ":";
  1428. }
  1429. portName += "events-in";
  1430. portName.truncate(portNameSize);
  1431. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, 0);
  1432. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1433. pData->event.cvSourcePorts = pData->client->createCVSourcePorts();
  1434. #endif
  1435. if (mIns == 1)
  1436. fInputEvents.portData[0].port = pData->event.portIn;
  1437. }
  1438. if (needsCtrlOut)
  1439. {
  1440. portName.clear();
  1441. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1442. {
  1443. portName = pData->name;
  1444. portName += ":";
  1445. }
  1446. portName += "events-out";
  1447. portName.truncate(portNameSize);
  1448. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, 0);
  1449. if (mOuts == 1)
  1450. fOutputEvents.portData[0].port = pData->event.portOut;
  1451. }
  1452. // plugin hints
  1453. pData->hints = PLUGIN_NEEDS_MAIN_THREAD_IDLE;
  1454. if (clapFeaturesContainInstrument(fPluginDescriptor->features))
  1455. pData->hints |= PLUGIN_IS_SYNTH;
  1456. #ifdef CLAP_WINDOW_API_NATIVE
  1457. if (guiExt != nullptr)
  1458. {
  1459. if (guiExt->is_api_supported(fPlugin, CLAP_WINDOW_API_NATIVE, false))
  1460. {
  1461. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  1462. pData->hints |= PLUGIN_HAS_CUSTOM_EMBED_UI;
  1463. pData->hints |= PLUGIN_NEEDS_UI_MAIN_THREAD;
  1464. }
  1465. else if (guiExt->is_api_supported(fPlugin, CLAP_WINDOW_API_NATIVE, true))
  1466. {
  1467. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  1468. pData->hints |= PLUGIN_NEEDS_UI_MAIN_THREAD;
  1469. }
  1470. }
  1471. #endif
  1472. if (aOuts > 0 && (aIns == aOuts || aIns == 1))
  1473. pData->hints |= PLUGIN_CAN_DRYWET;
  1474. if (aOuts > 0)
  1475. pData->hints |= PLUGIN_CAN_VOLUME;
  1476. if (aOuts >= 2 && aOuts % 2 == 0)
  1477. pData->hints |= PLUGIN_CAN_BALANCE;
  1478. // extra plugin hints
  1479. pData->extraHints = 0x0;
  1480. if (const uint32_t latency = fExtensions.latency != nullptr ? fExtensions.latency->get(fPlugin) : 0)
  1481. {
  1482. fLastKnownLatency = latency;
  1483. pData->client->setLatency(latency);
  1484. #ifndef BUILD_BRIDGE
  1485. pData->latency.recreateBuffers(std::max(aIns, aOuts), latency);
  1486. #endif
  1487. }
  1488. else
  1489. {
  1490. fLastKnownLatency = 0;
  1491. }
  1492. bufferSizeChanged(pData->engine->getBufferSize());
  1493. reloadPrograms(true);
  1494. if (pData->active)
  1495. activate();
  1496. else
  1497. runIdleCallbacksAsNeeded(false);
  1498. carla_debug("CarlaPluginCLAP::reload() - end");
  1499. }
  1500. void reloadPrograms(const bool doInit) override
  1501. {
  1502. carla_debug("CarlaPluginCLAP::reloadPrograms(%s)", bool2str(doInit));
  1503. }
  1504. // -------------------------------------------------------------------
  1505. // Plugin processing
  1506. void activate() noexcept override
  1507. {
  1508. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr,);
  1509. // FIXME check return status
  1510. fPlugin->activate(fPlugin, pData->engine->getSampleRate(), 1, pData->engine->getBufferSize());
  1511. fPlugin->start_processing(fPlugin);
  1512. fNeedsParamFlush = false;
  1513. runIdleCallbacksAsNeeded(false);
  1514. }
  1515. void deactivate() noexcept override
  1516. {
  1517. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr,);
  1518. // FIXME check return status
  1519. fPlugin->stop_processing(fPlugin);
  1520. fPlugin->deactivate(fPlugin);
  1521. runIdleCallbacksAsNeeded(false);
  1522. }
  1523. void process(const float* const* const audioIn,
  1524. float** const audioOut,
  1525. const float* const* const cvIn,
  1526. float** const,
  1527. const uint32_t frames) override
  1528. {
  1529. // --------------------------------------------------------------------------------------------------------
  1530. // Check if active
  1531. if (! pData->active)
  1532. {
  1533. // disable any output sound
  1534. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1535. carla_zeroFloats(audioOut[i], frames);
  1536. return;
  1537. }
  1538. // --------------------------------------------------------------------------------------------------------
  1539. // Check buffers
  1540. CARLA_SAFE_ASSERT_RETURN(frames > 0,);
  1541. if (pData->audioIn.count > 0)
  1542. {
  1543. CARLA_SAFE_ASSERT_RETURN(audioIn != nullptr,);
  1544. }
  1545. if (pData->audioOut.count > 0)
  1546. {
  1547. CARLA_SAFE_ASSERT_RETURN(audioOut != nullptr,);
  1548. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1549. CARLA_SAFE_ASSERT_RETURN(fAudioOutBuffers != nullptr,);
  1550. #endif
  1551. }
  1552. // --------------------------------------------------------------------------------------------------------
  1553. // Set audio buffers
  1554. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1555. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1556. carla_zeroFloats(fAudioOutBuffers[i], frames);
  1557. #endif
  1558. // --------------------------------------------------------------------------------------------------------
  1559. // Try lock, silence otherwise
  1560. if (pData->engine->isOffline())
  1561. {
  1562. pData->singleMutex.lock();
  1563. }
  1564. else if (! pData->singleMutex.tryLock())
  1565. {
  1566. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1567. carla_zeroFloats(audioOut[i], frames);
  1568. return;
  1569. }
  1570. // --------------------------------------------------------------------------------------------------------
  1571. fInputEvents.handleScheduledParameterUpdates();
  1572. // --------------------------------------------------------------------------------------------------------
  1573. // Check if needs reset
  1574. if (pData->needsReset)
  1575. {
  1576. // TODO alternative if plugin does not support CLAP_NOTE_DIALECT_MIDI
  1577. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1578. {
  1579. for (uint32_t p=0; p<fInputEvents.portCount; ++p)
  1580. {
  1581. const uint16_t port = fInputEvents.portData[p].clapPortIndex;
  1582. for (uint8_t i=0, k=fInputEvents.numEventsUsed; i < MAX_MIDI_CHANNELS; ++i)
  1583. {
  1584. fInputEvents.events[k + i].midi = {
  1585. { sizeof(clap_event_midi_t), 0, 0, CLAP_EVENT_MIDI, 0 },
  1586. port,
  1587. {
  1588. uint8_t(MIDI_STATUS_CONTROL_CHANGE | (i & MIDI_CHANNEL_BIT)),
  1589. MIDI_CONTROL_ALL_NOTES_OFF, 0
  1590. }
  1591. };
  1592. fInputEvents.events[k + MAX_MIDI_CHANNELS + i].midi = {
  1593. { sizeof(clap_event_midi_t), 0, 0, CLAP_EVENT_MIDI, 0 },
  1594. port,
  1595. {
  1596. uint8_t(MIDI_STATUS_CONTROL_CHANGE | (i & MIDI_CHANNEL_BIT)),
  1597. MIDI_CONTROL_ALL_SOUND_OFF, 0
  1598. }
  1599. };
  1600. }
  1601. fInputEvents.numEventsUsed += MAX_MIDI_CHANNELS * 2;
  1602. }
  1603. }
  1604. else if (pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  1605. {
  1606. for (uint32_t p=0; p<fInputEvents.portCount; ++p)
  1607. {
  1608. const uint16_t port = fInputEvents.portData[p].clapPortIndex;
  1609. for (uint8_t i=0, k=fInputEvents.numEventsUsed; i < MAX_MIDI_NOTE; ++i)
  1610. {
  1611. fInputEvents.events[k + i].midi = {
  1612. { sizeof(clap_event_midi_t), 0, 0, CLAP_EVENT_MIDI, 0 },
  1613. port,
  1614. {
  1615. uint8_t(MIDI_STATUS_NOTE_OFF | (pData->ctrlChannel & MIDI_CHANNEL_BIT)),
  1616. i, 0
  1617. }
  1618. };
  1619. }
  1620. fInputEvents.numEventsUsed += MAX_MIDI_NOTE;
  1621. }
  1622. }
  1623. pData->needsReset = false;
  1624. }
  1625. // --------------------------------------------------------------------------------------------------------
  1626. // Set TimeInfo
  1627. const EngineTimeInfo timeInfo(pData->engine->getTimeInfo());
  1628. clap_event_transport_t clapTransport = {
  1629. { sizeof(clap_event_transport_t), 0, 0, CLAP_EVENT_TRANSPORT, 0 },
  1630. 0x0, // flags
  1631. 0, // song_pos_beats, position in beats
  1632. 0, // song_pos_seconds, position in seconds
  1633. 0.0, // tempo, in bpm
  1634. 0.0, // tempo_inc, tempo increment for each samples and until the next time info event
  1635. 0, // loop_start_beats;
  1636. 0, // loop_end_beats;
  1637. 0, // loop_start_seconds;
  1638. 0, // loop_end_seconds;
  1639. 0, // bar_start, start pos of the current bar
  1640. 0, // bar_number, bar at song pos 0 has the number 0
  1641. 0, // tsig_num, time signature numerator
  1642. 0, // tsig_denom, time signature denominator
  1643. };
  1644. if (timeInfo.playing)
  1645. clapTransport.flags |= CLAP_TRANSPORT_IS_PLAYING;
  1646. // TODO song_pos_seconds (based on frame and sample rate)
  1647. if (timeInfo.bbt.valid)
  1648. {
  1649. // TODO song_pos_beats
  1650. // Tempo
  1651. clapTransport.tempo = timeInfo.bbt.beatsPerMinute;
  1652. clapTransport.flags |= CLAP_TRANSPORT_HAS_TEMPO;
  1653. // Bar
  1654. // TODO bar_start
  1655. clapTransport.bar_number = timeInfo.bbt.bar - 1;
  1656. // Time Signature
  1657. clapTransport.tsig_num = static_cast<uint16_t>(timeInfo.bbt.beatsPerBar + 0.5f);
  1658. clapTransport.tsig_denom = static_cast<uint16_t>(timeInfo.bbt.beatType + 0.5f);
  1659. clapTransport.flags |= CLAP_TRANSPORT_HAS_TIME_SIGNATURE;
  1660. }
  1661. else
  1662. {
  1663. // Tempo
  1664. clapTransport.tempo = 120.0;
  1665. clapTransport.flags |= CLAP_TRANSPORT_HAS_TEMPO;
  1666. // Time Signature
  1667. clapTransport.tsig_num = 4;
  1668. clapTransport.tsig_denom = 4;
  1669. clapTransport.flags |= CLAP_TRANSPORT_HAS_TIME_SIGNATURE;
  1670. }
  1671. // --------------------------------------------------------------------------------------------------------
  1672. // Event Input (main port)
  1673. if (pData->event.portIn != nullptr)
  1674. {
  1675. // ----------------------------------------------------------------------------------------------------
  1676. // MIDI Input (External)
  1677. if (pData->extNotes.mutex.tryLock())
  1678. {
  1679. if (fInputEvents.portCount == 0)
  1680. {
  1681. // does not handle MIDI
  1682. pData->extNotes.data.clear();
  1683. }
  1684. else
  1685. {
  1686. ExternalMidiNote note = { -1, 0, 0 };
  1687. const uint16_t p = fInputEvents.portData[0].clapPortIndex;
  1688. for (; fInputEvents.numEventsUsed < fInputEvents.numEventsAllocated && ! pData->extNotes.data.isEmpty();)
  1689. {
  1690. note = pData->extNotes.data.getFirst(note, true);
  1691. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  1692. if (fInputEvents.portData[0].supportedDialects & CLAP_NOTE_DIALECT_MIDI)
  1693. {
  1694. const uint8_t data[3] = {
  1695. uint8_t((note.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT)),
  1696. note.note,
  1697. note.velo
  1698. };
  1699. fInputEvents.addSimpleMidiEvent(true, p, 0, data);
  1700. }
  1701. else
  1702. {
  1703. fInputEvents.addSimpleNoteEvent(true, -1, 0, note.channel, note.note, note.velo);
  1704. }
  1705. }
  1706. }
  1707. pData->extNotes.mutex.unlock();
  1708. } // End of MIDI Input (External)
  1709. // ----------------------------------------------------------------------------------------------------
  1710. // Event Input (System)
  1711. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1712. bool allNotesOffSent = false;
  1713. #endif
  1714. uint32_t previousEventTime = 0;
  1715. uint32_t nextBankId;
  1716. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0)
  1717. nextBankId = pData->midiprog.data[pData->midiprog.current].bank;
  1718. else
  1719. nextBankId = 0;
  1720. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1721. if (cvIn != nullptr && pData->event.cvSourcePorts != nullptr)
  1722. pData->event.cvSourcePorts->initPortBuffers(cvIn + pData->cvIn.count, frames, true, pData->event.portIn);
  1723. #endif
  1724. const uint32_t numSysEvents = pData->event.portIn->getEventCount();
  1725. for (uint32_t i=0; i < numSysEvents; ++i)
  1726. {
  1727. EngineEvent& event(fInputEvents.defaultPort->port->getEvent(i));
  1728. uint32_t eventTime = event.time;
  1729. CARLA_SAFE_ASSERT_UINT2_CONTINUE(eventTime < frames, eventTime, frames);
  1730. if (eventTime < previousEventTime)
  1731. {
  1732. carla_stderr2("Timing error, eventTime:%u < previousEventTime:%u for '%s'",
  1733. eventTime, previousEventTime, pData->name);
  1734. eventTime = previousEventTime;
  1735. }
  1736. previousEventTime = eventTime;
  1737. switch (event.type)
  1738. {
  1739. case kEngineEventTypeNull:
  1740. break;
  1741. case kEngineEventTypeControl: {
  1742. EngineControlEvent& ctrlEvent(event.ctrl);
  1743. switch (ctrlEvent.type)
  1744. {
  1745. case kEngineControlEventTypeNull:
  1746. break;
  1747. case kEngineControlEventTypeParameter: {
  1748. float value;
  1749. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1750. // non-midi
  1751. if (event.channel == kEngineEventNonMidiChannel)
  1752. {
  1753. const uint32_t k = ctrlEvent.param;
  1754. CARLA_SAFE_ASSERT_CONTINUE(k < pData->param.count);
  1755. ctrlEvent.handled = true;
  1756. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  1757. setParameterValueRT(k, value, event.time, true);
  1758. continue;
  1759. }
  1760. // Control backend stuff
  1761. if (event.channel == pData->ctrlChannel)
  1762. {
  1763. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  1764. {
  1765. ctrlEvent.handled = true;
  1766. value = ctrlEvent.normalizedValue;
  1767. setDryWetRT(value, true);
  1768. }
  1769. else if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  1770. {
  1771. ctrlEvent.handled = true;
  1772. value = ctrlEvent.normalizedValue*127.0f/100.0f;
  1773. setVolumeRT(value, true);
  1774. }
  1775. else if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  1776. {
  1777. float left, right;
  1778. value = ctrlEvent.normalizedValue/0.5f - 1.0f;
  1779. if (value < 0.0f)
  1780. {
  1781. left = -1.0f;
  1782. right = (value*2.0f)+1.0f;
  1783. }
  1784. else if (value > 0.0f)
  1785. {
  1786. left = (value*2.0f)-1.0f;
  1787. right = 1.0f;
  1788. }
  1789. else
  1790. {
  1791. left = -1.0f;
  1792. right = 1.0f;
  1793. }
  1794. ctrlEvent.handled = true;
  1795. setBalanceLeftRT(left, true);
  1796. setBalanceRightRT(right, true);
  1797. }
  1798. }
  1799. #endif
  1800. // Control plugin parameters
  1801. uint32_t k;
  1802. for (k=0; k < pData->param.count; ++k)
  1803. {
  1804. if (pData->param.data[k].midiChannel != event.channel)
  1805. continue;
  1806. if (pData->param.data[k].mappedControlIndex != ctrlEvent.param)
  1807. continue;
  1808. if (pData->param.data[k].type != PARAMETER_INPUT)
  1809. continue;
  1810. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMATABLE) == 0)
  1811. continue;
  1812. ctrlEvent.handled = true;
  1813. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  1814. setParameterValueRT(k, value, event.time, true);
  1815. }
  1816. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param < MAX_MIDI_VALUE)
  1817. {
  1818. uint8_t midiData[3];
  1819. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1820. midiData[1] = uint8_t(ctrlEvent.param);
  1821. midiData[2] = uint8_t(ctrlEvent.normalizedValue*127.0f + 0.5f);
  1822. fInputEvents.addSimpleMidiEvent(true, 0, eventTime, midiData);
  1823. }
  1824. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1825. if (! ctrlEvent.handled)
  1826. checkForMidiLearn(event);
  1827. #endif
  1828. break;
  1829. } // case kEngineControlEventTypeParameter
  1830. case kEngineControlEventTypeMidiBank:
  1831. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  1832. {
  1833. if (event.channel == pData->ctrlChannel)
  1834. nextBankId = ctrlEvent.param;
  1835. }
  1836. else if (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES)
  1837. {
  1838. uint8_t midiData[3];
  1839. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1840. midiData[1] = MIDI_CONTROL_BANK_SELECT;
  1841. midiData[2] = uint8_t(ctrlEvent.param);
  1842. fInputEvents.addSimpleMidiEvent(true, 0, eventTime, midiData);
  1843. }
  1844. break;
  1845. case kEngineControlEventTypeMidiProgram:
  1846. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  1847. {
  1848. if (event.channel == pData->ctrlChannel)
  1849. {
  1850. const uint32_t nextProgramId(ctrlEvent.param);
  1851. for (uint32_t k=0; k < pData->midiprog.count; ++k)
  1852. {
  1853. if (pData->midiprog.data[k].bank == nextBankId && pData->midiprog.data[k].program == nextProgramId)
  1854. {
  1855. setMidiProgramRT(k, true);
  1856. break;
  1857. }
  1858. }
  1859. }
  1860. }
  1861. else if (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES)
  1862. {
  1863. uint8_t midiData[3];
  1864. midiData[0] = uint8_t(MIDI_STATUS_PROGRAM_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1865. midiData[1] = uint8_t(ctrlEvent.param);
  1866. midiData[2] = 0;
  1867. fInputEvents.addSimpleMidiEvent(true, 0, eventTime, midiData);
  1868. }
  1869. break;
  1870. case kEngineControlEventTypeAllSoundOff:
  1871. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1872. {
  1873. uint8_t midiData[3];
  1874. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1875. midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  1876. midiData[2] = 0;
  1877. fInputEvents.addSimpleMidiEvent(true, 0, eventTime, midiData);
  1878. }
  1879. break;
  1880. case kEngineControlEventTypeAllNotesOff:
  1881. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1882. {
  1883. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1884. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  1885. {
  1886. allNotesOffSent = true;
  1887. postponeRtAllNotesOff();
  1888. }
  1889. #endif
  1890. uint8_t midiData[3];
  1891. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1892. midiData[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  1893. midiData[2] = 0;
  1894. fInputEvents.addSimpleMidiEvent(true, 0, eventTime, midiData);
  1895. }
  1896. break;
  1897. } // switch (ctrlEvent.type)
  1898. break;
  1899. } // case kEngineEventTypeControl
  1900. case kEngineEventTypeMidi: {
  1901. const EngineMidiEvent& midiEvent(event.midi);
  1902. if (midiEvent.size > 3)
  1903. continue;
  1904. CARLA_SAFE_ASSERT_BREAK(midiEvent.port < fInputEvents.portCount);
  1905. const uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiEvent.data));
  1906. if (status == MIDI_STATUS_NOTE_OFF || status == MIDI_STATUS_NOTE_ON)
  1907. {
  1908. if (pData->options & PLUGIN_OPTION_SKIP_SENDING_NOTES)
  1909. continue;
  1910. // plugin does not support MIDI, send a simple note instead
  1911. if ((fInputEvents.portData[midiEvent.port].supportedDialects & CLAP_NOTE_DIALECT_MIDI) == 0x0)
  1912. {
  1913. fInputEvents.addSimpleNoteEvent(true, midiEvent.port, event.time,
  1914. event.channel, midiEvent.data[1], midiEvent.data[2]);
  1915. }
  1916. }
  1917. if (fInputEvents.portData[midiEvent.port].supportedDialects & CLAP_NOTE_DIALECT_MIDI)
  1918. {
  1919. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  1920. continue;
  1921. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  1922. continue;
  1923. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  1924. continue;
  1925. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  1926. continue;
  1927. // put back channel in data
  1928. uint8_t midiData[3] = { uint8_t(status | (event.channel & MIDI_CHANNEL_BIT)), 0, 0 };
  1929. switch (midiEvent.size)
  1930. {
  1931. case 3:
  1932. midiData[2] = midiEvent.data[2];
  1933. // fall through
  1934. case 2:
  1935. midiData[1] = midiEvent.data[1];
  1936. break;
  1937. }
  1938. fInputEvents.addSimpleMidiEvent(true, midiEvent.port, eventTime, midiData);
  1939. }
  1940. switch (status)
  1941. {
  1942. case MIDI_STATUS_NOTE_ON:
  1943. if (midiEvent.data[2] != 0)
  1944. {
  1945. pData->postponeNoteOnRtEvent(true, event.channel, midiEvent.data[1], midiEvent.data[2]);
  1946. break;
  1947. }
  1948. // fall through
  1949. case MIDI_STATUS_NOTE_OFF:
  1950. pData->postponeNoteOffRtEvent(true, event.channel, midiEvent.data[1]);
  1951. break;
  1952. }
  1953. } break;
  1954. } // switch (event.type)
  1955. }
  1956. pData->postRtEvents.trySplice();
  1957. } // End of Event Input (main port)
  1958. // --------------------------------------------------------------------------------------------------------
  1959. // Event input (multi MIDI port)
  1960. if (fInputEvents.portCount > 1)
  1961. {
  1962. // TODO
  1963. }
  1964. // --------------------------------------------------------------------------------------------------------
  1965. // Plugin processing
  1966. for (uint32_t i=0; i<fInputAudioBuffers.count; ++i)
  1967. fInputAudioBuffers.buffers[i].data32 = audioIn + fInputAudioBuffers.extra[i].offset;
  1968. for (uint32_t i=0; i<fOutputAudioBuffers.count; ++i)
  1969. {
  1970. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1971. fOutputAudioBuffers.buffers[i].data32 = fAudioOutBuffers + fOutputAudioBuffers.extra[i].offset;
  1972. #else
  1973. fOutputAudioBuffers.buffers[i].data32 = audioOut + fOutputAudioBuffers.extra[i].offset;
  1974. #endif
  1975. }
  1976. const clap_process_t process = {
  1977. static_cast<int64_t>(timeInfo.frame),
  1978. frames,
  1979. &clapTransport,
  1980. fInputAudioBuffers.cast(),
  1981. fOutputAudioBuffers.buffers,
  1982. fInputAudioBuffers.count,
  1983. fOutputAudioBuffers.count,
  1984. fInputEvents.cast(),
  1985. fOutputEvents.cast()
  1986. };
  1987. fPlugin->process(fPlugin, &process);
  1988. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1989. // --------------------------------------------------------------------------------------------------------
  1990. // Post-processing (dry/wet, volume and balance)
  1991. {
  1992. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  1993. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  1994. const bool isMono = (pData->audioIn.count == 1);
  1995. bool isPair;
  1996. float bufValue, oldBufLeft[doBalance ? frames : 1];
  1997. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1998. {
  1999. // Dry/Wet
  2000. if (doDryWet)
  2001. {
  2002. const uint32_t c = isMono ? 0 : i;
  2003. for (uint32_t k=0; k < frames; ++k)
  2004. {
  2005. bufValue = audioIn[c][k];
  2006. fAudioOutBuffers[i][k] = (fAudioOutBuffers[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  2007. }
  2008. }
  2009. // Balance
  2010. if (doBalance)
  2011. {
  2012. isPair = (i % 2 == 0);
  2013. if (isPair)
  2014. {
  2015. CARLA_ASSERT(i+1 < pData->audioOut.count);
  2016. carla_copyFloats(oldBufLeft, fAudioOutBuffers[i], frames);
  2017. }
  2018. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  2019. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  2020. for (uint32_t k=0; k < frames; ++k)
  2021. {
  2022. if (isPair)
  2023. {
  2024. // left
  2025. fAudioOutBuffers[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  2026. fAudioOutBuffers[i][k] += fAudioOutBuffers[i+1][k] * (1.0f - balRangeR);
  2027. }
  2028. else
  2029. {
  2030. // right
  2031. fAudioOutBuffers[i][k] = fAudioOutBuffers[i][k] * balRangeR;
  2032. fAudioOutBuffers[i][k] += oldBufLeft[k] * balRangeL;
  2033. }
  2034. }
  2035. }
  2036. // Volume (and buffer copy)
  2037. {
  2038. for (uint32_t k=0; k < frames; ++k)
  2039. audioOut[i][k] = fAudioOutBuffers[i][k] * pData->postProc.volume;
  2040. }
  2041. }
  2042. } // End of Post-processing
  2043. #endif // BUILD_BRIDGE_ALTERNATIVE_ARCH
  2044. // --------------------------------------------------------------------------------------------------------
  2045. pData->singleMutex.unlock();
  2046. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2047. // --------------------------------------------------------------------------------------------------------
  2048. // Control Output
  2049. if (pData->event.portOut != nullptr && fExtensions.params != nullptr)
  2050. {
  2051. uint8_t channel;
  2052. uint16_t param;
  2053. double value;
  2054. for (uint32_t k=0; k < pData->param.count; ++k)
  2055. {
  2056. if (pData->param.data[k].type != PARAMETER_OUTPUT)
  2057. continue;
  2058. if (pData->param.data[k].mappedControlIndex <= 0)
  2059. continue;
  2060. if (!fExtensions.params->get_value(fPlugin, pData->param.data[k].rindex, &value))
  2061. continue;
  2062. channel = pData->param.data[k].midiChannel;
  2063. param = static_cast<uint16_t>(pData->param.data[k].mappedControlIndex);
  2064. value = pData->param.ranges[k].getNormalizedValue(value);
  2065. pData->event.portOut->writeControlEvent(0, channel,
  2066. kEngineControlEventTypeParameter, param, -1,
  2067. value);
  2068. }
  2069. } // End of Control Output
  2070. #endif
  2071. // --------------------------------------------------------------------------------------------------------
  2072. // Events/MIDI Output
  2073. for (uint32_t i=0; i<fOutputEvents.numEventsUsed; ++i)
  2074. {
  2075. const carla_clap_output_events::Event& ev(fOutputEvents.events[i]);
  2076. switch (ev.header.type)
  2077. {
  2078. case CLAP_EVENT_PARAM_VALUE:
  2079. for (uint32_t j=0; j<pData->param.count; ++j)
  2080. {
  2081. if (pData->param.data[j].rindex != static_cast<int32_t>(ev.param.param_id))
  2082. continue;
  2083. pData->postponeParameterChangeRtEvent(true, static_cast<int32_t>(j), ev.param.value);
  2084. break;
  2085. }
  2086. break;
  2087. case CLAP_EVENT_MIDI:
  2088. for (uint32_t j=0; j<fOutputEvents.portCount; ++j)
  2089. {
  2090. if (fOutputEvents.portData[j].clapPortIndex != ev.midi.port_index)
  2091. continue;
  2092. fOutputEvents.portData[j].port->writeMidiEvent(ev.midi.header.time, 3, ev.midi.data);
  2093. break;
  2094. }
  2095. break;
  2096. }
  2097. }
  2098. fOutputEvents.numEventsUsed = 0;
  2099. // --------------------------------------------------------------------------------------------------------
  2100. #ifdef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2101. return;
  2102. // unused
  2103. (void)cvIn;
  2104. #endif
  2105. }
  2106. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2107. void bufferSizeChanged(const uint32_t newBufferSize) override
  2108. {
  2109. CARLA_ASSERT_INT(newBufferSize > 0, newBufferSize);
  2110. carla_debug("CarlaPluginCLAP::bufferSizeChanged(%i)", newBufferSize);
  2111. if (pData->active)
  2112. deactivate();
  2113. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  2114. {
  2115. if (fAudioOutBuffers[i] != nullptr)
  2116. delete[] fAudioOutBuffers[i];
  2117. fAudioOutBuffers[i] = new float[newBufferSize];
  2118. }
  2119. if (pData->active)
  2120. activate();
  2121. }
  2122. #endif
  2123. // -------------------------------------------------------------------
  2124. // Plugin buffers
  2125. void initBuffers() const noexcept override
  2126. {
  2127. fInputEvents.initBuffers();
  2128. fOutputEvents.initBuffers();
  2129. CarlaPlugin::initBuffers();
  2130. }
  2131. void clearBuffers() noexcept override
  2132. {
  2133. carla_debug("CarlaPluginCLAP::clearBuffers() - start");
  2134. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2135. if (fAudioOutBuffers != nullptr)
  2136. {
  2137. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  2138. {
  2139. if (fAudioOutBuffers[i] != nullptr)
  2140. {
  2141. delete[] fAudioOutBuffers[i];
  2142. fAudioOutBuffers[i] = nullptr;
  2143. }
  2144. }
  2145. delete[] fAudioOutBuffers;
  2146. fAudioOutBuffers = nullptr;
  2147. }
  2148. #endif
  2149. fInputEvents.clear(pData->event.portIn);
  2150. fOutputEvents.clear(pData->event.portOut);
  2151. CarlaPlugin::clearBuffers();
  2152. carla_debug("CarlaPluginCLAP::clearBuffers() - end");
  2153. }
  2154. // -------------------------------------------------------------------
  2155. // Post-poned UI Stuff
  2156. // nothing
  2157. // -------------------------------------------------------------------
  2158. protected:
  2159. #ifdef CLAP_WINDOW_API_NATIVE
  2160. void handlePluginUIClosed() override
  2161. {
  2162. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  2163. carla_stdout("CarlaPluginCLAP::handlePluginUIClosed()");
  2164. fUI.shouldClose = true;
  2165. }
  2166. void handlePluginUIResized(const uint width, const uint height) override
  2167. {
  2168. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  2169. carla_stdout("CarlaPluginCLAP::handlePluginUIResized(%u, %u | vs %u %u) %d %s %s",
  2170. width, height,
  2171. fUI.width, fUI.height,
  2172. fUI.isResizingFromPlugin, bool2str(fUI.isResizingFromInit), bool2str(fUI.isResizingFromHost));
  2173. if (fExtensions.gui == nullptr)
  2174. return;
  2175. if (fUI.isResizingFromPlugin != 0)
  2176. {
  2177. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.width == width, fUI.width, width,);
  2178. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.height == height, fUI.height, height,);
  2179. fUI.isResizingFromPlugin = 2;
  2180. return;
  2181. }
  2182. if (fUI.isResizingFromInit)
  2183. {
  2184. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.width == width, fUI.width, width,);
  2185. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.height == height, fUI.height, height,);
  2186. fUI.isResizingFromInit = false;
  2187. return;
  2188. }
  2189. if (fUI.isResizingFromHost)
  2190. {
  2191. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.width == width, fUI.width, width,);
  2192. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.height == height, fUI.height, height,);
  2193. fUI.isResizingFromHost = false;
  2194. return;
  2195. }
  2196. if (fUI.width != width || fUI.height != height)
  2197. {
  2198. uint width2 = width;
  2199. uint height2 = height;
  2200. if (fExtensions.gui->adjust_size(fPlugin, &width2, &height2))
  2201. {
  2202. if (width2 != width || height2 != height)
  2203. {
  2204. fUI.isResizingFromHost = true;
  2205. fUI.width = width2;
  2206. fUI.height = height2;
  2207. fUI.window->setSize(width2, height2, false, false);
  2208. }
  2209. else
  2210. {
  2211. fExtensions.gui->set_size(fPlugin, width2, height2);
  2212. }
  2213. }
  2214. }
  2215. }
  2216. #endif
  2217. // -------------------------------------------------------------------
  2218. void clapRequestRestart() override
  2219. {
  2220. carla_stdout("CarlaPluginCLAP::clapRequestRestart()");
  2221. fNeedsRestart = true;
  2222. }
  2223. void clapRequestProcess() override
  2224. {
  2225. carla_stdout("CarlaPluginCLAP::clapRequestProcess()");
  2226. fNeedsProcess = true;
  2227. }
  2228. void clapRequestCallback() override
  2229. {
  2230. carla_stdout("CarlaPluginCLAP::clapRequestCallback()");
  2231. if (fPlugin->on_main_thread != nullptr)
  2232. fNeedsIdleCallback = true;
  2233. }
  2234. // -------------------------------------------------------------------
  2235. void clapLatencyChanged() override
  2236. {
  2237. carla_stdout("CarlaPluginCLAP::clapLatencyChanged()");
  2238. CARLA_SAFE_ASSERT_RETURN(fExtensions.latency != nullptr,);
  2239. fLastKnownLatency = fExtensions.latency->get(fPlugin);
  2240. }
  2241. // -------------------------------------------------------------------
  2242. void clapMarkDirty() override
  2243. {
  2244. carla_stdout("CarlaPluginCLAP::clapMarkDirty()");
  2245. }
  2246. // -------------------------------------------------------------------
  2247. #ifdef CLAP_WINDOW_API_NATIVE
  2248. void clapGuiResizeHintsChanged() override
  2249. {
  2250. carla_stdout("CarlaPluginCLAP::clapGuiResizeHintsChanged()");
  2251. }
  2252. bool clapGuiRequestResize(const uint width, const uint height) override
  2253. {
  2254. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr, false);
  2255. carla_stdout("CarlaPluginCLAP::hostRequestResize(%u, %u)", width, height);
  2256. fUI.isResizingFromPlugin = 3;
  2257. fUI.width = width;
  2258. fUI.height = height;
  2259. fUI.window->setSize(width, height, true, false);
  2260. return true;
  2261. }
  2262. bool clapGuiRequestShow() override
  2263. {
  2264. carla_stdout("CarlaPluginCLAP::clapGuiRequestShow()");
  2265. return false;
  2266. }
  2267. bool clapGuiRequestHide() override
  2268. {
  2269. carla_stdout("CarlaPluginCLAP::clapGuiRequestHide()");
  2270. return false;
  2271. }
  2272. void clapGuiClosed(const bool wasDestroyed) override
  2273. {
  2274. carla_stdout("CarlaPluginCLAP::clapGuiClosed(%s)", bool2str(wasDestroyed));
  2275. CARLA_SAFE_ASSERT_RETURN(!fUI.isEmbed,);
  2276. CARLA_SAFE_ASSERT_RETURN(fUI.isVisible,);
  2277. fUI.isVisible = false;
  2278. if (wasDestroyed)
  2279. {
  2280. CARLA_SAFE_ASSERT_RETURN(fUI.isCreated,);
  2281. fExtensions.gui->destroy(fPlugin);
  2282. fUI.isCreated = false;
  2283. }
  2284. pData->engine->callback(true, true,
  2285. ENGINE_CALLBACK_UI_STATE_CHANGED,
  2286. pData->id,
  2287. 0,
  2288. 0, 0, 0.0f, nullptr);
  2289. }
  2290. // -------------------------------------------------------------------
  2291. #ifdef _POSIX_VERSION
  2292. bool clapRegisterPosixFD(const int fd, const clap_posix_fd_flags_t flags) override
  2293. {
  2294. carla_stdout("CarlaPluginCLAP::clapRegisterPosixFD(%i, %x)", fd, flags);
  2295. // NOTE some plugins wont have their posix fd extension ready when first loaded, so try again here
  2296. if (fExtensions.posixFD == nullptr)
  2297. {
  2298. const clap_plugin_posix_fd_support_t* const posixFdExt = static_cast<const clap_plugin_posix_fd_support_t*>(
  2299. fPlugin->get_extension(fPlugin, CLAP_EXT_POSIX_FD_SUPPORT));
  2300. if (posixFdExt != nullptr && posixFdExt->on_fd != nullptr)
  2301. fExtensions.posixFD = posixFdExt;
  2302. }
  2303. CARLA_SAFE_ASSERT_RETURN(fExtensions.posixFD != nullptr, false);
  2304. // FIXME events only driven as long as UI is open
  2305. // CARLA_SAFE_ASSERT_RETURN(fUI.isCreated, false);
  2306. if (flags & (CLAP_POSIX_FD_READ|CLAP_POSIX_FD_WRITE))
  2307. {
  2308. #ifdef CARLA_CLAP_POSIX_EPOLL
  2309. const int hostFd = ::epoll_create1(0);
  2310. #else
  2311. const int hostFd = ::kqueue();
  2312. #endif
  2313. CARLA_SAFE_ASSERT_RETURN(hostFd >= 0, false);
  2314. #ifdef CARLA_CLAP_POSIX_EPOLL
  2315. struct ::epoll_event ev = {};
  2316. if (flags & CLAP_POSIX_FD_READ)
  2317. ev.events |= EPOLLIN;
  2318. if (flags & CLAP_POSIX_FD_WRITE)
  2319. ev.events |= EPOLLOUT;
  2320. ev.data.fd = fd;
  2321. if (::epoll_ctl(hostFd, EPOLL_CTL_ADD, fd, &ev) < 0)
  2322. {
  2323. ::close(hostFd);
  2324. return false;
  2325. }
  2326. #endif
  2327. const HostPosixFileDescriptorDetails posixFD = {
  2328. hostFd,
  2329. fd,
  2330. flags,
  2331. };
  2332. fPosixFileDescriptors.append(posixFD);
  2333. return true;
  2334. }
  2335. return false;
  2336. }
  2337. bool clapModifyPosixFD(const int fd, const clap_posix_fd_flags_t flags) override
  2338. {
  2339. carla_stdout("CarlaPluginCLAP::clapTimerUnregister(%i, %x)", fd, flags);
  2340. for (LinkedList<HostPosixFileDescriptorDetails>::Itenerator it = fPosixFileDescriptors.begin2(); it.valid(); it.next())
  2341. {
  2342. HostPosixFileDescriptorDetails& posixFD(it.getValue(kPosixFileDescriptorFallbackNC));
  2343. if (posixFD.pluginFd == fd)
  2344. {
  2345. if (posixFD.flags == flags)
  2346. return true;
  2347. #ifdef CARLA_CLAP_POSIX_EPOLL
  2348. struct ::epoll_event ev = {};
  2349. if (flags & CLAP_POSIX_FD_READ)
  2350. ev.events |= EPOLLIN;
  2351. if (flags & CLAP_POSIX_FD_WRITE)
  2352. ev.events |= EPOLLOUT;
  2353. ev.data.fd = fd;
  2354. if (::epoll_ctl(posixFD.hostFd, EPOLL_CTL_MOD, fd, &ev) < 0)
  2355. return false;
  2356. #endif
  2357. posixFD.flags = flags;
  2358. return true;
  2359. }
  2360. }
  2361. return false;
  2362. }
  2363. bool clapUnregisterPosixFD(const int fd) override
  2364. {
  2365. carla_stdout("CarlaPluginCLAP::clapTimerUnregister(%i)", fd);
  2366. for (LinkedList<HostPosixFileDescriptorDetails>::Itenerator it = fPosixFileDescriptors.begin2(); it.valid(); it.next())
  2367. {
  2368. const HostPosixFileDescriptorDetails& posixFD(it.getValue(kPosixFileDescriptorFallback));
  2369. if (posixFD.pluginFd == fd)
  2370. {
  2371. #ifdef CARLA_CLAP_POSIX_EPOLL
  2372. ::epoll_ctl(posixFD.hostFd, EPOLL_CTL_DEL, fd, nullptr);
  2373. #endif
  2374. ::close(posixFD.hostFd);
  2375. fPosixFileDescriptors.remove(it);
  2376. return true;
  2377. }
  2378. }
  2379. return false;
  2380. }
  2381. #endif // _POSIX_VERSION
  2382. // -------------------------------------------------------------------
  2383. bool clapRegisterTimer(const uint32_t periodInMs, clap_id* const timerId) override
  2384. {
  2385. carla_stdout("CarlaPluginCLAP::clapTimerRegister(%u, %p)", periodInMs, timerId);
  2386. // NOTE some plugins wont have their timer extension ready when first loaded, so try again here
  2387. if (fExtensions.timer == nullptr)
  2388. {
  2389. const clap_plugin_timer_support_t* const timerExt = static_cast<const clap_plugin_timer_support_t*>(
  2390. fPlugin->get_extension(fPlugin, CLAP_EXT_TIMER_SUPPORT));
  2391. if (timerExt != nullptr && timerExt->on_timer != nullptr)
  2392. fExtensions.timer = timerExt;
  2393. }
  2394. CARLA_SAFE_ASSERT_RETURN(fExtensions.timer != nullptr, false);
  2395. // FIXME events only driven as long as UI is open
  2396. // CARLA_SAFE_ASSERT_RETURN(fUI.isCreated, false);
  2397. const HostTimerDetails timer = {
  2398. fTimers.isNotEmpty() ? fTimers.getLast(kTimerFallback).clapId + 1 : 1,
  2399. periodInMs,
  2400. 0
  2401. };
  2402. fTimers.append(timer);
  2403. *timerId = timer.clapId;
  2404. return true;
  2405. }
  2406. bool clapUnregisterTimer(const clap_id timerId) override
  2407. {
  2408. carla_stdout("CarlaPluginCLAP::clapTimerUnregister(%u)", timerId);
  2409. for (LinkedList<HostTimerDetails>::Itenerator it = fTimers.begin2(); it.valid(); it.next())
  2410. {
  2411. const HostTimerDetails& timer(it.getValue(kTimerFallback));
  2412. if (timer.clapId == timerId)
  2413. {
  2414. fTimers.remove(it);
  2415. return true;
  2416. }
  2417. }
  2418. return false;
  2419. }
  2420. #endif // CLAP_WINDOW_API_NATIVE
  2421. // -------------------------------------------------------------------
  2422. public:
  2423. bool init(const CarlaPluginPtr plugin,
  2424. const char* const filename, const char* const name, const char* const id, const uint options)
  2425. {
  2426. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  2427. // ---------------------------------------------------------------
  2428. // first checks
  2429. if (pData->client != nullptr)
  2430. {
  2431. pData->engine->setLastError("Plugin client is already registered");
  2432. return false;
  2433. }
  2434. if (filename == nullptr || filename[0] == '\0')
  2435. {
  2436. pData->engine->setLastError("null filename");
  2437. return false;
  2438. }
  2439. // ---------------------------------------------------------------
  2440. const clap_plugin_entry_t* entry;
  2441. #ifdef CARLA_OS_MAC
  2442. if (!water::File(filename).existsAsFile())
  2443. {
  2444. if (! fBundleLoader.load(filename))
  2445. {
  2446. pData->engine->setLastError("Failed to load CLAP bundle executable");
  2447. return false;
  2448. }
  2449. entry = fBundleLoader.getSymbol<const clap_plugin_entry_t*>(CFSTR("clap_entry"));
  2450. }
  2451. else
  2452. #endif
  2453. {
  2454. if (! pData->libOpen(filename))
  2455. {
  2456. pData->engine->setLastError(pData->libError(filename));
  2457. return false;
  2458. }
  2459. entry = pData->libSymbol<const clap_plugin_entry_t*>("clap_entry");
  2460. }
  2461. if (entry == nullptr)
  2462. {
  2463. pData->engine->setLastError("Could not find the CLAP entry in the plugin library");
  2464. return false;
  2465. }
  2466. if (entry->init == nullptr || entry->deinit == nullptr || entry->get_factory == nullptr)
  2467. {
  2468. pData->engine->setLastError("CLAP factory entries are null");
  2469. return false;
  2470. }
  2471. if (!clap_version_is_compatible(entry->clap_version))
  2472. {
  2473. pData->engine->setLastError("Incompatible CLAP plugin");
  2474. return false;
  2475. }
  2476. // ---------------------------------------------------------------
  2477. const water::String pluginPath(water::File(filename).getParentDirectory().getFullPathName());
  2478. if (!entry->init(pluginPath.toRawUTF8()))
  2479. {
  2480. pData->engine->setLastError("Plugin entry failed to initialize");
  2481. return false;
  2482. }
  2483. fPluginEntry = entry;
  2484. // ---------------------------------------------------------------
  2485. const clap_plugin_factory_t* const factory = static_cast<const clap_plugin_factory_t*>(
  2486. entry->get_factory(CLAP_PLUGIN_FACTORY_ID));
  2487. if (factory == nullptr
  2488. || factory->get_plugin_count == nullptr
  2489. || factory->get_plugin_descriptor == nullptr
  2490. || factory->create_plugin == nullptr)
  2491. {
  2492. pData->engine->setLastError("Plugin is missing factory methods");
  2493. return false;
  2494. }
  2495. // ---------------------------------------------------------------
  2496. if (const uint32_t count = factory->get_plugin_count(factory))
  2497. {
  2498. // null id requested, use first available plugin
  2499. if (id == nullptr || id[0] == '\0')
  2500. {
  2501. fPluginDescriptor = factory->get_plugin_descriptor(factory, 0);
  2502. if (fPluginDescriptor == nullptr)
  2503. {
  2504. pData->engine->setLastError("Plugin library does not contain a valid first plugin");
  2505. return false;
  2506. }
  2507. }
  2508. else
  2509. {
  2510. for (uint32_t i=0; i<count; ++i)
  2511. {
  2512. const clap_plugin_descriptor_t* const desc = factory->get_plugin_descriptor(factory, i);
  2513. CARLA_SAFE_ASSERT_CONTINUE(desc != nullptr);
  2514. CARLA_SAFE_ASSERT_CONTINUE(desc->id != nullptr);
  2515. if (std::strcmp(desc->id, id) == 0)
  2516. {
  2517. fPluginDescriptor = desc;
  2518. break;
  2519. }
  2520. }
  2521. if (fPluginDescriptor == nullptr)
  2522. {
  2523. pData->engine->setLastError("Plugin library does not contain the requested plugin");
  2524. return false;
  2525. }
  2526. }
  2527. }
  2528. else
  2529. {
  2530. pData->engine->setLastError("Plugin library contains no plugins");
  2531. return false;
  2532. }
  2533. // ---------------------------------------------------------------
  2534. fPlugin = factory->create_plugin(factory, &fHost, fPluginDescriptor->id);
  2535. if (fPlugin == nullptr)
  2536. {
  2537. pData->engine->setLastError("Failed to create CLAP plugin instance");
  2538. return false;
  2539. }
  2540. if (!fPlugin->init(fPlugin))
  2541. {
  2542. pData->engine->setLastError("Failed to initialize CLAP plugin instance");
  2543. return false;
  2544. }
  2545. // ---------------------------------------------------------------
  2546. // get info
  2547. pData->name = pData->engine->getUniquePluginName(name != nullptr && name[0] != '\0' ? name
  2548. : fPluginDescriptor->name);
  2549. pData->filename = carla_strdup(filename);
  2550. // ---------------------------------------------------------------
  2551. // register client
  2552. pData->client = pData->engine->addClient(plugin);
  2553. if (pData->client == nullptr || ! pData->client->isOk())
  2554. {
  2555. pData->engine->setLastError("Failed to register plugin client");
  2556. return false;
  2557. }
  2558. // ---------------------------------------------------------------
  2559. // set default options
  2560. pData->options = PLUGIN_OPTION_FIXED_BUFFERS;
  2561. if (const clap_plugin_state_t* const stateExt =
  2562. static_cast<const clap_plugin_state_t*>(fPlugin->get_extension(fPlugin, CLAP_EXT_STATE)))
  2563. {
  2564. if (stateExt->save != nullptr && stateExt->load != nullptr)
  2565. if (isPluginOptionEnabled(options, PLUGIN_OPTION_USE_CHUNKS))
  2566. pData->options |= PLUGIN_OPTION_USE_CHUNKS;
  2567. }
  2568. if (const clap_plugin_note_ports_t* const notePortsExt =
  2569. static_cast<const clap_plugin_note_ports_t*>(fPlugin->get_extension(fPlugin, CLAP_EXT_NOTE_PORTS)))
  2570. {
  2571. const uint32_t numNoteInputPorts = notePortsExt->count != nullptr && notePortsExt->get != nullptr
  2572. ? notePortsExt->count(fPlugin, true) : 0;
  2573. for (uint32_t i=0; i<numNoteInputPorts; ++i)
  2574. {
  2575. clap_note_port_info_t portInfo = {};
  2576. CARLA_SAFE_ASSERT_BREAK(notePortsExt->get(fPlugin, i, true, &portInfo));
  2577. if (portInfo.supported_dialects & CLAP_NOTE_DIALECT_MIDI)
  2578. {
  2579. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CONTROL_CHANGES))
  2580. pData->options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  2581. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CHANNEL_PRESSURE))
  2582. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  2583. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH))
  2584. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  2585. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PITCHBEND))
  2586. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  2587. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_ALL_SOUND_OFF))
  2588. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  2589. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PROGRAM_CHANGES))
  2590. pData->options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  2591. if (isPluginOptionInverseEnabled(options, PLUGIN_OPTION_SKIP_SENDING_NOTES))
  2592. pData->options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  2593. break;
  2594. }
  2595. if (portInfo.supported_dialects & CLAP_NOTE_DIALECT_CLAP)
  2596. {
  2597. if (isPluginOptionInverseEnabled(options, PLUGIN_OPTION_SKIP_SENDING_NOTES))
  2598. pData->options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  2599. // nobreak, in case another port supports MIDI
  2600. }
  2601. }
  2602. }
  2603. // if (fEffect->numPrograms > 1 && (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) == 0)
  2604. // if (isPluginOptionEnabled(options, PLUGIN_OPTION_MAP_PROGRAM_CHANGES))
  2605. // pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  2606. return true;
  2607. }
  2608. private:
  2609. const clap_plugin_t* fPlugin;
  2610. const clap_plugin_descriptor_t* fPluginDescriptor;
  2611. const clap_plugin_entry_t* fPluginEntry;
  2612. const carla_clap_host fHost;
  2613. struct Extensions {
  2614. const clap_plugin_latency_t* latency;
  2615. const clap_plugin_params_t* params;
  2616. const clap_plugin_state_t* state;
  2617. const clap_plugin_timer_support_t* timer;
  2618. #ifdef CLAP_WINDOW_API_NATIVE
  2619. const clap_plugin_gui_t* gui;
  2620. #ifdef _POSIX_VERSION
  2621. const clap_plugin_posix_fd_support_t* posixFD;
  2622. #endif
  2623. #endif
  2624. Extensions()
  2625. : latency(nullptr),
  2626. params(nullptr),
  2627. state(nullptr),
  2628. timer(nullptr)
  2629. #ifdef CLAP_WINDOW_API_NATIVE
  2630. , gui(nullptr)
  2631. #ifdef _POSIX_VERSION
  2632. , posixFD(nullptr)
  2633. #endif
  2634. #endif
  2635. {
  2636. }
  2637. CARLA_DECLARE_NON_COPYABLE(Extensions)
  2638. } fExtensions;
  2639. #ifdef CLAP_WINDOW_API_NATIVE
  2640. struct UI {
  2641. bool initalized;
  2642. bool isCreated;
  2643. bool isEmbed;
  2644. bool isVisible;
  2645. bool isResizingFromHost;
  2646. bool isResizingFromInit;
  2647. int isResizingFromPlugin;
  2648. bool shouldClose;
  2649. uint32_t width, height;
  2650. CarlaPluginUI* window;
  2651. UI()
  2652. : initalized(false),
  2653. isCreated(false),
  2654. isEmbed(false),
  2655. isVisible(false),
  2656. isResizingFromHost(false),
  2657. isResizingFromInit(false),
  2658. isResizingFromPlugin(0),
  2659. shouldClose(false),
  2660. width(0),
  2661. height(0),
  2662. window(nullptr) {}
  2663. ~UI()
  2664. {
  2665. CARLA_SAFE_ASSERT(window == nullptr);
  2666. }
  2667. CARLA_DECLARE_NON_COPYABLE(UI)
  2668. } fUI;
  2669. #ifdef _POSIX_VERSION
  2670. LinkedList<HostPosixFileDescriptorDetails> fPosixFileDescriptors;
  2671. #endif
  2672. LinkedList<HostTimerDetails> fTimers;
  2673. #endif
  2674. carla_clap_input_audio_buffers fInputAudioBuffers;
  2675. carla_clap_output_audio_buffers fOutputAudioBuffers;
  2676. carla_clap_input_events fInputEvents;
  2677. carla_clap_output_events fOutputEvents;
  2678. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2679. float** fAudioOutBuffers;
  2680. #endif
  2681. void* fLastChunk;
  2682. uint32_t fLastKnownLatency;
  2683. const bool kEngineHasIdleOnMainThread;
  2684. bool fNeedsParamFlush;
  2685. bool fNeedsRestart;
  2686. bool fNeedsProcess;
  2687. bool fNeedsIdleCallback;
  2688. #ifdef CARLA_OS_MAC
  2689. BundleLoader fBundleLoader;
  2690. #endif
  2691. void runIdleCallbacksAsNeeded(const bool isIdleCallback)
  2692. {
  2693. if (isIdleCallback && (fNeedsRestart || fNeedsProcess))
  2694. {
  2695. carla_stdout("runIdleCallbacksAsNeeded %d %d", fNeedsRestart, fNeedsProcess);
  2696. const bool needsRestart = fNeedsRestart;
  2697. if (needsRestart)
  2698. {
  2699. fNeedsRestart = false;
  2700. setActive(false, true, true);
  2701. }
  2702. if (fNeedsProcess)
  2703. {
  2704. fNeedsProcess = false;
  2705. setEnabled(true);
  2706. setActive(true, true, true);
  2707. }
  2708. else if (needsRestart)
  2709. {
  2710. setActive(true, true, true);
  2711. }
  2712. }
  2713. if (fNeedsParamFlush)
  2714. {
  2715. fNeedsParamFlush = false;
  2716. carla_clap_input_events copy;
  2717. copy.reallocEqualTo(fInputEvents);
  2718. {
  2719. const ScopedSingleProcessLocker sspl(this, true);
  2720. fInputEvents.handleScheduledParameterUpdates();
  2721. fInputEvents.swap(copy);
  2722. }
  2723. fExtensions.params->flush(fPlugin, copy.cast(), nullptr);
  2724. }
  2725. if (fNeedsIdleCallback)
  2726. {
  2727. fNeedsIdleCallback = false;
  2728. fPlugin->on_main_thread(fPlugin);
  2729. }
  2730. #ifdef CLAP_WINDOW_API_NATIVE
  2731. #ifdef _POSIX_VERSION
  2732. for (LinkedList<HostPosixFileDescriptorDetails>::Itenerator it = fPosixFileDescriptors.begin2(); it.valid(); it.next())
  2733. {
  2734. const HostPosixFileDescriptorDetails& posixFD(it.getValue(kPosixFileDescriptorFallback));
  2735. #ifdef CARLA_CLAP_POSIX_EPOLL
  2736. struct ::epoll_event event;
  2737. #else
  2738. const int16_t filter = posixFD.flags & CLAP_POSIX_FD_WRITE ? EVFILT_WRITE : EVFILT_READ;
  2739. struct ::kevent kev = {}, event;
  2740. struct ::timespec timeout = {};
  2741. EV_SET(&kev, posixFD.pluginFd, filter, EV_ADD|EV_ENABLE, 0, 0, nullptr);
  2742. #endif
  2743. for (int i=0; i<50; ++i)
  2744. {
  2745. #ifdef CARLA_CLAP_POSIX_EPOLL
  2746. switch (::epoll_wait(posixFD.hostFd, &event, 1, 0))
  2747. #else
  2748. switch (::kevent(posixFD.hostFd, &kev, 1, &event, 1, &timeout))
  2749. #endif
  2750. {
  2751. case 1:
  2752. fExtensions.posixFD->on_fd(fPlugin, posixFD.pluginFd, posixFD.flags);
  2753. break;
  2754. case -1:
  2755. fExtensions.posixFD->on_fd(fPlugin, posixFD.pluginFd, posixFD.flags | CLAP_POSIX_FD_ERROR);
  2756. // fall through
  2757. case 0:
  2758. i = 50;
  2759. break;
  2760. default:
  2761. carla_safe_exception("posix fd received abnormal value", __FILE__, __LINE__);
  2762. i = 50;
  2763. break;
  2764. }
  2765. }
  2766. }
  2767. #endif // _POSIX_VERSION
  2768. const uint32_t currentTimeInMs = water::Time::getMillisecondCounter();
  2769. for (LinkedList<HostTimerDetails>::Itenerator it = fTimers.begin2(); it.valid(); it.next())
  2770. {
  2771. HostTimerDetails& timer(it.getValue(kTimerFallbackNC));
  2772. if (currentTimeInMs > timer.lastCallTimeInMs + timer.periodInMs)
  2773. {
  2774. timer.lastCallTimeInMs = currentTimeInMs;
  2775. fExtensions.timer->on_timer(fPlugin, timer.clapId);
  2776. }
  2777. }
  2778. #endif // CLAP_WINDOW_API_NATIVE
  2779. }
  2780. };
  2781. // --------------------------------------------------------------------------------------------------------------------
  2782. CarlaPluginPtr CarlaPlugin::newCLAP(const Initializer& init)
  2783. {
  2784. carla_debug("CarlaPlugin::newCLAP({%p, \"%s\", \"%s\", \"%s\"})",
  2785. init.engine, init.filename, init.name, init.label);
  2786. std::shared_ptr<CarlaPluginCLAP> plugin(new CarlaPluginCLAP(init.engine, init.id));
  2787. if (! plugin->init(plugin, init.filename, init.name, init.label, init.options))
  2788. return nullptr;
  2789. return plugin;
  2790. }
  2791. // -------------------------------------------------------------------------------------------------------------------
  2792. CARLA_BACKEND_END_NAMESPACE