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.

3355 lines
114KB

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