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.

3441 lines
118KB

  1. // SPDX-FileCopyrightText: 2011-2025 Filipe Coelho <falktx@falktx.com>
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include "CarlaPluginInternal.hpp"
  4. #include "CarlaEngine.hpp"
  5. #include "CarlaBackendUtils.hpp"
  6. #include "CarlaClapUtils.hpp"
  7. #include "CarlaMathUtils.hpp"
  8. #include "CarlaPluginUI.hpp"
  9. #ifdef CARLA_OS_MAC
  10. # include "CarlaMacUtils.hpp"
  11. # import <Foundation/Foundation.h>
  12. #endif
  13. #include "water/files/File.h"
  14. #include "water/misc/Time.h"
  15. #if defined(CLAP_WINDOW_API_NATIVE) && defined(_POSIX_VERSION)
  16. # if defined(CARLA_OS_LINUX)
  17. # define CARLA_CLAP_POSIX_EPOLL
  18. # include <sys/epoll.h>
  19. # else
  20. # include <sys/event.h>
  21. # include <sys/types.h>
  22. # endif
  23. #endif
  24. // FIXME
  25. // #ifndef CLAP_WINDOW_API_NATIVE
  26. // #define CLAP_WINDOW_API_NATIVE ""
  27. // #define HAVE_X11 1
  28. // #endif
  29. CARLA_BACKEND_START_NAMESPACE
  30. // --------------------------------------------------------------------------------------------------------------------
  31. struct ClapEventData {
  32. uint16_t clapPortIndex;
  33. uint32_t supportedDialects;
  34. CarlaEngineEventPort* port;
  35. };
  36. struct CarlaPluginClapEventData {
  37. uint32_t portCount;
  38. ClapEventData* portData;
  39. ClapEventData* defaultPort; // either this->portData[x] or pData->portIn/Out
  40. CarlaPluginClapEventData() noexcept
  41. : portCount(0),
  42. portData(nullptr),
  43. defaultPort(nullptr) {}
  44. ~CarlaPluginClapEventData() noexcept
  45. {
  46. CARLA_SAFE_ASSERT_INT(portCount == 0, portCount);
  47. CARLA_SAFE_ASSERT(portData == nullptr);
  48. CARLA_SAFE_ASSERT(defaultPort == nullptr);
  49. }
  50. void createNew(const uint32_t newCount)
  51. {
  52. CARLA_SAFE_ASSERT_INT(portCount == 0, portCount);
  53. CARLA_SAFE_ASSERT_RETURN(portData == nullptr,);
  54. CARLA_SAFE_ASSERT_RETURN(defaultPort == nullptr,);
  55. CARLA_SAFE_ASSERT_RETURN(newCount > 0,);
  56. portData = new ClapEventData[newCount];
  57. portCount = newCount;
  58. defaultPort = nullptr;
  59. }
  60. void clear(CarlaEngineEventPort* const portToIgnore) noexcept
  61. {
  62. if (portData != nullptr)
  63. {
  64. for (uint32_t i=0; i < portCount; ++i)
  65. {
  66. if (portData[i].port != nullptr)
  67. {
  68. if (portData[i].port != portToIgnore)
  69. delete portData[i].port;
  70. portData[i].port = nullptr;
  71. }
  72. }
  73. delete[] portData;
  74. portData = nullptr;
  75. }
  76. portCount = 0;
  77. defaultPort = nullptr;
  78. }
  79. void initBuffers() const noexcept
  80. {
  81. for (uint32_t i=0; i < portCount; ++i)
  82. {
  83. if (portData[i].port != nullptr && (defaultPort == nullptr || portData[i].port != defaultPort->port))
  84. portData[i].port->initBuffer();
  85. }
  86. }
  87. CARLA_DECLARE_NON_COPYABLE(CarlaPluginClapEventData)
  88. };
  89. #ifdef _POSIX_VERSION
  90. // --------------------------------------------------------------------------------------------------------------------
  91. struct HostPosixFileDescriptorDetails {
  92. int hostFd;
  93. int pluginFd;
  94. clap_posix_fd_flags_t flags;
  95. };
  96. static constexpr const HostPosixFileDescriptorDetails kPosixFileDescriptorFallback = { -1, -1, 0x0 };
  97. static /* */ HostPosixFileDescriptorDetails kPosixFileDescriptorFallbackNC = { -1, -1, 0x0 };
  98. #endif
  99. // --------------------------------------------------------------------------------------------------------------------
  100. struct HostTimerDetails {
  101. clap_id clapId;
  102. uint32_t periodInMs;
  103. uint32_t lastCallTimeInMs;
  104. };
  105. static constexpr const HostTimerDetails kTimerFallback = { CLAP_INVALID_ID, 0, 0 };
  106. static /* */ HostTimerDetails kTimerFallbackNC = { CLAP_INVALID_ID, 0, 0 };
  107. // --------------------------------------------------------------------------------------------------------------------
  108. struct carla_clap_host : clap_host_t {
  109. class Callbacks {
  110. public:
  111. virtual ~Callbacks() {}
  112. virtual void clapRequestRestart() = 0;
  113. virtual void clapRequestProcess() = 0;
  114. virtual void clapRequestCallback() = 0;
  115. virtual void clapMarkDirty() = 0;
  116. virtual void clapLatencyChanged() = 0;
  117. #ifdef CLAP_WINDOW_API_NATIVE
  118. // gui
  119. virtual void clapGuiResizeHintsChanged() = 0;
  120. virtual bool clapGuiRequestResize(uint width, uint height) = 0;
  121. virtual bool clapGuiRequestShow() = 0;
  122. virtual bool clapGuiRequestHide() = 0;
  123. virtual void clapGuiClosed(bool wasDestroyed) = 0;
  124. #ifdef _POSIX_VERSION
  125. // posix fd
  126. virtual bool clapRegisterPosixFD(int fd, clap_posix_fd_flags_t flags) = 0;
  127. virtual bool clapModifyPosixFD(int fd, clap_posix_fd_flags_t flags) = 0;
  128. virtual bool clapUnregisterPosixFD(int fd) = 0;
  129. #endif
  130. // timer
  131. virtual bool clapRegisterTimer(uint32_t periodInMs, clap_id* timerId) = 0;
  132. virtual bool clapUnregisterTimer(clap_id timerId) = 0;
  133. #endif
  134. };
  135. Callbacks* const hostCallbacks;
  136. clap_host_latency_t latency;
  137. clap_host_state_t state;
  138. #ifdef CLAP_WINDOW_API_NATIVE
  139. clap_host_gui_t gui;
  140. #ifdef _POSIX_VERSION
  141. clap_host_posix_fd_support_t posixFD;
  142. #endif
  143. clap_host_timer_support_t timer;
  144. #endif
  145. carla_clap_host(Callbacks* const hostCb)
  146. : hostCallbacks(hostCb)
  147. {
  148. clap_version = CLAP_VERSION;
  149. host_data = this;
  150. name = "Carla";
  151. vendor = "falkTX";
  152. url = "https://kx.studio/carla";
  153. version = CARLA_VERSION_STRING;
  154. get_extension = carla_get_extension;
  155. request_restart = carla_request_restart;
  156. request_process = carla_request_process;
  157. request_callback = carla_request_callback;
  158. latency.changed = carla_latency_changed;
  159. state.mark_dirty = carla_mark_dirty;
  160. #ifdef CLAP_WINDOW_API_NATIVE
  161. gui.resize_hints_changed = carla_resize_hints_changed;
  162. gui.request_resize = carla_request_resize;
  163. gui.request_show = carla_request_show;
  164. gui.request_hide = carla_request_hide;
  165. gui.closed = carla_closed;
  166. #ifdef _POSIX_VERSION
  167. posixFD.register_fd = carla_register_fd;
  168. posixFD.modify_fd = carla_modify_fd;
  169. posixFD.unregister_fd = carla_unregister_fd;
  170. #endif
  171. timer.register_timer = carla_register_timer;
  172. timer.unregister_timer = carla_unregister_timer;
  173. #endif
  174. }
  175. static const void* CLAP_ABI carla_get_extension(const clap_host_t* const host, const char* const extension_id)
  176. {
  177. carla_clap_host* const self = static_cast<carla_clap_host*>(host->host_data);
  178. if (std::strcmp(extension_id, CLAP_EXT_LATENCY) == 0)
  179. return &self->latency;
  180. if (std::strcmp(extension_id, CLAP_EXT_STATE) == 0)
  181. return &self->state;
  182. #ifdef CLAP_WINDOW_API_NATIVE
  183. if (std::strcmp(extension_id, CLAP_EXT_GUI) == 0)
  184. return &self->gui;
  185. #ifdef _POSIX_VERSION
  186. if (std::strcmp(extension_id, CLAP_EXT_POSIX_FD_SUPPORT) == 0)
  187. return &self->posixFD;
  188. #endif
  189. if (std::strcmp(extension_id, CLAP_EXT_TIMER_SUPPORT) == 0)
  190. return &self->timer;
  191. #endif
  192. carla_stderr("Plugin requested unsupported CLAP extension '%s'", extension_id);
  193. return nullptr;
  194. }
  195. static void CLAP_ABI carla_request_restart(const clap_host_t* const host)
  196. {
  197. static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapRequestRestart();
  198. }
  199. static void CLAP_ABI carla_request_process(const clap_host_t* const host)
  200. {
  201. static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapRequestProcess();
  202. }
  203. static void CLAP_ABI carla_request_callback(const clap_host_t* const host)
  204. {
  205. static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapRequestCallback();
  206. }
  207. static void CLAP_ABI carla_latency_changed(const clap_host_t* const host)
  208. {
  209. static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapLatencyChanged();
  210. }
  211. static void CLAP_ABI carla_mark_dirty(const clap_host_t* const host)
  212. {
  213. static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapMarkDirty();
  214. }
  215. #ifdef CLAP_WINDOW_API_NATIVE
  216. static void CLAP_ABI carla_resize_hints_changed(const clap_host_t* const host)
  217. {
  218. static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapGuiResizeHintsChanged();
  219. }
  220. static bool CLAP_ABI carla_request_resize(const clap_host_t* const host, const uint32_t width, const uint32_t height)
  221. {
  222. return static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapGuiRequestResize(width, height);
  223. }
  224. static bool CLAP_ABI carla_request_show(const clap_host_t* const host)
  225. {
  226. return static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapGuiRequestShow();
  227. }
  228. static bool CLAP_ABI carla_request_hide(const clap_host_t* const host)
  229. {
  230. return static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapGuiRequestHide();
  231. }
  232. static void CLAP_ABI carla_closed(const clap_host_t* const host, bool was_destroyed)
  233. {
  234. static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapGuiClosed(was_destroyed);
  235. }
  236. #ifdef _POSIX_VERSION
  237. static bool CLAP_ABI carla_register_fd(const clap_host_t* const host, const int fd, const clap_posix_fd_flags_t flags)
  238. {
  239. return static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapRegisterPosixFD(fd, flags);
  240. }
  241. static bool CLAP_ABI carla_modify_fd(const clap_host_t* const host, const int fd, const clap_posix_fd_flags_t flags)
  242. {
  243. return static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapModifyPosixFD(fd, flags);
  244. }
  245. static bool CLAP_ABI carla_unregister_fd(const clap_host_t* const host, const int fd)
  246. {
  247. return static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapUnregisterPosixFD(fd);
  248. }
  249. #endif
  250. static bool CLAP_ABI carla_register_timer(const clap_host_t* const host, const uint32_t period_ms, clap_id* const timer_id)
  251. {
  252. return static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapRegisterTimer(period_ms, timer_id);
  253. }
  254. static bool CLAP_ABI carla_unregister_timer(const clap_host_t* const host, const clap_id timer_id)
  255. {
  256. return static_cast<const carla_clap_host*>(host->host_data)->hostCallbacks->clapUnregisterTimer(timer_id);
  257. }
  258. #endif
  259. };
  260. // --------------------------------------------------------------------------------------------------------------------
  261. struct carla_clap_input_audio_buffers {
  262. clap_audio_buffer_const_t* buffers;
  263. clap_audio_buffer_extra_data_t* extra;
  264. uint32_t count;
  265. carla_clap_input_audio_buffers() noexcept
  266. : buffers(nullptr),
  267. extra(nullptr),
  268. count(0) {}
  269. ~carla_clap_input_audio_buffers()
  270. {
  271. delete[] buffers;
  272. delete[] extra;
  273. }
  274. void realloc(const uint32_t portCount)
  275. {
  276. delete[] buffers;
  277. delete[] extra;
  278. count = portCount;
  279. if (portCount != 0)
  280. {
  281. buffers = new clap_audio_buffer_const_t[portCount];
  282. extra = new clap_audio_buffer_extra_data_t[portCount];
  283. carla_zeroStructs(buffers, portCount);
  284. carla_zeroStructs(extra, portCount);
  285. }
  286. else
  287. {
  288. buffers = nullptr;
  289. extra = nullptr;
  290. }
  291. }
  292. const clap_audio_buffer_t* cast() const noexcept
  293. {
  294. return static_cast<const clap_audio_buffer_t*>(static_cast<const void*>(buffers));
  295. }
  296. };
  297. struct carla_clap_output_audio_buffers {
  298. clap_audio_buffer_t* buffers;
  299. clap_audio_buffer_extra_data_t* extra;
  300. uint32_t count;
  301. carla_clap_output_audio_buffers() noexcept
  302. : buffers(nullptr),
  303. extra(nullptr),
  304. count(0) {}
  305. ~carla_clap_output_audio_buffers()
  306. {
  307. delete[] buffers;
  308. delete[] extra;
  309. }
  310. void realloc(const uint32_t portCount)
  311. {
  312. delete[] buffers;
  313. delete[] extra;
  314. count = portCount;
  315. if (portCount != 0)
  316. {
  317. buffers = new clap_audio_buffer_t[portCount];
  318. extra = new clap_audio_buffer_extra_data_t[portCount];
  319. carla_zeroStructs(buffers, portCount);
  320. carla_zeroStructs(extra, portCount);
  321. }
  322. else
  323. {
  324. buffers = nullptr;
  325. extra = nullptr;
  326. }
  327. }
  328. };
  329. // --------------------------------------------------------------------------------------------------------------------
  330. struct carla_clap_input_events : clap_input_events_t, CarlaPluginClapEventData {
  331. union Event {
  332. clap_event_header_t header;
  333. clap_event_param_value_t param;
  334. clap_event_param_gesture_t gesture;
  335. clap_event_midi_t midi;
  336. clap_event_note_t note;
  337. clap_event_midi_sysex_t sysex;
  338. };
  339. struct ScheduledParameterUpdate {
  340. bool updated;
  341. double value;
  342. clap_id clapId;
  343. void* cookie;
  344. ScheduledParameterUpdate()
  345. : updated(false),
  346. value(0.f),
  347. clapId(0),
  348. cookie(0) {}
  349. };
  350. Event* events;
  351. ScheduledParameterUpdate* updatedParams;
  352. uint32_t numEventsAllocated;
  353. uint32_t numEventsUsed;
  354. uint32_t numParams;
  355. carla_clap_input_events()
  356. : CarlaPluginClapEventData(),
  357. events(nullptr),
  358. updatedParams(nullptr),
  359. numEventsAllocated(0),
  360. numEventsUsed(0),
  361. numParams(0)
  362. {
  363. ctx = this;
  364. size = carla_size;
  365. get = carla_get;
  366. }
  367. ~carla_clap_input_events()
  368. {
  369. delete[] events;
  370. delete[] updatedParams;
  371. }
  372. // called on plugin reload
  373. // NOTE: clapId and cookie must be separately set outside this function
  374. void realloc(CarlaEngineEventPort* const defPortIn, const uint32_t portCount, const uint32_t paramCount)
  375. {
  376. numEventsUsed = 0;
  377. numParams = paramCount;
  378. delete[] events;
  379. delete[] updatedParams;
  380. if (portCount != 0 || paramCount != 0)
  381. {
  382. static_assert(kPluginMaxMidiEvents > MAX_MIDI_NOTE, "Enough space for input events");
  383. numEventsAllocated = paramCount * 2 + kPluginMaxMidiEvents * std::max(1u, portCount);
  384. events = new Event[numEventsAllocated];
  385. updatedParams = new ScheduledParameterUpdate[paramCount];
  386. }
  387. else
  388. {
  389. numEventsAllocated = 0;
  390. events = nullptr;
  391. updatedParams = nullptr;
  392. }
  393. CarlaPluginClapEventData::clear(defPortIn);
  394. if (portCount != 0)
  395. CarlaPluginClapEventData::createNew(portCount);
  396. }
  397. // used for temporary copies (this instance must be empty)
  398. void reallocEqualTo(const carla_clap_input_events& other)
  399. {
  400. numParams = other.numParams;
  401. numEventsAllocated = other.numEventsAllocated;
  402. if (numEventsAllocated != 0)
  403. {
  404. events = new Event[numEventsAllocated];
  405. updatedParams = new ScheduledParameterUpdate[numParams];
  406. for (uint32_t i=0; i<numParams; ++i)
  407. {
  408. updatedParams[i].clapId = other.updatedParams[i].clapId;
  409. updatedParams[i].cookie = other.updatedParams[i].cookie;
  410. }
  411. }
  412. }
  413. void swap(carla_clap_input_events& other)
  414. {
  415. CARLA_SAFE_ASSERT_RETURN(numParams == other.numParams,);
  416. CARLA_SAFE_ASSERT_RETURN(numEventsAllocated == other.numEventsAllocated,);
  417. std::swap(numEventsUsed, other.numEventsUsed);
  418. std::swap(updatedParams, other.updatedParams);
  419. std::swap(events, other.events);
  420. }
  421. const clap_input_events_t* cast() const noexcept
  422. {
  423. return static_cast<const clap_input_events_t*>(this);
  424. }
  425. // called just before plugin processing
  426. void handleScheduledParameterUpdates()
  427. {
  428. uint32_t count = 0;
  429. for (uint32_t i=0; i<numParams; ++i)
  430. {
  431. if (updatedParams[i].updated)
  432. {
  433. events[count++].param = {
  434. { sizeof(clap_event_param_value_t), 0, 0, CLAP_EVENT_PARAM_VALUE, 0 },
  435. updatedParams[i].clapId,
  436. updatedParams[i].cookie,
  437. -1, -1, -1, -1,
  438. updatedParams[i].value
  439. };
  440. updatedParams[i].updated = false;
  441. }
  442. }
  443. numEventsUsed = count;
  444. }
  445. // called when a parameter is set from non-rt thread
  446. void setParamValue(const uint32_t index, const float value) noexcept
  447. {
  448. CARLA_SAFE_ASSERT_RETURN(index < numParams,);
  449. updatedParams[index].value = value;
  450. updatedParams[index].updated = true;
  451. }
  452. // called when a parameter is set from rt thread
  453. void setParamValueRT(const uint32_t index, const float value, const uint32_t frameOffset) noexcept
  454. {
  455. CARLA_SAFE_ASSERT_RETURN(index < numParams,);
  456. if (numEventsUsed == numEventsAllocated)
  457. return;
  458. events[numEventsUsed++].param = {
  459. { sizeof(clap_event_param_value_t), frameOffset, 0, CLAP_EVENT_PARAM_VALUE, CLAP_EVENT_IS_LIVE },
  460. updatedParams[index].clapId,
  461. updatedParams[index].cookie,
  462. -1, -1, -1, -1,
  463. value
  464. };
  465. }
  466. void addSimpleMidiEvent(const bool isLive, const uint16_t port, const uint32_t frameOffset, const uint8_t data[3])
  467. {
  468. if (numEventsUsed == numEventsAllocated)
  469. return;
  470. events[numEventsUsed++].midi = {
  471. { sizeof(clap_event_midi_t), frameOffset, 0, CLAP_EVENT_MIDI, isLive ? (uint32_t)CLAP_EVENT_IS_LIVE : 0u },
  472. port,
  473. { data[0], data[1], data[2] }
  474. };
  475. }
  476. void addSimpleNoteEvent(const bool isLive, const int16_t port, const uint32_t frameOffset,
  477. const uint8_t channel, const uint8_t key, const uint8_t velocity)
  478. {
  479. if (numEventsUsed == numEventsAllocated)
  480. return;
  481. const uint16_t eventType = velocity > 0 ? CLAP_EVENT_NOTE_ON : CLAP_EVENT_NOTE_OFF;
  482. events[numEventsUsed++].note = {
  483. { sizeof(clap_event_note_t), frameOffset, 0, eventType, isLive ? (uint32_t)CLAP_EVENT_IS_LIVE : 0u },
  484. -1,
  485. port,
  486. channel,
  487. key,
  488. static_cast<double>(velocity) / 127.0
  489. };
  490. }
  491. static uint32_t CLAP_ABI carla_size(const clap_input_events_t* const list) noexcept
  492. {
  493. return static_cast<const carla_clap_input_events*>(list->ctx)->numEventsUsed;
  494. }
  495. static const clap_event_header_t* CLAP_ABI carla_get(const clap_input_events_t* const list, const uint32_t index) noexcept
  496. {
  497. return &static_cast<const carla_clap_input_events*>(list->ctx)->events[index].header;
  498. }
  499. };
  500. // --------------------------------------------------------------------------------------------------------------------
  501. struct carla_clap_output_events : clap_output_events_t, CarlaPluginClapEventData {
  502. union Event {
  503. clap_event_header_t header;
  504. clap_event_param_value_t param;
  505. clap_event_midi_t midi;
  506. };
  507. Event* events;
  508. uint32_t numEventsAllocated;
  509. uint32_t numEventsUsed;
  510. carla_clap_output_events()
  511. : events(nullptr),
  512. numEventsAllocated(0),
  513. numEventsUsed(0)
  514. {
  515. ctx = this;
  516. try_push = carla_try_push;
  517. }
  518. ~carla_clap_output_events()
  519. {
  520. delete[] events;
  521. }
  522. // called on plugin reload
  523. void realloc(CarlaEngineEventPort* const defPortOut, const uint32_t portCount, const uint32_t paramCount)
  524. {
  525. numEventsUsed = 0;
  526. delete[] events;
  527. if (portCount != 0 || paramCount != 0)
  528. {
  529. numEventsAllocated = paramCount + kPluginMaxMidiEvents * std::max(1u, portCount);
  530. events = new Event[numEventsAllocated];
  531. }
  532. else
  533. {
  534. numEventsAllocated = 0;
  535. events = nullptr;
  536. }
  537. CarlaPluginClapEventData::clear(defPortOut);
  538. if (portCount != 0)
  539. CarlaPluginClapEventData::createNew(portCount);
  540. }
  541. const clap_output_events_t* cast() const noexcept
  542. {
  543. return static_cast<const clap_output_events_t*>(this);
  544. }
  545. bool tryPush(const clap_event_header_t* const event)
  546. {
  547. if (numEventsUsed == numEventsAllocated)
  548. return false;
  549. Event e;
  550. switch (event->type)
  551. {
  552. case CLAP_EVENT_PARAM_VALUE:
  553. e.param = *static_cast<const clap_event_param_value_t*>(static_cast<const void*>(event));
  554. break;
  555. case CLAP_EVENT_MIDI:
  556. e.midi = *static_cast<const clap_event_midi_t*>(static_cast<const void*>(event));
  557. break;
  558. 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. if (guiExt->can_resize(fPlugin))
  1470. pData->hints |= PLUGIN_HAS_CUSTOM_RESIZABLE_UI;
  1471. }
  1472. else if (guiExt->is_api_supported(fPlugin, CLAP_WINDOW_API_NATIVE, true))
  1473. {
  1474. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  1475. pData->hints |= PLUGIN_NEEDS_UI_MAIN_THREAD;
  1476. }
  1477. }
  1478. #endif
  1479. if (aOuts > 0 && (aIns == aOuts || aIns == 1))
  1480. pData->hints |= PLUGIN_CAN_DRYWET;
  1481. if (aOuts > 0)
  1482. pData->hints |= PLUGIN_CAN_VOLUME;
  1483. if (aOuts >= 2 && aOuts % 2 == 0)
  1484. pData->hints |= PLUGIN_CAN_BALANCE;
  1485. // extra plugin hints
  1486. pData->extraHints = 0x0;
  1487. if (const uint32_t latency = fExtensions.latency != nullptr ? fExtensions.latency->get(fPlugin) : 0)
  1488. {
  1489. fLastKnownLatency = latency;
  1490. pData->client->setLatency(latency);
  1491. #ifndef BUILD_BRIDGE
  1492. pData->latency.recreateBuffers(std::max(aIns, aOuts), latency);
  1493. #endif
  1494. }
  1495. else
  1496. {
  1497. fLastKnownLatency = 0;
  1498. }
  1499. bufferSizeChanged(pData->engine->getBufferSize());
  1500. reloadPrograms(true);
  1501. if (pData->active)
  1502. activate();
  1503. else
  1504. runIdleCallbacksAsNeeded(false);
  1505. carla_debug("CarlaPluginCLAP::reload() - end");
  1506. }
  1507. void reloadPrograms(const bool doInit) override
  1508. {
  1509. carla_debug("CarlaPluginCLAP::reloadPrograms(%s)", bool2str(doInit));
  1510. }
  1511. // -------------------------------------------------------------------
  1512. // Plugin processing
  1513. void activate() noexcept override
  1514. {
  1515. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr,);
  1516. // FIXME check return status
  1517. fPlugin->activate(fPlugin, pData->engine->getSampleRate(), 1, pData->engine->getBufferSize());
  1518. fPlugin->start_processing(fPlugin);
  1519. fNeedsParamFlush = false;
  1520. runIdleCallbacksAsNeeded(false);
  1521. }
  1522. void deactivate() noexcept override
  1523. {
  1524. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr,);
  1525. // FIXME check return status
  1526. fPlugin->stop_processing(fPlugin);
  1527. fPlugin->deactivate(fPlugin);
  1528. runIdleCallbacksAsNeeded(false);
  1529. }
  1530. void process(const float* const* const audioIn,
  1531. float** const audioOut,
  1532. const float* const* const cvIn,
  1533. float** const,
  1534. const uint32_t frames) override
  1535. {
  1536. // --------------------------------------------------------------------------------------------------------
  1537. // Check if active
  1538. if (! pData->active)
  1539. {
  1540. // disable any output sound
  1541. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1542. carla_zeroFloats(audioOut[i], frames);
  1543. return;
  1544. }
  1545. // --------------------------------------------------------------------------------------------------------
  1546. // Check buffers
  1547. CARLA_SAFE_ASSERT_RETURN(frames > 0,);
  1548. if (pData->audioIn.count > 0)
  1549. {
  1550. CARLA_SAFE_ASSERT_RETURN(audioIn != nullptr,);
  1551. }
  1552. if (pData->audioOut.count > 0)
  1553. {
  1554. CARLA_SAFE_ASSERT_RETURN(audioOut != nullptr,);
  1555. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1556. CARLA_SAFE_ASSERT_RETURN(fAudioOutBuffers != nullptr,);
  1557. #endif
  1558. }
  1559. // --------------------------------------------------------------------------------------------------------
  1560. // Set audio buffers
  1561. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1562. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1563. carla_zeroFloats(fAudioOutBuffers[i], frames);
  1564. #endif
  1565. // --------------------------------------------------------------------------------------------------------
  1566. // Try lock, silence otherwise
  1567. if (pData->engine->isOffline())
  1568. {
  1569. pData->singleMutex.lock();
  1570. }
  1571. else if (! pData->singleMutex.tryLock())
  1572. {
  1573. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1574. carla_zeroFloats(audioOut[i], frames);
  1575. return;
  1576. }
  1577. // --------------------------------------------------------------------------------------------------------
  1578. fInputEvents.handleScheduledParameterUpdates();
  1579. // --------------------------------------------------------------------------------------------------------
  1580. // Check if needs reset
  1581. if (pData->needsReset)
  1582. {
  1583. // TODO alternative if plugin does not support CLAP_NOTE_DIALECT_MIDI
  1584. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1585. {
  1586. for (uint32_t p=0; p<fInputEvents.portCount; ++p)
  1587. {
  1588. const uint16_t port = fInputEvents.portData[p].clapPortIndex;
  1589. for (uint8_t i=0, k=fInputEvents.numEventsUsed; i < MAX_MIDI_CHANNELS; ++i)
  1590. {
  1591. fInputEvents.events[k + i].midi = {
  1592. { sizeof(clap_event_midi_t), 0, 0, CLAP_EVENT_MIDI, 0 },
  1593. port,
  1594. {
  1595. uint8_t(MIDI_STATUS_CONTROL_CHANGE | (i & MIDI_CHANNEL_BIT)),
  1596. MIDI_CONTROL_ALL_NOTES_OFF, 0
  1597. }
  1598. };
  1599. fInputEvents.events[k + MAX_MIDI_CHANNELS + i].midi = {
  1600. { sizeof(clap_event_midi_t), 0, 0, CLAP_EVENT_MIDI, 0 },
  1601. port,
  1602. {
  1603. uint8_t(MIDI_STATUS_CONTROL_CHANGE | (i & MIDI_CHANNEL_BIT)),
  1604. MIDI_CONTROL_ALL_SOUND_OFF, 0
  1605. }
  1606. };
  1607. }
  1608. fInputEvents.numEventsUsed += MAX_MIDI_CHANNELS * 2;
  1609. }
  1610. }
  1611. else if (pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS)
  1612. {
  1613. for (uint32_t p=0; p<fInputEvents.portCount; ++p)
  1614. {
  1615. const uint16_t port = fInputEvents.portData[p].clapPortIndex;
  1616. for (uint8_t i=0, k=fInputEvents.numEventsUsed; i < MAX_MIDI_NOTE; ++i)
  1617. {
  1618. fInputEvents.events[k + i].midi = {
  1619. { sizeof(clap_event_midi_t), 0, 0, CLAP_EVENT_MIDI, 0 },
  1620. port,
  1621. {
  1622. uint8_t(MIDI_STATUS_NOTE_OFF | (pData->ctrlChannel & MIDI_CHANNEL_BIT)),
  1623. i, 0
  1624. }
  1625. };
  1626. }
  1627. fInputEvents.numEventsUsed += MAX_MIDI_NOTE;
  1628. }
  1629. }
  1630. pData->needsReset = false;
  1631. }
  1632. // --------------------------------------------------------------------------------------------------------
  1633. // Set TimeInfo
  1634. const EngineTimeInfo timeInfo(pData->engine->getTimeInfo());
  1635. const double sampleRate = pData->engine->getSampleRate();
  1636. clap_event_transport_t clapTransport = {
  1637. { sizeof(clap_event_transport_t), 0, 0, CLAP_EVENT_TRANSPORT, 0 },
  1638. 0x0, // flags
  1639. 0, // song_pos_beats, position in beats
  1640. 0, // song_pos_seconds, position in seconds
  1641. 0.0, // tempo, in bpm
  1642. 0.0, // tempo_inc, tempo increment for each samples and until the next time info event
  1643. 0, // loop_start_beats
  1644. 0, // loop_end_beats
  1645. 0, // loop_start_seconds
  1646. 0, // loop_end_seconds
  1647. 0, // bar_start, start pos of the current bar
  1648. 0, // bar_number, bar at song pos 0 has the number 0
  1649. 0, // tsig_num, time signature numerator
  1650. 0, // tsig_denom, time signature denominator
  1651. };
  1652. if (timeInfo.playing)
  1653. clapTransport.flags |= CLAP_TRANSPORT_IS_PLAYING;
  1654. const double positionSeconds = static_cast<double>(timeInfo.frame) / sampleRate;
  1655. clapTransport.song_pos_seconds = std::round(CLAP_SECTIME_FACTOR * positionSeconds);
  1656. clapTransport.flags |= CLAP_TRANSPORT_HAS_SECONDS_TIMELINE;
  1657. if (timeInfo.bbt.valid)
  1658. {
  1659. CARLA_SAFE_ASSERT_INT(timeInfo.bbt.bar > 0, timeInfo.bbt.bar);
  1660. CARLA_SAFE_ASSERT_INT(timeInfo.bbt.beat > 0, timeInfo.bbt.beat);
  1661. const double barStart = static_cast<double>(timeInfo.bbt.beatsPerBar) * (timeInfo.bbt.bar - 1);
  1662. const double positionBeats = static_cast<double>(timeInfo.frame)
  1663. / (sampleRate * 60 / timeInfo.bbt.beatsPerMinute);
  1664. // Bar/Beats
  1665. clapTransport.bar_start = std::round(CLAP_BEATTIME_FACTOR * barStart);
  1666. clapTransport.bar_number = timeInfo.bbt.bar - 1;
  1667. clapTransport.song_pos_beats = std::round(CLAP_BEATTIME_FACTOR * positionBeats);
  1668. clapTransport.flags |= CLAP_TRANSPORT_HAS_BEATS_TIMELINE;
  1669. // Tempo
  1670. clapTransport.tempo = timeInfo.bbt.beatsPerMinute;
  1671. clapTransport.flags |= CLAP_TRANSPORT_HAS_TEMPO;
  1672. // Time Signature
  1673. clapTransport.tsig_num = static_cast<uint16_t>(timeInfo.bbt.beatsPerBar + 0.5f);
  1674. clapTransport.tsig_denom = static_cast<uint16_t>(timeInfo.bbt.beatType + 0.5f);
  1675. clapTransport.flags |= CLAP_TRANSPORT_HAS_TIME_SIGNATURE;
  1676. }
  1677. else
  1678. {
  1679. // Tempo
  1680. clapTransport.tempo = 120.0;
  1681. clapTransport.flags |= CLAP_TRANSPORT_HAS_TEMPO;
  1682. // Time Signature
  1683. clapTransport.tsig_num = 4;
  1684. clapTransport.tsig_denom = 4;
  1685. clapTransport.flags |= CLAP_TRANSPORT_HAS_TIME_SIGNATURE;
  1686. }
  1687. // --------------------------------------------------------------------------------------------------------
  1688. // Event Input (main port)
  1689. if (pData->event.portIn != nullptr)
  1690. {
  1691. // ----------------------------------------------------------------------------------------------------
  1692. // MIDI Input (External)
  1693. if (pData->extNotes.mutex.tryLock())
  1694. {
  1695. if (fInputEvents.portCount == 0)
  1696. {
  1697. // does not handle MIDI
  1698. pData->extNotes.data.clear();
  1699. }
  1700. else
  1701. {
  1702. ExternalMidiNote note = { -1, 0, 0 };
  1703. const uint16_t p = fInputEvents.portData[0].clapPortIndex;
  1704. for (; fInputEvents.numEventsUsed < fInputEvents.numEventsAllocated && ! pData->extNotes.data.isEmpty();)
  1705. {
  1706. note = pData->extNotes.data.getFirst(note, true);
  1707. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  1708. if (fInputEvents.portData[0].supportedDialects & CLAP_NOTE_DIALECT_MIDI)
  1709. {
  1710. const uint8_t data[3] = {
  1711. uint8_t((note.velo > 0 ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF) | (note.channel & MIDI_CHANNEL_BIT)),
  1712. note.note,
  1713. note.velo
  1714. };
  1715. fInputEvents.addSimpleMidiEvent(true, p, 0, data);
  1716. }
  1717. else
  1718. {
  1719. fInputEvents.addSimpleNoteEvent(true, -1, 0, note.channel, note.note, note.velo);
  1720. }
  1721. }
  1722. }
  1723. pData->extNotes.mutex.unlock();
  1724. } // End of MIDI Input (External)
  1725. // ----------------------------------------------------------------------------------------------------
  1726. // Event Input (System)
  1727. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1728. bool allNotesOffSent = false;
  1729. #endif
  1730. uint32_t previousEventTime = 0;
  1731. uint32_t nextBankId;
  1732. if (pData->midiprog.current >= 0 && pData->midiprog.count > 0)
  1733. nextBankId = pData->midiprog.data[pData->midiprog.current].bank;
  1734. else
  1735. nextBankId = 0;
  1736. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1737. if (cvIn != nullptr && pData->event.cvSourcePorts != nullptr)
  1738. pData->event.cvSourcePorts->initPortBuffers(cvIn + pData->cvIn.count, frames, true, pData->event.portIn);
  1739. #endif
  1740. const uint32_t numSysEvents = pData->event.portIn->getEventCount();
  1741. for (uint32_t i=0; i < numSysEvents; ++i)
  1742. {
  1743. EngineEvent& event(pData->event.portIn->getEvent(i));
  1744. uint32_t eventTime = event.time;
  1745. CARLA_SAFE_ASSERT_UINT2_CONTINUE(eventTime < frames, eventTime, frames);
  1746. if (eventTime < previousEventTime)
  1747. {
  1748. carla_stderr2("Timing error, eventTime:%u < previousEventTime:%u for '%s'",
  1749. eventTime, previousEventTime, pData->name);
  1750. eventTime = previousEventTime;
  1751. }
  1752. previousEventTime = eventTime;
  1753. switch (event.type)
  1754. {
  1755. case kEngineEventTypeNull:
  1756. break;
  1757. case kEngineEventTypeControl: {
  1758. EngineControlEvent& ctrlEvent(event.ctrl);
  1759. switch (ctrlEvent.type)
  1760. {
  1761. case kEngineControlEventTypeNull:
  1762. break;
  1763. case kEngineControlEventTypeParameter: {
  1764. float value;
  1765. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1766. // non-midi
  1767. if (event.channel == kEngineEventNonMidiChannel)
  1768. {
  1769. const uint32_t k = ctrlEvent.param;
  1770. CARLA_SAFE_ASSERT_CONTINUE(k < pData->param.count);
  1771. ctrlEvent.handled = true;
  1772. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  1773. setParameterValueRT(k, value, event.time, true);
  1774. continue;
  1775. }
  1776. // Control backend stuff
  1777. if (event.channel == pData->ctrlChannel)
  1778. {
  1779. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  1780. {
  1781. ctrlEvent.handled = true;
  1782. value = ctrlEvent.normalizedValue;
  1783. setDryWetRT(value, true);
  1784. }
  1785. else if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  1786. {
  1787. ctrlEvent.handled = true;
  1788. value = ctrlEvent.normalizedValue*127.0f/100.0f;
  1789. setVolumeRT(value, true);
  1790. }
  1791. else if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  1792. {
  1793. float left, right;
  1794. value = ctrlEvent.normalizedValue/0.5f - 1.0f;
  1795. if (value < 0.0f)
  1796. {
  1797. left = -1.0f;
  1798. right = (value*2.0f)+1.0f;
  1799. }
  1800. else if (value > 0.0f)
  1801. {
  1802. left = (value*2.0f)-1.0f;
  1803. right = 1.0f;
  1804. }
  1805. else
  1806. {
  1807. left = -1.0f;
  1808. right = 1.0f;
  1809. }
  1810. ctrlEvent.handled = true;
  1811. setBalanceLeftRT(left, true);
  1812. setBalanceRightRT(right, true);
  1813. }
  1814. }
  1815. #endif
  1816. // Control plugin parameters
  1817. uint32_t k;
  1818. for (k=0; k < pData->param.count; ++k)
  1819. {
  1820. if (pData->param.data[k].midiChannel != event.channel)
  1821. continue;
  1822. if (pData->param.data[k].mappedControlIndex != ctrlEvent.param)
  1823. continue;
  1824. if (pData->param.data[k].type != PARAMETER_INPUT)
  1825. continue;
  1826. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMATABLE) == 0)
  1827. continue;
  1828. ctrlEvent.handled = true;
  1829. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  1830. setParameterValueRT(k, value, event.time, true);
  1831. }
  1832. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param < MAX_MIDI_VALUE)
  1833. {
  1834. uint8_t midiData[3];
  1835. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1836. midiData[1] = uint8_t(ctrlEvent.param);
  1837. midiData[2] = uint8_t(ctrlEvent.normalizedValue*127.0f + 0.5f);
  1838. fInputEvents.addSimpleMidiEvent(true, 0, eventTime, midiData);
  1839. }
  1840. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1841. if (! ctrlEvent.handled)
  1842. checkForMidiLearn(event);
  1843. #endif
  1844. break;
  1845. } // case kEngineControlEventTypeParameter
  1846. case kEngineControlEventTypeMidiBank:
  1847. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  1848. {
  1849. if (event.channel == pData->ctrlChannel)
  1850. nextBankId = ctrlEvent.param;
  1851. }
  1852. else if (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES)
  1853. {
  1854. uint8_t midiData[3];
  1855. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1856. midiData[1] = MIDI_CONTROL_BANK_SELECT;
  1857. midiData[2] = uint8_t(ctrlEvent.param);
  1858. fInputEvents.addSimpleMidiEvent(true, 0, eventTime, midiData);
  1859. }
  1860. break;
  1861. case kEngineControlEventTypeMidiProgram:
  1862. if (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES)
  1863. {
  1864. if (event.channel == pData->ctrlChannel)
  1865. {
  1866. const uint32_t nextProgramId(ctrlEvent.param);
  1867. for (uint32_t k=0; k < pData->midiprog.count; ++k)
  1868. {
  1869. if (pData->midiprog.data[k].bank == nextBankId && pData->midiprog.data[k].program == nextProgramId)
  1870. {
  1871. setMidiProgramRT(k, true);
  1872. break;
  1873. }
  1874. }
  1875. }
  1876. }
  1877. else if (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES)
  1878. {
  1879. uint8_t midiData[3];
  1880. midiData[0] = uint8_t(MIDI_STATUS_PROGRAM_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1881. midiData[1] = uint8_t(ctrlEvent.param);
  1882. midiData[2] = 0;
  1883. fInputEvents.addSimpleMidiEvent(true, 0, eventTime, midiData);
  1884. }
  1885. break;
  1886. case kEngineControlEventTypeAllSoundOff:
  1887. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1888. {
  1889. uint8_t midiData[3];
  1890. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1891. midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  1892. midiData[2] = 0;
  1893. fInputEvents.addSimpleMidiEvent(true, 0, eventTime, midiData);
  1894. }
  1895. break;
  1896. case kEngineControlEventTypeAllNotesOff:
  1897. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1898. {
  1899. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1900. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  1901. {
  1902. allNotesOffSent = true;
  1903. postponeRtAllNotesOff();
  1904. }
  1905. #endif
  1906. uint8_t midiData[3];
  1907. midiData[0] = uint8_t(MIDI_STATUS_CONTROL_CHANGE | (event.channel & MIDI_CHANNEL_BIT));
  1908. midiData[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  1909. midiData[2] = 0;
  1910. fInputEvents.addSimpleMidiEvent(true, 0, eventTime, midiData);
  1911. }
  1912. break;
  1913. } // switch (ctrlEvent.type)
  1914. break;
  1915. } // case kEngineEventTypeControl
  1916. case kEngineEventTypeMidi: {
  1917. const EngineMidiEvent& midiEvent(event.midi);
  1918. if (midiEvent.size > 3)
  1919. continue;
  1920. CARLA_SAFE_ASSERT_BREAK(midiEvent.port < fInputEvents.portCount);
  1921. const uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiEvent.data));
  1922. if (status == MIDI_STATUS_NOTE_OFF || status == MIDI_STATUS_NOTE_ON)
  1923. {
  1924. if (pData->options & PLUGIN_OPTION_SKIP_SENDING_NOTES)
  1925. continue;
  1926. // plugin does not support MIDI, send a simple note instead
  1927. if ((fInputEvents.portData[midiEvent.port].supportedDialects & CLAP_NOTE_DIALECT_MIDI) == 0x0)
  1928. {
  1929. fInputEvents.addSimpleNoteEvent(true, midiEvent.port, event.time,
  1930. event.channel, midiEvent.data[1], midiEvent.data[2]);
  1931. }
  1932. }
  1933. if (fInputEvents.portData[midiEvent.port].supportedDialects & CLAP_NOTE_DIALECT_MIDI)
  1934. {
  1935. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  1936. continue;
  1937. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  1938. continue;
  1939. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  1940. continue;
  1941. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  1942. continue;
  1943. // put back channel in data
  1944. uint8_t midiData[3] = { uint8_t(status | (event.channel & MIDI_CHANNEL_BIT)), 0, 0 };
  1945. switch (midiEvent.size)
  1946. {
  1947. case 3:
  1948. midiData[2] = midiEvent.data[2];
  1949. // fall through
  1950. case 2:
  1951. midiData[1] = midiEvent.data[1];
  1952. break;
  1953. }
  1954. fInputEvents.addSimpleMidiEvent(true, midiEvent.port, eventTime, midiData);
  1955. }
  1956. switch (status)
  1957. {
  1958. case MIDI_STATUS_NOTE_ON:
  1959. if (midiEvent.data[2] != 0)
  1960. {
  1961. pData->postponeNoteOnRtEvent(true, event.channel, midiEvent.data[1], midiEvent.data[2]);
  1962. break;
  1963. }
  1964. // fall through
  1965. case MIDI_STATUS_NOTE_OFF:
  1966. pData->postponeNoteOffRtEvent(true, event.channel, midiEvent.data[1]);
  1967. break;
  1968. }
  1969. } break;
  1970. } // switch (event.type)
  1971. }
  1972. pData->postRtEvents.trySplice();
  1973. } // End of Event Input (main port)
  1974. // --------------------------------------------------------------------------------------------------------
  1975. // Event input (multi MIDI port)
  1976. if (fInputEvents.portCount > 1)
  1977. {
  1978. // TODO
  1979. }
  1980. // --------------------------------------------------------------------------------------------------------
  1981. // Plugin processing
  1982. for (uint32_t i=0; i<fInputAudioBuffers.count; ++i)
  1983. fInputAudioBuffers.buffers[i].data32 = audioIn + fInputAudioBuffers.extra[i].offset;
  1984. for (uint32_t i=0; i<fOutputAudioBuffers.count; ++i)
  1985. {
  1986. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1987. fOutputAudioBuffers.buffers[i].data32 = fAudioOutBuffers + fOutputAudioBuffers.extra[i].offset;
  1988. #else
  1989. fOutputAudioBuffers.buffers[i].data32 = audioOut + fOutputAudioBuffers.extra[i].offset;
  1990. #endif
  1991. }
  1992. const clap_process_t process = {
  1993. static_cast<int64_t>(timeInfo.frame),
  1994. frames,
  1995. &clapTransport,
  1996. fInputAudioBuffers.cast(),
  1997. fOutputAudioBuffers.buffers,
  1998. fInputAudioBuffers.count,
  1999. fOutputAudioBuffers.count,
  2000. fInputEvents.cast(),
  2001. fOutputEvents.cast()
  2002. };
  2003. fPlugin->process(fPlugin, &process);
  2004. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2005. // --------------------------------------------------------------------------------------------------------
  2006. // Post-processing (dry/wet, volume and balance)
  2007. {
  2008. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  2009. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  2010. const bool isMono = (pData->audioIn.count == 1);
  2011. bool isPair;
  2012. float bufValue;
  2013. float* const oldBufLeft = pData->postProc.extraBuffer;
  2014. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  2015. {
  2016. // Dry/Wet
  2017. if (doDryWet)
  2018. {
  2019. const uint32_t c = isMono ? 0 : i;
  2020. for (uint32_t k=0; k < frames; ++k)
  2021. {
  2022. bufValue = audioIn[c][k];
  2023. fAudioOutBuffers[i][k] = (fAudioOutBuffers[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  2024. }
  2025. }
  2026. // Balance
  2027. if (doBalance)
  2028. {
  2029. isPair = (i % 2 == 0);
  2030. if (isPair)
  2031. {
  2032. CARLA_ASSERT(i+1 < pData->audioOut.count);
  2033. carla_copyFloats(oldBufLeft, fAudioOutBuffers[i], frames);
  2034. }
  2035. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  2036. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  2037. for (uint32_t k=0; k < frames; ++k)
  2038. {
  2039. if (isPair)
  2040. {
  2041. // left
  2042. fAudioOutBuffers[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  2043. fAudioOutBuffers[i][k] += fAudioOutBuffers[i+1][k] * (1.0f - balRangeR);
  2044. }
  2045. else
  2046. {
  2047. // right
  2048. fAudioOutBuffers[i][k] = fAudioOutBuffers[i][k] * balRangeR;
  2049. fAudioOutBuffers[i][k] += oldBufLeft[k] * balRangeL;
  2050. }
  2051. }
  2052. }
  2053. // Volume (and buffer copy)
  2054. {
  2055. for (uint32_t k=0; k < frames; ++k)
  2056. audioOut[i][k] = fAudioOutBuffers[i][k] * pData->postProc.volume;
  2057. }
  2058. }
  2059. } // End of Post-processing
  2060. #endif // BUILD_BRIDGE_ALTERNATIVE_ARCH
  2061. // --------------------------------------------------------------------------------------------------------
  2062. pData->singleMutex.unlock();
  2063. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2064. // --------------------------------------------------------------------------------------------------------
  2065. // Control Output
  2066. if (pData->event.portOut != nullptr && fExtensions.params != nullptr)
  2067. {
  2068. uint8_t channel;
  2069. uint16_t param;
  2070. double value;
  2071. for (uint32_t k=0; k < pData->param.count; ++k)
  2072. {
  2073. if (pData->param.data[k].type != PARAMETER_OUTPUT)
  2074. continue;
  2075. if (pData->param.data[k].mappedControlIndex <= 0)
  2076. continue;
  2077. if (!fExtensions.params->get_value(fPlugin, pData->param.data[k].rindex, &value))
  2078. continue;
  2079. channel = pData->param.data[k].midiChannel;
  2080. param = static_cast<uint16_t>(pData->param.data[k].mappedControlIndex);
  2081. value = pData->param.ranges[k].getNormalizedValue(value);
  2082. pData->event.portOut->writeControlEvent(0, channel,
  2083. kEngineControlEventTypeParameter, param, -1,
  2084. value);
  2085. }
  2086. } // End of Control Output
  2087. #endif
  2088. // --------------------------------------------------------------------------------------------------------
  2089. // Events/MIDI Output
  2090. for (uint32_t i=0; i<fOutputEvents.numEventsUsed; ++i)
  2091. {
  2092. const carla_clap_output_events::Event& ev(fOutputEvents.events[i]);
  2093. switch (ev.header.type)
  2094. {
  2095. case CLAP_EVENT_PARAM_VALUE:
  2096. for (uint32_t j=0; j<pData->param.count; ++j)
  2097. {
  2098. if (pData->param.data[j].rindex != static_cast<int32_t>(ev.param.param_id))
  2099. continue;
  2100. pData->postponeParameterChangeRtEvent(true, static_cast<int32_t>(j), ev.param.value);
  2101. break;
  2102. }
  2103. break;
  2104. case CLAP_EVENT_MIDI:
  2105. for (uint32_t j=0; j<fOutputEvents.portCount; ++j)
  2106. {
  2107. if (fOutputEvents.portData[j].clapPortIndex != ev.midi.port_index)
  2108. continue;
  2109. fOutputEvents.portData[j].port->writeMidiEvent(ev.midi.header.time, 3, ev.midi.data);
  2110. break;
  2111. }
  2112. break;
  2113. }
  2114. }
  2115. fOutputEvents.numEventsUsed = 0;
  2116. // --------------------------------------------------------------------------------------------------------
  2117. #ifdef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2118. return;
  2119. // unused
  2120. (void)cvIn;
  2121. #endif
  2122. }
  2123. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2124. void bufferSizeChanged(const uint32_t newBufferSize) override
  2125. {
  2126. CARLA_ASSERT_INT(newBufferSize > 0, newBufferSize);
  2127. carla_debug("CarlaPluginCLAP::bufferSizeChanged(%i)", newBufferSize);
  2128. if (pData->active)
  2129. deactivate();
  2130. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  2131. {
  2132. if (fAudioOutBuffers[i] != nullptr)
  2133. delete[] fAudioOutBuffers[i];
  2134. fAudioOutBuffers[i] = new float[newBufferSize];
  2135. }
  2136. if (pData->active)
  2137. activate();
  2138. CarlaPlugin::bufferSizeChanged(newBufferSize);
  2139. }
  2140. #endif
  2141. // -------------------------------------------------------------------
  2142. // Plugin buffers
  2143. void initBuffers() const noexcept override
  2144. {
  2145. fInputEvents.initBuffers();
  2146. fOutputEvents.initBuffers();
  2147. CarlaPlugin::initBuffers();
  2148. }
  2149. void clearBuffers() noexcept override
  2150. {
  2151. carla_debug("CarlaPluginCLAP::clearBuffers() - start");
  2152. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2153. if (fAudioOutBuffers != nullptr)
  2154. {
  2155. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  2156. {
  2157. if (fAudioOutBuffers[i] != nullptr)
  2158. {
  2159. delete[] fAudioOutBuffers[i];
  2160. fAudioOutBuffers[i] = nullptr;
  2161. }
  2162. }
  2163. delete[] fAudioOutBuffers;
  2164. fAudioOutBuffers = nullptr;
  2165. }
  2166. #endif
  2167. fInputEvents.clear(pData->event.portIn);
  2168. fOutputEvents.clear(pData->event.portOut);
  2169. CarlaPlugin::clearBuffers();
  2170. carla_debug("CarlaPluginCLAP::clearBuffers() - end");
  2171. }
  2172. // -------------------------------------------------------------------
  2173. // Post-poned UI Stuff
  2174. // nothing
  2175. // -------------------------------------------------------------------
  2176. protected:
  2177. #ifdef CLAP_WINDOW_API_NATIVE
  2178. void handlePluginUIClosed() override
  2179. {
  2180. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  2181. carla_stdout("CarlaPluginCLAP::handlePluginUIClosed()");
  2182. fUI.shouldClose = true;
  2183. }
  2184. void handlePluginUIResized(const uint width, const uint height) override
  2185. {
  2186. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  2187. carla_stdout("CarlaPluginCLAP::handlePluginUIResized(%u, %u | vs %u %u) %d %s %s",
  2188. width, height,
  2189. fUI.width, fUI.height,
  2190. fUI.isResizingFromPlugin, bool2str(fUI.isResizingFromInit), bool2str(fUI.isResizingFromHost));
  2191. if (fExtensions.gui == nullptr)
  2192. return;
  2193. if (fUI.isResizingFromPlugin != 0)
  2194. {
  2195. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.width == width, fUI.width, width,);
  2196. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.height == height, fUI.height, height,);
  2197. fUI.isResizingFromPlugin = 2;
  2198. return;
  2199. }
  2200. if (fUI.isResizingFromInit)
  2201. {
  2202. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.width == width, fUI.width, width,);
  2203. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.height == height, fUI.height, height,);
  2204. fUI.isResizingFromInit = false;
  2205. return;
  2206. }
  2207. if (fUI.isResizingFromHost)
  2208. {
  2209. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.width == width, fUI.width, width,);
  2210. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.height == height, fUI.height, height,);
  2211. fUI.isResizingFromHost = false;
  2212. return;
  2213. }
  2214. if (fUI.width != width || fUI.height != height)
  2215. {
  2216. uint width2 = width;
  2217. uint height2 = height;
  2218. if (fExtensions.gui->adjust_size(fPlugin, &width2, &height2))
  2219. {
  2220. if (width2 != width || height2 != height)
  2221. {
  2222. fUI.isResizingFromHost = true;
  2223. fUI.width = width2;
  2224. fUI.height = height2;
  2225. fUI.window->setSize(width2, height2, false, false);
  2226. }
  2227. else
  2228. {
  2229. fExtensions.gui->set_size(fPlugin, width2, height2);
  2230. }
  2231. }
  2232. }
  2233. }
  2234. #endif
  2235. // -------------------------------------------------------------------
  2236. void clapRequestRestart() override
  2237. {
  2238. carla_stdout("CarlaPluginCLAP::clapRequestRestart()");
  2239. fNeedsRestart = true;
  2240. }
  2241. void clapRequestProcess() override
  2242. {
  2243. carla_stdout("CarlaPluginCLAP::clapRequestProcess()");
  2244. fNeedsProcess = true;
  2245. }
  2246. void clapRequestCallback() override
  2247. {
  2248. carla_stdout("CarlaPluginCLAP::clapRequestCallback()");
  2249. if (fPlugin->on_main_thread != nullptr)
  2250. fNeedsIdleCallback = true;
  2251. }
  2252. // -------------------------------------------------------------------
  2253. void clapLatencyChanged() override
  2254. {
  2255. carla_stdout("CarlaPluginCLAP::clapLatencyChanged()");
  2256. CARLA_SAFE_ASSERT_RETURN(fExtensions.latency != nullptr,);
  2257. fLastKnownLatency = fExtensions.latency->get(fPlugin);
  2258. }
  2259. // -------------------------------------------------------------------
  2260. void clapMarkDirty() override
  2261. {
  2262. carla_stdout("CarlaPluginCLAP::clapMarkDirty()");
  2263. }
  2264. // -------------------------------------------------------------------
  2265. #ifdef CLAP_WINDOW_API_NATIVE
  2266. void clapGuiResizeHintsChanged() override
  2267. {
  2268. carla_stdout("CarlaPluginCLAP::clapGuiResizeHintsChanged()");
  2269. }
  2270. bool clapGuiRequestResize(const uint width, const uint height) override
  2271. {
  2272. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr, false);
  2273. carla_stdout("CarlaPluginCLAP::hostRequestResize(%u, %u)", width, height);
  2274. fUI.isResizingFromPlugin = 3;
  2275. fUI.width = width;
  2276. fUI.height = height;
  2277. fUI.window->setSize(width, height, true, false);
  2278. return true;
  2279. }
  2280. bool clapGuiRequestShow() override
  2281. {
  2282. carla_stdout("CarlaPluginCLAP::clapGuiRequestShow()");
  2283. return false;
  2284. }
  2285. bool clapGuiRequestHide() override
  2286. {
  2287. carla_stdout("CarlaPluginCLAP::clapGuiRequestHide()");
  2288. return false;
  2289. }
  2290. void clapGuiClosed(const bool wasDestroyed) override
  2291. {
  2292. carla_stdout("CarlaPluginCLAP::clapGuiClosed(%s)", bool2str(wasDestroyed));
  2293. CARLA_SAFE_ASSERT_RETURN(!fUI.isEmbed,);
  2294. CARLA_SAFE_ASSERT_RETURN(fUI.isVisible,);
  2295. fUI.isVisible = false;
  2296. if (wasDestroyed)
  2297. {
  2298. CARLA_SAFE_ASSERT_RETURN(fUI.isCreated,);
  2299. fExtensions.gui->destroy(fPlugin);
  2300. fUI.isCreated = false;
  2301. }
  2302. pData->engine->callback(true, true,
  2303. ENGINE_CALLBACK_UI_STATE_CHANGED,
  2304. pData->id,
  2305. 0,
  2306. 0, 0, 0.0f, nullptr);
  2307. }
  2308. // -------------------------------------------------------------------
  2309. #ifdef _POSIX_VERSION
  2310. bool clapRegisterPosixFD(const int fd, const clap_posix_fd_flags_t flags) override
  2311. {
  2312. carla_stdout("CarlaPluginCLAP::clapRegisterPosixFD(%i, %x)", fd, flags);
  2313. // NOTE some plugins wont have their posix fd extension ready when first loaded, so try again here
  2314. if (fExtensions.posixFD == nullptr)
  2315. {
  2316. const clap_plugin_posix_fd_support_t* const posixFdExt = static_cast<const clap_plugin_posix_fd_support_t*>(
  2317. fPlugin->get_extension(fPlugin, CLAP_EXT_POSIX_FD_SUPPORT));
  2318. if (posixFdExt != nullptr && posixFdExt->on_fd != nullptr)
  2319. fExtensions.posixFD = posixFdExt;
  2320. }
  2321. CARLA_SAFE_ASSERT_RETURN(fExtensions.posixFD != nullptr, false);
  2322. // FIXME events only driven as long as UI is open
  2323. // CARLA_SAFE_ASSERT_RETURN(fUI.isCreated, false);
  2324. if (flags & (CLAP_POSIX_FD_READ|CLAP_POSIX_FD_WRITE))
  2325. {
  2326. #ifdef CARLA_CLAP_POSIX_EPOLL
  2327. const int hostFd = ::epoll_create1(0);
  2328. #else
  2329. const int hostFd = ::kqueue();
  2330. #endif
  2331. CARLA_SAFE_ASSERT_RETURN(hostFd >= 0, false);
  2332. #ifdef CARLA_CLAP_POSIX_EPOLL
  2333. struct ::epoll_event ev = {};
  2334. if (flags & CLAP_POSIX_FD_READ)
  2335. ev.events |= EPOLLIN;
  2336. if (flags & CLAP_POSIX_FD_WRITE)
  2337. ev.events |= EPOLLOUT;
  2338. ev.data.fd = fd;
  2339. if (::epoll_ctl(hostFd, EPOLL_CTL_ADD, fd, &ev) < 0)
  2340. {
  2341. ::close(hostFd);
  2342. return false;
  2343. }
  2344. #endif
  2345. const HostPosixFileDescriptorDetails posixFD = {
  2346. hostFd,
  2347. fd,
  2348. flags,
  2349. };
  2350. fPosixFileDescriptors.append(posixFD);
  2351. return true;
  2352. }
  2353. return false;
  2354. }
  2355. bool clapModifyPosixFD(const int fd, const clap_posix_fd_flags_t flags) override
  2356. {
  2357. carla_stdout("CarlaPluginCLAP::clapTimerUnregister(%i, %x)", fd, flags);
  2358. for (LinkedList<HostPosixFileDescriptorDetails>::Itenerator it = fPosixFileDescriptors.begin2(); it.valid(); it.next())
  2359. {
  2360. HostPosixFileDescriptorDetails& posixFD(it.getValue(kPosixFileDescriptorFallbackNC));
  2361. if (posixFD.pluginFd == fd)
  2362. {
  2363. if (posixFD.flags == flags)
  2364. return true;
  2365. #ifdef CARLA_CLAP_POSIX_EPOLL
  2366. struct ::epoll_event ev = {};
  2367. if (flags & CLAP_POSIX_FD_READ)
  2368. ev.events |= EPOLLIN;
  2369. if (flags & CLAP_POSIX_FD_WRITE)
  2370. ev.events |= EPOLLOUT;
  2371. ev.data.fd = fd;
  2372. if (::epoll_ctl(posixFD.hostFd, EPOLL_CTL_MOD, fd, &ev) < 0)
  2373. return false;
  2374. #endif
  2375. posixFD.flags = flags;
  2376. return true;
  2377. }
  2378. }
  2379. return false;
  2380. }
  2381. bool clapUnregisterPosixFD(const int fd) override
  2382. {
  2383. carla_stdout("CarlaPluginCLAP::clapTimerUnregister(%i)", fd);
  2384. for (LinkedList<HostPosixFileDescriptorDetails>::Itenerator it = fPosixFileDescriptors.begin2(); it.valid(); it.next())
  2385. {
  2386. const HostPosixFileDescriptorDetails& posixFD(it.getValue(kPosixFileDescriptorFallback));
  2387. if (posixFD.pluginFd == fd)
  2388. {
  2389. #ifdef CARLA_CLAP_POSIX_EPOLL
  2390. ::epoll_ctl(posixFD.hostFd, EPOLL_CTL_DEL, fd, nullptr);
  2391. #endif
  2392. ::close(posixFD.hostFd);
  2393. fPosixFileDescriptors.remove(it);
  2394. return true;
  2395. }
  2396. }
  2397. return false;
  2398. }
  2399. #endif // _POSIX_VERSION
  2400. // -------------------------------------------------------------------
  2401. bool clapRegisterTimer(const uint32_t periodInMs, clap_id* const timerId) override
  2402. {
  2403. carla_stdout("CarlaPluginCLAP::clapTimerRegister(%u, %p)", periodInMs, timerId);
  2404. // NOTE some plugins wont have their timer extension ready when first loaded, so try again here
  2405. if (fExtensions.timer == nullptr)
  2406. {
  2407. const clap_plugin_timer_support_t* const timerExt = static_cast<const clap_plugin_timer_support_t*>(
  2408. fPlugin->get_extension(fPlugin, CLAP_EXT_TIMER_SUPPORT));
  2409. if (timerExt != nullptr && timerExt->on_timer != nullptr)
  2410. fExtensions.timer = timerExt;
  2411. }
  2412. CARLA_SAFE_ASSERT_RETURN(fExtensions.timer != nullptr, false);
  2413. // FIXME events only driven as long as UI is open
  2414. // CARLA_SAFE_ASSERT_RETURN(fUI.isCreated, false);
  2415. const HostTimerDetails timer = {
  2416. fTimers.isNotEmpty() ? fTimers.getLast(kTimerFallback).clapId + 1 : 1,
  2417. periodInMs,
  2418. 0
  2419. };
  2420. fTimers.append(timer);
  2421. *timerId = timer.clapId;
  2422. return true;
  2423. }
  2424. bool clapUnregisterTimer(const clap_id timerId) override
  2425. {
  2426. carla_stdout("CarlaPluginCLAP::clapTimerUnregister(%u)", timerId);
  2427. for (LinkedList<HostTimerDetails>::Itenerator it = fTimers.begin2(); it.valid(); it.next())
  2428. {
  2429. const HostTimerDetails& timer(it.getValue(kTimerFallback));
  2430. if (timer.clapId == timerId)
  2431. {
  2432. fTimers.remove(it);
  2433. return true;
  2434. }
  2435. }
  2436. return false;
  2437. }
  2438. #endif // CLAP_WINDOW_API_NATIVE
  2439. // -------------------------------------------------------------------
  2440. public:
  2441. bool init(const CarlaPluginPtr plugin,
  2442. const char* const filename, const char* const name, const char* const id, const uint options)
  2443. {
  2444. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  2445. // ---------------------------------------------------------------
  2446. // first checks
  2447. if (pData->client != nullptr)
  2448. {
  2449. pData->engine->setLastError("Plugin client is already registered");
  2450. return false;
  2451. }
  2452. if (filename == nullptr || filename[0] == '\0')
  2453. {
  2454. pData->engine->setLastError("null filename");
  2455. return false;
  2456. }
  2457. // ---------------------------------------------------------------
  2458. const clap_plugin_entry_t* entry;
  2459. #ifdef CARLA_OS_MAC
  2460. if (!water::File(filename).existsAsFile())
  2461. {
  2462. if (! fBundleLoader.load(filename))
  2463. {
  2464. pData->engine->setLastError("Failed to load CLAP bundle executable");
  2465. return false;
  2466. }
  2467. entry = fBundleLoader.getSymbol<const clap_plugin_entry_t*>(CFSTR("clap_entry"));
  2468. }
  2469. else
  2470. #endif
  2471. {
  2472. if (! pData->libOpen(filename))
  2473. {
  2474. pData->engine->setLastError(pData->libError(filename));
  2475. return false;
  2476. }
  2477. entry = pData->libSymbol<const clap_plugin_entry_t*>("clap_entry");
  2478. }
  2479. if (entry == nullptr)
  2480. {
  2481. pData->engine->setLastError("Could not find the CLAP entry in the plugin library");
  2482. return false;
  2483. }
  2484. if (entry->init == nullptr || entry->deinit == nullptr || entry->get_factory == nullptr)
  2485. {
  2486. pData->engine->setLastError("CLAP factory entries are null");
  2487. return false;
  2488. }
  2489. if (!clap_version_is_compatible(entry->clap_version))
  2490. {
  2491. pData->engine->setLastError("Incompatible CLAP plugin");
  2492. return false;
  2493. }
  2494. // ---------------------------------------------------------------
  2495. const water::String pluginPath(water::File(filename).getParentDirectory().getFullPathName());
  2496. if (!entry->init(pluginPath.toRawUTF8()))
  2497. {
  2498. pData->engine->setLastError("Plugin entry failed to initialize");
  2499. return false;
  2500. }
  2501. fPluginEntry = entry;
  2502. // ---------------------------------------------------------------
  2503. const clap_plugin_factory_t* const factory = static_cast<const clap_plugin_factory_t*>(
  2504. entry->get_factory(CLAP_PLUGIN_FACTORY_ID));
  2505. if (factory == nullptr
  2506. || factory->get_plugin_count == nullptr
  2507. || factory->get_plugin_descriptor == nullptr
  2508. || factory->create_plugin == nullptr)
  2509. {
  2510. pData->engine->setLastError("Plugin is missing factory methods");
  2511. return false;
  2512. }
  2513. // ---------------------------------------------------------------
  2514. if (const uint32_t count = factory->get_plugin_count(factory))
  2515. {
  2516. // null id requested, use first available plugin
  2517. if (id == nullptr || id[0] == '\0')
  2518. {
  2519. fPluginDescriptor = factory->get_plugin_descriptor(factory, 0);
  2520. if (fPluginDescriptor == nullptr)
  2521. {
  2522. pData->engine->setLastError("Plugin library does not contain a valid first plugin");
  2523. return false;
  2524. }
  2525. }
  2526. else
  2527. {
  2528. for (uint32_t i=0; i<count; ++i)
  2529. {
  2530. const clap_plugin_descriptor_t* const desc = factory->get_plugin_descriptor(factory, i);
  2531. CARLA_SAFE_ASSERT_CONTINUE(desc != nullptr);
  2532. CARLA_SAFE_ASSERT_CONTINUE(desc->id != nullptr);
  2533. if (std::strcmp(desc->id, id) == 0)
  2534. {
  2535. fPluginDescriptor = desc;
  2536. break;
  2537. }
  2538. }
  2539. if (fPluginDescriptor == nullptr)
  2540. {
  2541. pData->engine->setLastError("Plugin library does not contain the requested plugin");
  2542. return false;
  2543. }
  2544. }
  2545. }
  2546. else
  2547. {
  2548. pData->engine->setLastError("Plugin library contains no plugins");
  2549. return false;
  2550. }
  2551. // ---------------------------------------------------------------
  2552. fPlugin = factory->create_plugin(factory, &fHost, fPluginDescriptor->id);
  2553. if (fPlugin == nullptr)
  2554. {
  2555. pData->engine->setLastError("Failed to create CLAP plugin instance");
  2556. return false;
  2557. }
  2558. if (!fPlugin->init(fPlugin))
  2559. {
  2560. pData->engine->setLastError("Failed to initialize CLAP plugin instance");
  2561. return false;
  2562. }
  2563. // ---------------------------------------------------------------
  2564. // get info
  2565. pData->name = pData->engine->getUniquePluginName(name != nullptr && name[0] != '\0' ? name
  2566. : fPluginDescriptor->name);
  2567. pData->filename = carla_strdup(filename);
  2568. // ---------------------------------------------------------------
  2569. // register client
  2570. pData->client = pData->engine->addClient(plugin);
  2571. if (pData->client == nullptr || ! pData->client->isOk())
  2572. {
  2573. pData->engine->setLastError("Failed to register plugin client");
  2574. return false;
  2575. }
  2576. // ---------------------------------------------------------------
  2577. // set default options
  2578. pData->options = PLUGIN_OPTION_FIXED_BUFFERS;
  2579. if (const clap_plugin_state_t* const stateExt =
  2580. static_cast<const clap_plugin_state_t*>(fPlugin->get_extension(fPlugin, CLAP_EXT_STATE)))
  2581. {
  2582. if (stateExt->save != nullptr && stateExt->load != nullptr)
  2583. if (isPluginOptionEnabled(options, PLUGIN_OPTION_USE_CHUNKS))
  2584. pData->options |= PLUGIN_OPTION_USE_CHUNKS;
  2585. }
  2586. if (const clap_plugin_note_ports_t* const notePortsExt =
  2587. static_cast<const clap_plugin_note_ports_t*>(fPlugin->get_extension(fPlugin, CLAP_EXT_NOTE_PORTS)))
  2588. {
  2589. const uint32_t numNoteInputPorts = notePortsExt->count != nullptr && notePortsExt->get != nullptr
  2590. ? notePortsExt->count(fPlugin, true) : 0;
  2591. for (uint32_t i=0; i<numNoteInputPorts; ++i)
  2592. {
  2593. clap_note_port_info_t portInfo = {};
  2594. CARLA_SAFE_ASSERT_BREAK(notePortsExt->get(fPlugin, i, true, &portInfo));
  2595. if (portInfo.supported_dialects & CLAP_NOTE_DIALECT_MIDI)
  2596. {
  2597. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CONTROL_CHANGES))
  2598. pData->options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  2599. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CHANNEL_PRESSURE))
  2600. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  2601. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH))
  2602. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  2603. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PITCHBEND))
  2604. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  2605. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_ALL_SOUND_OFF))
  2606. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  2607. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PROGRAM_CHANGES))
  2608. pData->options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  2609. if (isPluginOptionInverseEnabled(options, PLUGIN_OPTION_SKIP_SENDING_NOTES))
  2610. pData->options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  2611. break;
  2612. }
  2613. if (portInfo.supported_dialects & CLAP_NOTE_DIALECT_CLAP)
  2614. {
  2615. if (isPluginOptionInverseEnabled(options, PLUGIN_OPTION_SKIP_SENDING_NOTES))
  2616. pData->options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  2617. // nobreak, in case another port supports MIDI
  2618. }
  2619. }
  2620. }
  2621. // if (fEffect->numPrograms > 1 && (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) == 0)
  2622. // if (isPluginOptionEnabled(options, PLUGIN_OPTION_MAP_PROGRAM_CHANGES))
  2623. // pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  2624. return true;
  2625. }
  2626. private:
  2627. const clap_plugin_t* fPlugin;
  2628. const clap_plugin_descriptor_t* fPluginDescriptor;
  2629. const clap_plugin_entry_t* fPluginEntry;
  2630. const carla_clap_host fHost;
  2631. struct Extensions {
  2632. const clap_plugin_latency_t* latency;
  2633. const clap_plugin_params_t* params;
  2634. const clap_plugin_state_t* state;
  2635. const clap_plugin_timer_support_t* timer;
  2636. #ifdef CLAP_WINDOW_API_NATIVE
  2637. const clap_plugin_gui_t* gui;
  2638. #ifdef _POSIX_VERSION
  2639. const clap_plugin_posix_fd_support_t* posixFD;
  2640. #endif
  2641. #endif
  2642. Extensions()
  2643. : latency(nullptr),
  2644. params(nullptr),
  2645. state(nullptr),
  2646. timer(nullptr)
  2647. #ifdef CLAP_WINDOW_API_NATIVE
  2648. , gui(nullptr)
  2649. #ifdef _POSIX_VERSION
  2650. , posixFD(nullptr)
  2651. #endif
  2652. #endif
  2653. {
  2654. }
  2655. CARLA_DECLARE_NON_COPYABLE(Extensions)
  2656. } fExtensions;
  2657. #ifdef CLAP_WINDOW_API_NATIVE
  2658. struct UI {
  2659. bool initalized;
  2660. bool isCreated;
  2661. bool isEmbed;
  2662. bool isVisible;
  2663. bool isResizingFromHost;
  2664. bool isResizingFromInit;
  2665. int isResizingFromPlugin;
  2666. bool shouldClose;
  2667. uint32_t width, height;
  2668. CarlaPluginUI* window;
  2669. UI()
  2670. : initalized(false),
  2671. isCreated(false),
  2672. isEmbed(false),
  2673. isVisible(false),
  2674. isResizingFromHost(false),
  2675. isResizingFromInit(false),
  2676. isResizingFromPlugin(0),
  2677. shouldClose(false),
  2678. width(0),
  2679. height(0),
  2680. window(nullptr) {}
  2681. ~UI()
  2682. {
  2683. CARLA_SAFE_ASSERT(window == nullptr);
  2684. }
  2685. CARLA_DECLARE_NON_COPYABLE(UI)
  2686. } fUI;
  2687. #ifdef _POSIX_VERSION
  2688. LinkedList<HostPosixFileDescriptorDetails> fPosixFileDescriptors;
  2689. #endif
  2690. LinkedList<HostTimerDetails> fTimers;
  2691. #endif
  2692. carla_clap_input_audio_buffers fInputAudioBuffers;
  2693. carla_clap_output_audio_buffers fOutputAudioBuffers;
  2694. carla_clap_input_events fInputEvents;
  2695. carla_clap_output_events fOutputEvents;
  2696. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2697. float** fAudioOutBuffers;
  2698. #endif
  2699. void* fLastChunk;
  2700. uint32_t fLastKnownLatency;
  2701. const bool kEngineHasIdleOnMainThread;
  2702. bool fNeedsParamFlush;
  2703. bool fNeedsRestart;
  2704. bool fNeedsProcess;
  2705. bool fNeedsIdleCallback;
  2706. #ifdef CARLA_OS_MAC
  2707. BundleLoader fBundleLoader;
  2708. #endif
  2709. void runIdleCallbacksAsNeeded(const bool isIdleCallback)
  2710. {
  2711. if (isIdleCallback && (fNeedsRestart || fNeedsProcess))
  2712. {
  2713. carla_stdout("runIdleCallbacksAsNeeded %d %d", fNeedsRestart, fNeedsProcess);
  2714. const bool needsRestart = fNeedsRestart;
  2715. if (needsRestart)
  2716. {
  2717. fNeedsRestart = false;
  2718. setActive(false, true, true);
  2719. }
  2720. if (fNeedsProcess)
  2721. {
  2722. fNeedsProcess = false;
  2723. setEnabled(true);
  2724. setActive(true, true, true);
  2725. }
  2726. else if (needsRestart)
  2727. {
  2728. setActive(true, true, true);
  2729. }
  2730. }
  2731. if (fNeedsParamFlush)
  2732. {
  2733. fNeedsParamFlush = false;
  2734. carla_clap_input_events copy;
  2735. copy.reallocEqualTo(fInputEvents);
  2736. {
  2737. const ScopedSingleProcessLocker sspl(this, true);
  2738. fInputEvents.handleScheduledParameterUpdates();
  2739. fInputEvents.swap(copy);
  2740. }
  2741. fExtensions.params->flush(fPlugin, copy.cast(), nullptr);
  2742. }
  2743. if (fNeedsIdleCallback)
  2744. {
  2745. fNeedsIdleCallback = false;
  2746. fPlugin->on_main_thread(fPlugin);
  2747. }
  2748. #ifdef CLAP_WINDOW_API_NATIVE
  2749. #ifdef _POSIX_VERSION
  2750. for (LinkedList<HostPosixFileDescriptorDetails>::Itenerator it = fPosixFileDescriptors.begin2(); it.valid(); it.next())
  2751. {
  2752. const HostPosixFileDescriptorDetails& posixFD(it.getValue(kPosixFileDescriptorFallback));
  2753. #ifdef CARLA_CLAP_POSIX_EPOLL
  2754. struct ::epoll_event event;
  2755. #else
  2756. const int16_t filter = posixFD.flags & CLAP_POSIX_FD_WRITE ? EVFILT_WRITE : EVFILT_READ;
  2757. struct ::kevent kev = {}, event;
  2758. struct ::timespec timeout = {};
  2759. EV_SET(&kev, posixFD.pluginFd, filter, EV_ADD|EV_ENABLE, 0, 0, nullptr);
  2760. #endif
  2761. for (int i=0; i<50; ++i)
  2762. {
  2763. #ifdef CARLA_CLAP_POSIX_EPOLL
  2764. switch (::epoll_wait(posixFD.hostFd, &event, 1, 0))
  2765. #else
  2766. switch (::kevent(posixFD.hostFd, &kev, 1, &event, 1, &timeout))
  2767. #endif
  2768. {
  2769. case 1:
  2770. fExtensions.posixFD->on_fd(fPlugin, posixFD.pluginFd, posixFD.flags);
  2771. break;
  2772. case -1:
  2773. fExtensions.posixFD->on_fd(fPlugin, posixFD.pluginFd, posixFD.flags | CLAP_POSIX_FD_ERROR);
  2774. // fall through
  2775. case 0:
  2776. i = 50;
  2777. break;
  2778. default:
  2779. carla_safe_exception("posix fd received abnormal value", __FILE__, __LINE__);
  2780. i = 50;
  2781. break;
  2782. }
  2783. }
  2784. }
  2785. #endif // _POSIX_VERSION
  2786. for (LinkedList<HostTimerDetails>::Itenerator it = fTimers.begin2(); it.valid(); it.next())
  2787. {
  2788. const uint32_t currentTimeInMs = water::Time::getMillisecondCounter();
  2789. HostTimerDetails& timer(it.getValue(kTimerFallbackNC));
  2790. if (currentTimeInMs > timer.lastCallTimeInMs + timer.periodInMs)
  2791. {
  2792. timer.lastCallTimeInMs = currentTimeInMs;
  2793. fExtensions.timer->on_timer(fPlugin, timer.clapId);
  2794. }
  2795. }
  2796. #endif // CLAP_WINDOW_API_NATIVE
  2797. }
  2798. };
  2799. // --------------------------------------------------------------------------------------------------------------------
  2800. CarlaPluginPtr CarlaPlugin::newCLAP(const Initializer& init)
  2801. {
  2802. carla_debug("CarlaPlugin::newCLAP({%p, \"%s\", \"%s\", \"%s\"})",
  2803. init.engine, init.filename, init.name, init.label);
  2804. std::shared_ptr<CarlaPluginCLAP> plugin(new CarlaPluginCLAP(init.engine, init.id));
  2805. if (! plugin->init(plugin, init.filename, init.name, init.label, init.options))
  2806. return nullptr;
  2807. return plugin;
  2808. }
  2809. // -------------------------------------------------------------------------------------------------------------------
  2810. CARLA_BACKEND_END_NAMESPACE