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.

3445 lines
118KB

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