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.

3435 lines
117KB

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