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.

3439 lines
117KB

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