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.

3407 lines
116KB

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