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.

704 lines
21KB

  1. /*
  2. * Carla LV2 Single Plugin
  3. * Copyright (C) 2017 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. #ifndef BUILD_BRIDGE
  18. # error This file should not be compiled if not building bridge
  19. #endif
  20. #include "engine/CarlaEngineInternal.hpp"
  21. #include "CarlaPlugin.hpp"
  22. #include "CarlaBackendUtils.hpp"
  23. #include "CarlaEngineUtils.hpp"
  24. #include "CarlaLv2Utils.hpp"
  25. #include "CarlaUtils.h"
  26. #include "water/files/File.h"
  27. // --------------------------------------------------------------------------------------------------------------------
  28. CARLA_BACKEND_START_NAMESPACE
  29. class CarlaEngineSingleLV2 : public CarlaEngine,
  30. public Lv2PluginBaseClass<EngineTimeInfo>
  31. {
  32. public:
  33. CarlaEngineSingleLV2(const double sampleRate,
  34. const char* const bundlePath,
  35. const LV2_Feature* const* const features)
  36. : Lv2PluginBaseClass(sampleRate, features),
  37. fPlugin(nullptr),
  38. fUiName()
  39. {
  40. CARLA_SAFE_ASSERT_RETURN(pData->curPluginCount == 0,)
  41. CARLA_SAFE_ASSERT_RETURN(pData->plugins[0].plugin == nullptr,);
  42. if (! loadedInProperHost())
  43. return;
  44. // xxxxx
  45. CarlaString binaryDir(bundlePath);
  46. binaryDir += CARLA_OS_SEP_STR "bin" CARLA_OS_SEP_STR;
  47. CarlaString resourceDir(bundlePath);
  48. resourceDir += CARLA_OS_SEP_STR "res" CARLA_OS_SEP_STR;
  49. pData->bufferSize = fBufferSize;
  50. pData->sampleRate = sampleRate;
  51. pData->initTime(nullptr);
  52. pData->options.processMode = ENGINE_PROCESS_MODE_BRIDGE;
  53. pData->options.transportMode = ENGINE_TRANSPORT_MODE_PLUGIN;
  54. pData->options.forceStereo = false;
  55. pData->options.preferPluginBridges = false;
  56. pData->options.preferUiBridges = false;
  57. init("LV2-Export");
  58. if (pData->options.resourceDir != nullptr)
  59. delete[] pData->options.resourceDir;
  60. if (pData->options.binaryDir != nullptr)
  61. delete[] pData->options.binaryDir;
  62. pData->options.binaryDir = binaryDir.dup();
  63. pData->options.resourceDir = resourceDir.dup();
  64. setCallback(_engine_callback, this);
  65. using water::File;
  66. const File pluginFile(File::getSpecialLocation(File::currentExecutableFile).withFileExtension("xml"));
  67. if (! loadProject(pluginFile.getFullPathName().toRawUTF8()))
  68. {
  69. carla_stderr2("Failed to init plugin, possible reasons: %s", getLastError());
  70. return;
  71. }
  72. CARLA_SAFE_ASSERT_RETURN(pData->curPluginCount == 1,)
  73. fPlugin = pData->plugins[0].plugin;
  74. CARLA_SAFE_ASSERT_RETURN(fPlugin != nullptr,);
  75. CARLA_SAFE_ASSERT_RETURN(fPlugin->isEnabled(),);
  76. fPorts.usesTime = true;
  77. fPorts.numAudioIns = fPlugin->getAudioInCount();
  78. fPorts.numAudioOuts = fPlugin->getAudioOutCount();
  79. fPorts.numMidiIns = fPlugin->getMidiInCount();
  80. fPorts.numMidiOuts = fPlugin->getMidiOutCount();
  81. fPorts.numParams = fPlugin->getParameterCount();
  82. fPorts.init();
  83. for (uint32_t i=0; i < fPorts.numParams; ++i)
  84. {
  85. fPorts.paramsLast[i] = fPlugin->getParameterValue(i);
  86. fPorts.paramsOut [i] = fPlugin->isParameterOutput(i);
  87. }
  88. }
  89. ~CarlaEngineSingleLV2()
  90. {
  91. if (fPlugin != nullptr && fIsActive)
  92. fPlugin->setActive(false, false, false);
  93. close();
  94. }
  95. bool hasPlugin() noexcept
  96. {
  97. return fPlugin != nullptr;
  98. }
  99. // ----------------------------------------------------------------------------------------------------------------
  100. // LV2 functions
  101. void lv2_activate() noexcept
  102. {
  103. CARLA_SAFE_ASSERT_RETURN(! fIsActive,);
  104. resetTimeInfo();
  105. fPlugin->setActive(true, false, false);
  106. fIsActive = true;
  107. }
  108. void lv2_deactivate() noexcept
  109. {
  110. CARLA_SAFE_ASSERT_RETURN(fIsActive,);
  111. fIsActive = false;
  112. fPlugin->setActive(false, false, false);
  113. }
  114. void lv2_run(const uint32_t frames)
  115. {
  116. //const PendingRtEventsRunner prt(this, frames);
  117. if (! lv2_pre_run(frames))
  118. {
  119. updateParameterOutputs();
  120. return;
  121. }
  122. if (fPorts.numMidiIns > 0)
  123. {
  124. uint32_t engineEventIndex = 0;
  125. carla_zeroStructs(pData->events.in, kMaxEngineEventInternalCount);
  126. for (uint32_t i=0; i < fPorts.numMidiIns; ++i)
  127. {
  128. LV2_ATOM_SEQUENCE_FOREACH(fPorts.eventsIn[i], event)
  129. {
  130. if (event == nullptr)
  131. continue;
  132. if (event->body.type != fURIs.midiEvent)
  133. continue;
  134. if (event->body.size > 4)
  135. continue;
  136. if (event->time.frames >= frames)
  137. break;
  138. const uint8_t* const data((const uint8_t*)(event + 1));
  139. EngineEvent& engineEvent(pData->events.in[engineEventIndex++]);
  140. engineEvent.time = (uint32_t)event->time.frames;
  141. engineEvent.fillFromMidiData((uint8_t)event->body.size, data, (uint8_t)i);
  142. if (engineEventIndex >= kMaxEngineEventInternalCount)
  143. break;
  144. }
  145. }
  146. }
  147. if (fPorts.numMidiOuts > 0)
  148. {
  149. carla_zeroStructs(pData->events.out, kMaxEngineEventInternalCount);
  150. }
  151. if (fPlugin->tryLock(fIsOffline))
  152. {
  153. fPlugin->initBuffers();
  154. fPlugin->process(fPorts.audioIns, fPorts.audioOuts, nullptr, nullptr, frames);
  155. fPlugin->unlock();
  156. if (fPorts.numMidiOuts > 0)
  157. {
  158. uint8_t port = 0;
  159. uint8_t size = 0;
  160. uint8_t data[3] = { 0, 0, 0 };
  161. const uint8_t* dataPtr = data;
  162. for (ushort i=0; i < kMaxEngineEventInternalCount; ++i)
  163. {
  164. const EngineEvent& engineEvent(pData->events.out[i]);
  165. switch (engineEvent.type)
  166. {
  167. case kEngineEventTypeNull:
  168. break;
  169. case kEngineEventTypeControl: {
  170. const EngineControlEvent& ctrlEvent(engineEvent.ctrl);
  171. ctrlEvent.convertToMidiData(engineEvent.channel, size, data);
  172. dataPtr = data;
  173. break;
  174. }
  175. case kEngineEventTypeMidi: {
  176. const EngineMidiEvent& midiEvent(engineEvent.midi);
  177. port = midiEvent.port;
  178. size = midiEvent.size;
  179. if (size > EngineMidiEvent::kDataSize && midiEvent.dataExt != nullptr)
  180. dataPtr = midiEvent.dataExt;
  181. else
  182. dataPtr = midiEvent.data;
  183. break;
  184. }
  185. }
  186. if (size > 0 && ! writeMidiEvent(port, engineEvent.time, size, dataPtr))
  187. break;
  188. }
  189. }
  190. }
  191. else
  192. {
  193. for (uint32_t i=0; i<fPorts.numAudioOuts; ++i)
  194. carla_zeroFloats(fPorts.audioOuts[i], frames);
  195. }
  196. lv2_post_run(frames);
  197. updateParameterOutputs();
  198. }
  199. // ----------------------------------------------------------------------------------------------------------------
  200. bool lv2ui_instantiate(LV2UI_Write_Function writeFunction, LV2UI_Controller controller,
  201. LV2UI_Widget* widget, const LV2_Feature* const* features)
  202. {
  203. fUI.writeFunction = writeFunction;
  204. fUI.controller = controller;
  205. fUI.host = nullptr;
  206. fUiName.clear();
  207. const LV2_URID_Map* uridMap = nullptr;
  208. // ------------------------------------------------------------------------------------------------------------
  209. // see if the host supports external-ui, get uridMap
  210. for (int i=0; features[i] != nullptr; ++i)
  211. {
  212. if (std::strcmp(features[i]->URI, LV2_EXTERNAL_UI__Host) == 0 ||
  213. std::strcmp(features[i]->URI, LV2_EXTERNAL_UI_DEPRECATED_URI) == 0)
  214. {
  215. fUI.host = (const LV2_External_UI_Host*)features[i]->data;
  216. }
  217. else if (std::strcmp(features[i]->URI, LV2_URID__map) == 0)
  218. {
  219. uridMap = (const LV2_URID_Map*)features[i]->data;
  220. }
  221. }
  222. if (fUI.host != nullptr)
  223. {
  224. fUiName = fUI.host->plugin_human_id;
  225. *widget = (LV2_External_UI_Widget_Compat*)this;
  226. return true;
  227. }
  228. // ------------------------------------------------------------------------------------------------------------
  229. // no external-ui support, use showInterface
  230. for (int i=0; features[i] != nullptr; ++i)
  231. {
  232. if (std::strcmp(features[i]->URI, LV2_OPTIONS__options) == 0)
  233. {
  234. const LV2_Options_Option* const options((const LV2_Options_Option*)features[i]->data);
  235. for (int j=0; options[j].key != 0; ++j)
  236. {
  237. if (options[j].key == uridMap->map(uridMap->handle, LV2_UI__windowTitle))
  238. {
  239. fUiName = (const char*)options[j].value;
  240. break;
  241. }
  242. }
  243. break;
  244. }
  245. }
  246. if (fUiName.isEmpty())
  247. fUiName = fPlugin->getName();
  248. *widget = nullptr;
  249. return true;
  250. }
  251. void lv2ui_port_event(uint32_t portIndex, uint32_t bufferSize, uint32_t format, const void* buffer) const
  252. {
  253. if (format != 0 || bufferSize != sizeof(float) || buffer == nullptr)
  254. return;
  255. if (portIndex >= fPorts.indexOffset || ! fUI.isVisible)
  256. return;
  257. const float value(*(const float*)buffer);
  258. fPlugin->uiParameterChange(portIndex-fPorts.indexOffset, value);
  259. }
  260. protected:
  261. // ----------------------------------------------------------------------------------------------------------------
  262. // CarlaEngine virtual calls
  263. bool init(const char* const clientName) override
  264. {
  265. carla_stdout("CarlaEngineNative::init(\"%s\")", clientName);
  266. if (! pData->init(clientName))
  267. {
  268. close();
  269. setLastError("Failed to init internal data");
  270. return false;
  271. }
  272. return true;
  273. }
  274. bool isRunning() const noexcept override
  275. {
  276. return fIsActive;
  277. }
  278. bool isOffline() const noexcept override
  279. {
  280. return fIsOffline;
  281. }
  282. bool usesConstantBufferSize() const noexcept override
  283. {
  284. return false;
  285. }
  286. EngineType getType() const noexcept override
  287. {
  288. return kEngineTypePlugin;
  289. }
  290. const char* getCurrentDriverName() const noexcept override
  291. {
  292. return "LV2 Plugin";
  293. }
  294. void engineCallback(const EngineCallbackOpcode action, const uint pluginId, const int value1, const int value2, const float value3, const char* const valueStr)
  295. {
  296. switch (action)
  297. {
  298. case ENGINE_CALLBACK_PARAMETER_VALUE_CHANGED:
  299. CARLA_SAFE_ASSERT_RETURN(value1 >= 0,);
  300. if (fUI.writeFunction != nullptr && fUI.controller != nullptr && fUI.isVisible)
  301. {
  302. fUI.writeFunction(fUI.controller,
  303. static_cast<uint32_t>(value1)+fPorts.indexOffset,
  304. sizeof(float), 0, &value3);
  305. }
  306. break;
  307. case ENGINE_CALLBACK_UI_STATE_CHANGED:
  308. fUI.isVisible = (value1 == 1);
  309. if (fUI.host != nullptr)
  310. fUI.host->ui_closed(fUI.controller);
  311. break;
  312. case ENGINE_CALLBACK_IDLE:
  313. break;
  314. default:
  315. carla_stdout("engineCallback(%i:%s, %u, %i, %i, %f, %s)",
  316. action, EngineCallbackOpcode2Str(action), pluginId, value1, value2, value3, valueStr);
  317. break;
  318. }
  319. }
  320. // ----------------------------------------------------------------------------------------------------------------
  321. void handleUiRun() const override
  322. {
  323. try {
  324. fPlugin->uiIdle();
  325. } CARLA_SAFE_EXCEPTION("fPlugin->uiIdle()")
  326. }
  327. void handleUiShow() override
  328. {
  329. fPlugin->showCustomUI(true);
  330. fUI.isVisible = true;
  331. }
  332. void handleUiHide() override
  333. {
  334. fUI.isVisible = false;
  335. fPlugin->showCustomUI(false);
  336. }
  337. // ----------------------------------------------------------------------------------------------------------------
  338. void handleParameterValueChanged(const uint32_t index, const float value) override
  339. {
  340. fPlugin->setParameterValue(index, value, false, false, false);
  341. }
  342. void handleBufferSizeChanged(const uint32_t bufferSize) override
  343. {
  344. CarlaEngine::bufferSizeChanged(bufferSize);
  345. }
  346. void handleSampleRateChanged(const double sampleRate) override
  347. {
  348. CarlaEngine::sampleRateChanged(sampleRate);
  349. }
  350. // ----------------------------------------------------------------------------------------------------------------
  351. private:
  352. CarlaPlugin* fPlugin;
  353. CarlaString fUiName;
  354. void updateParameterOutputs() noexcept
  355. {
  356. float value;
  357. for (uint32_t i=0; i < fPorts.numParams; ++i)
  358. {
  359. if (! fPorts.paramsOut[i])
  360. continue;
  361. fPorts.paramsLast[i] = value = fPlugin->getParameterValue(i);
  362. if (fPorts.paramsPtr[i] != nullptr)
  363. *fPorts.paramsPtr[i] = value;
  364. }
  365. }
  366. bool writeMidiEvent(const uint8_t port, const uint32_t time, const uint8_t midiSize, const uint8_t* midiData)
  367. {
  368. CARLA_SAFE_ASSERT_RETURN(fPorts.numMidiOuts > 0, false);
  369. CARLA_SAFE_ASSERT_RETURN(port < fPorts.numMidiOuts, false);
  370. CARLA_SAFE_ASSERT_RETURN(midiData != nullptr, false);
  371. CARLA_SAFE_ASSERT_RETURN(midiSize > 0, false);
  372. LV2_Atom_Sequence* const seq(fPorts.midiOuts[port]);
  373. CARLA_SAFE_ASSERT_RETURN(seq != nullptr, false);
  374. Ports::MidiOutData& mData(fPorts.midiOutData[port]);
  375. if (sizeof(LV2_Atom_Event) + midiSize > mData.capacity - mData.offset)
  376. return false;
  377. LV2_Atom_Event* const aev = (LV2_Atom_Event*)(LV2_ATOM_CONTENTS(LV2_Atom_Sequence, seq) + mData.offset);
  378. aev->time.frames = time;
  379. aev->body.size = midiSize;
  380. aev->body.type = fURIs.midiEvent;
  381. std::memcpy(LV2_ATOM_BODY(&aev->body), midiData, midiSize);
  382. const uint32_t size = lv2_atom_pad_size(static_cast<uint32_t>(sizeof(LV2_Atom_Event) + midiSize));
  383. mData.offset += size;
  384. seq->atom.size += size;
  385. return true;
  386. }
  387. // -------------------------------------------------------------------
  388. #define handlePtr ((CarlaEngineSingleLV2*)handle)
  389. static void _engine_callback(void* handle, EngineCallbackOpcode action, uint pluginId, int value1, int value2, float value3, const char* valueStr)
  390. {
  391. handlePtr->engineCallback(action, pluginId, value1, value2, value3, valueStr);
  392. }
  393. #undef handlePtr
  394. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineSingleLV2)
  395. };
  396. CARLA_BACKEND_END_NAMESPACE
  397. using CarlaBackend::CarlaEngineSingleLV2;
  398. // --------------------------------------------------------------------------------------------------------------------
  399. // LV2 DSP functions
  400. static LV2_Handle lv2_instantiate(const LV2_Descriptor* lv2Descriptor, double sampleRate, const char* bundlePath, const LV2_Feature* const* features)
  401. {
  402. carla_stdout("lv2_instantiate(%p, %g, %s, %p)", lv2Descriptor, sampleRate, bundlePath, features);
  403. CarlaEngineSingleLV2* const instance(new CarlaEngineSingleLV2(sampleRate, bundlePath, features));
  404. if (instance->hasPlugin())
  405. return (LV2_Handle)instance;
  406. delete instance;
  407. return nullptr;
  408. }
  409. #define instancePtr ((CarlaEngineSingleLV2*)instance)
  410. static void lv2_connect_port(LV2_Handle instance, uint32_t port, void* dataLocation)
  411. {
  412. instancePtr->lv2_connect_port(port, dataLocation);
  413. }
  414. static void lv2_activate(LV2_Handle instance)
  415. {
  416. carla_debug("lv2_activate(%p)", instance);
  417. instancePtr->lv2_activate();
  418. }
  419. static void lv2_run(LV2_Handle instance, uint32_t sampleCount)
  420. {
  421. instancePtr->lv2_run(sampleCount);
  422. }
  423. static void lv2_deactivate(LV2_Handle instance)
  424. {
  425. carla_debug("lv2_deactivate(%p)", instance);
  426. instancePtr->lv2_deactivate();
  427. }
  428. static void lv2_cleanup(LV2_Handle instance)
  429. {
  430. carla_debug("lv2_cleanup(%p)", instance);
  431. delete instancePtr;
  432. }
  433. static const void* lv2_extension_data(const char* uri)
  434. {
  435. carla_debug("lv2_extension_data(\"%s\")", uri);
  436. return nullptr;
  437. // unused
  438. (void)uri;
  439. }
  440. #undef instancePtr
  441. // --------------------------------------------------------------------------------------------------------------------
  442. // LV2 UI functions
  443. static LV2UI_Handle lv2ui_instantiate(const LV2UI_Descriptor*, const char*, const char*,
  444. LV2UI_Write_Function writeFunction, LV2UI_Controller controller,
  445. LV2UI_Widget* widget, const LV2_Feature* const* features)
  446. {
  447. carla_debug("lv2ui_instantiate(..., %p, %p, %p)", writeFunction, controller, widget, features);
  448. CarlaEngineSingleLV2* engine = nullptr;
  449. for (int i=0; features[i] != nullptr; ++i)
  450. {
  451. if (std::strcmp(features[i]->URI, LV2_INSTANCE_ACCESS_URI) == 0)
  452. {
  453. engine = (CarlaEngineSingleLV2*)features[i]->data;
  454. break;
  455. }
  456. }
  457. if (engine == nullptr)
  458. {
  459. carla_stderr("Host doesn't support instance-access, cannot show UI");
  460. return nullptr;
  461. }
  462. if (! engine->lv2ui_instantiate(writeFunction, controller, widget, features))
  463. return nullptr;
  464. return (LV2UI_Handle)engine;
  465. }
  466. #define uiPtr ((CarlaEngineSingleLV2*)ui)
  467. static void lv2ui_port_event(LV2UI_Handle ui, uint32_t portIndex, uint32_t bufferSize, uint32_t format, const void* buffer)
  468. {
  469. carla_debug("lv2ui_port_event(%p, %i, %i, %i, %p)", ui, portIndex, bufferSize, format, buffer);
  470. uiPtr->lv2ui_port_event(portIndex, bufferSize, format, buffer);
  471. }
  472. static void lv2ui_cleanup(LV2UI_Handle ui)
  473. {
  474. carla_debug("lv2ui_cleanup(%p)", ui);
  475. uiPtr->lv2ui_cleanup();
  476. }
  477. static int lv2ui_idle(LV2UI_Handle ui)
  478. {
  479. return uiPtr->lv2ui_idle();
  480. }
  481. static int lv2ui_show(LV2UI_Handle ui)
  482. {
  483. carla_debug("lv2ui_show(%p)", ui);
  484. return uiPtr->lv2ui_show();
  485. }
  486. static int lv2ui_hide(LV2UI_Handle ui)
  487. {
  488. carla_debug("lv2ui_hide(%p)", ui);
  489. return uiPtr->lv2ui_hide();
  490. }
  491. static const void* lv2ui_extension_data(const char* uri)
  492. {
  493. carla_debug("lv2ui_extension_data(\"%s\")", uri);
  494. static const LV2UI_Idle_Interface uiidle = { lv2ui_idle };
  495. static const LV2UI_Show_Interface uishow = { lv2ui_show, lv2ui_hide };
  496. if (std::strcmp(uri, LV2_UI__idleInterface) == 0)
  497. return &uiidle;
  498. if (std::strcmp(uri, LV2_UI__showInterface) == 0)
  499. return &uishow;
  500. return nullptr;
  501. }
  502. #undef uiPtr
  503. // --------------------------------------------------------------------------------------------------------------------
  504. // Startup code
  505. CARLA_EXPORT
  506. const LV2_Descriptor* lv2_descriptor(uint32_t index)
  507. {
  508. carla_stdout("lv2_descriptor(%i)", index);
  509. if (index != 0)
  510. return nullptr;
  511. static CarlaString ret;
  512. if (ret.isEmpty())
  513. {
  514. using namespace water;
  515. const File file(File::getSpecialLocation(File::currentExecutableFile).withFileExtension("ttl"));
  516. ret = String("file://" + file.getFullPathName()).toRawUTF8();
  517. }
  518. static const LV2_Descriptor desc = {
  519. /* URI */ ret.buffer(),
  520. /* instantiate */ lv2_instantiate,
  521. /* connect_port */ lv2_connect_port,
  522. /* activate */ lv2_activate,
  523. /* run */ lv2_run,
  524. /* deactivate */ lv2_deactivate,
  525. /* cleanup */ lv2_cleanup,
  526. /* extension_data */ lv2_extension_data
  527. };
  528. return &desc;
  529. }
  530. CARLA_EXPORT
  531. const LV2UI_Descriptor* lv2ui_descriptor(uint32_t index)
  532. {
  533. carla_stdout("lv2ui_descriptor(%i)", index);
  534. static CarlaString ret;
  535. if (ret.isEmpty())
  536. {
  537. using namespace water;
  538. const File file(File::getSpecialLocation(File::currentExecutableFile).getSiblingFile("ext-ui"));
  539. ret = String("file://" + file.getFullPathName()).toRawUTF8();
  540. }
  541. static const LV2UI_Descriptor lv2UiExtDesc = {
  542. /* URI */ ret.buffer(),
  543. /* instantiate */ lv2ui_instantiate,
  544. /* cleanup */ lv2ui_cleanup,
  545. /* port_event */ lv2ui_port_event,
  546. /* extension_data */ lv2ui_extension_data
  547. };
  548. return (index == 0) ? &lv2UiExtDesc : nullptr;
  549. }
  550. // --------------------------------------------------------------------------------------------------------------------