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.

3203 lines
109KB

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