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.

1576 lines
54KB

  1. /*
  2. * Carla Native Plugins
  3. * Copyright (C) 2013-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. #define CARLA_NATIVE_PLUGIN_LV2
  18. #include "carla-base.cpp"
  19. #include "CarlaLv2Utils.hpp"
  20. #include "CarlaMathUtils.hpp"
  21. #include "CarlaPipeUtils.hpp"
  22. #include "CarlaString.hpp"
  23. #include "water/files/File.h"
  24. static const char* const kPathForCarlaFiles = "carlafiles";
  25. template<>
  26. void Lv2PluginBaseClass<NativeTimeInfo>::clearTimeData() noexcept
  27. {
  28. fLastPositionData.clear();
  29. carla_zeroStruct(fTimeInfo);
  30. }
  31. struct PreviewData {
  32. char type;
  33. uint32_t size;
  34. const void* buffer;
  35. bool shouldSend;
  36. PreviewData()
  37. : type(0),
  38. size(0),
  39. buffer(nullptr),
  40. shouldSend(false) {}
  41. };
  42. // --------------------------------------------------------------------------------------------------------------------
  43. // Carla Internal Plugin API exposed as LV2 plugin
  44. class NativePlugin : public Lv2PluginBaseClass<NativeTimeInfo>
  45. {
  46. public:
  47. static const uint32_t kMaxMidiEvents = 512;
  48. NativePlugin(const NativePluginDescriptor* const desc,
  49. const double sampleRate,
  50. const char* const bundlePath,
  51. const LV2_Feature* const* const features)
  52. : Lv2PluginBaseClass<NativeTimeInfo>(sampleRate, features),
  53. fHandle(nullptr),
  54. fHost(),
  55. fDescriptor(desc),
  56. #ifdef CARLA_PROPER_CPP11_SUPPORT
  57. fProgramDesc({0, 0, nullptr}),
  58. #endif
  59. kIgnoreParameters(std::strncmp(desc->label, "carla", 5) == 0),
  60. fAtomForge(),
  61. fMidiEventCount(0),
  62. fLastProjectPath(),
  63. fLoadedFile(),
  64. fPreviewData(),
  65. fNeedsNotifyFileChanged(false),
  66. fPluginNeedsIdle(0),
  67. fWorkerUISignal(0)
  68. {
  69. carla_zeroStruct(fHost);
  70. #ifndef CARLA_PROPER_CPP11_SUPPORT
  71. carla_zeroStruct(fProgramDesc);
  72. #endif
  73. if (! loadedInProperHost())
  74. return;
  75. using water::File;
  76. using water::String;
  77. String resourceDir(water::File(bundlePath).getChildFile("resources").getFullPathName());
  78. fHost.handle = this;
  79. fHost.resourceDir = carla_strdup(resourceDir.toRawUTF8());
  80. fHost.uiName = nullptr;
  81. fHost.uiParentId = 0;
  82. fHost.get_buffer_size = host_get_buffer_size;
  83. fHost.get_sample_rate = host_get_sample_rate;
  84. fHost.is_offline = host_is_offline;
  85. fHost.get_time_info = host_get_time_info;
  86. fHost.write_midi_event = host_write_midi_event;
  87. fHost.ui_parameter_changed = host_ui_parameter_changed;
  88. fHost.ui_custom_data_changed = host_ui_custom_data_changed;
  89. fHost.ui_closed = host_ui_closed;
  90. fHost.ui_open_file = host_ui_open_file;
  91. fHost.ui_save_file = host_ui_save_file;
  92. fHost.dispatcher = host_dispatcher;
  93. carla_zeroStruct(fAtomForge);
  94. lv2_atom_forge_init(&fAtomForge, fUridMap);
  95. }
  96. ~NativePlugin()
  97. {
  98. CARLA_SAFE_ASSERT(fHandle == nullptr);
  99. if (fHost.resourceDir != nullptr)
  100. {
  101. delete[] fHost.resourceDir;
  102. fHost.resourceDir = nullptr;
  103. }
  104. if (fHost.uiName != nullptr)
  105. {
  106. delete[] fHost.uiName;
  107. fHost.uiName = nullptr;
  108. }
  109. }
  110. // ----------------------------------------------------------------------------------------------------------------
  111. bool init()
  112. {
  113. if (fHost.resourceDir == nullptr)
  114. return false;
  115. if (fDescriptor->instantiate == nullptr || fDescriptor->process == nullptr)
  116. {
  117. carla_stderr("Plugin is missing something...");
  118. return false;
  119. }
  120. carla_zeroStructs(fMidiEvents, kMaxMidiEvents);
  121. fHandle = fDescriptor->instantiate(&fHost);
  122. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr, false);
  123. fPorts.hasUI = fDescriptor->hints & NATIVE_PLUGIN_HAS_UI;
  124. fPorts.usesTime = fDescriptor->hints & NATIVE_PLUGIN_USES_TIME;
  125. fPorts.numAudioIns = fDescriptor->audioIns;
  126. fPorts.numAudioOuts = fDescriptor->audioOuts;
  127. fPorts.numCVIns = fDescriptor->cvIns;
  128. fPorts.numCVOuts = fDescriptor->cvOuts;
  129. fPorts.numMidiIns = fDescriptor->midiIns;
  130. fPorts.numMidiOuts = fDescriptor->midiOuts;
  131. if (fDescriptor->get_parameter_count != nullptr &&
  132. fDescriptor->get_parameter_info != nullptr &&
  133. fDescriptor->get_parameter_value != nullptr &&
  134. fDescriptor->set_parameter_value != nullptr &&
  135. ! kIgnoreParameters)
  136. {
  137. fPorts.numParams = fDescriptor->get_parameter_count(fHandle);
  138. }
  139. fPorts.init();
  140. if (fPorts.numParams > 0)
  141. {
  142. for (uint32_t i=0; i < fPorts.numParams; ++i)
  143. {
  144. fPorts.paramsLast[i] = fDescriptor->get_parameter_value(fHandle, i);
  145. fPorts.paramsOut [i] = fDescriptor->get_parameter_info(fHandle, i)->hints & NATIVE_PARAMETER_IS_OUTPUT;
  146. }
  147. }
  148. return true;
  149. }
  150. // ----------------------------------------------------------------------------------------------------------------
  151. // LV2 functions
  152. void lv2_activate()
  153. {
  154. CARLA_SAFE_ASSERT_RETURN(! fIsActive,);
  155. resetTimeInfo();
  156. if (fDescriptor->activate != nullptr)
  157. fDescriptor->activate(fHandle);
  158. fIsActive = true;
  159. }
  160. void lv2_deactivate()
  161. {
  162. CARLA_SAFE_ASSERT_RETURN(fIsActive,);
  163. fIsActive = false;
  164. if (fDescriptor->deactivate != nullptr)
  165. fDescriptor->deactivate(fHandle);
  166. }
  167. void lv2_cleanup()
  168. {
  169. if (fIsActive)
  170. {
  171. carla_stderr("Warning: Host forgot to call deactivate!");
  172. fIsActive = false;
  173. if (fDescriptor->deactivate != nullptr)
  174. fDescriptor->deactivate(fHandle);
  175. }
  176. if (fDescriptor->cleanup != nullptr)
  177. fDescriptor->cleanup(fHandle);
  178. fHandle = nullptr;
  179. }
  180. // ----------------------------------------------------------------------------------------------------------------
  181. void lv2_run(const uint32_t frames)
  182. {
  183. if (! lv2_pre_run(frames))
  184. {
  185. updateParameterOutputs();
  186. return;
  187. }
  188. if (fPorts.numMidiIns > 0 || fPorts.hasUI)
  189. {
  190. uint32_t numEventPortsIn;
  191. if (fPorts.numMidiIns > 0)
  192. {
  193. numEventPortsIn = fPorts.numMidiIns;
  194. fMidiEventCount = 0;
  195. carla_zeroStructs(fMidiEvents, kMaxMidiEvents);
  196. }
  197. else
  198. {
  199. numEventPortsIn = 1;
  200. }
  201. for (uint32_t i=0; i < numEventPortsIn; ++i)
  202. {
  203. const LV2_Atom_Sequence* const eventPortIn(fPorts.eventsIn[i]);
  204. CARLA_SAFE_ASSERT_CONTINUE(eventPortIn != nullptr);
  205. LV2_ATOM_SEQUENCE_FOREACH(eventPortIn, event)
  206. {
  207. if (event == nullptr)
  208. continue;
  209. if (event->body.type == fURIs.carlaUiEvents && fWorkerUISignal != -1)
  210. {
  211. CARLA_SAFE_ASSERT_CONTINUE((fDescriptor->hints & NATIVE_PLUGIN_NEEDS_UI_OPEN_SAVE) == 0);
  212. if (fWorker != nullptr)
  213. {
  214. // worker is supported by the host, we can continue
  215. fWorkerUISignal = 1;
  216. const char* const msg((const char*)(event + 1));
  217. const size_t msgSize = std::strlen(msg);
  218. fWorker->schedule_work(fWorker->handle, static_cast<uint32_t>(msgSize + 1U), msg);
  219. }
  220. else
  221. {
  222. // worker is not supported, cancel
  223. fWorkerUISignal = -1;
  224. }
  225. continue;
  226. }
  227. if (event->body.type == fURIs.atomObject)
  228. {
  229. const LV2_Atom_Object* const obj = (const LV2_Atom_Object*)(&event->body);
  230. if (obj->body.otype == fURIs.patchSet)
  231. {
  232. // Get property URI.
  233. const LV2_Atom* property = nullptr;
  234. lv2_atom_object_get(obj, fURIs.patchProperty, &property, 0);
  235. CARLA_SAFE_ASSERT_CONTINUE(property != nullptr);
  236. CARLA_SAFE_ASSERT_CONTINUE(property->type == fURIs.atomURID);
  237. const LV2_URID urid = ((const LV2_Atom_URID*)property)->body;
  238. /* */ if (std::strcmp(fDescriptor->label, "audiofile") == 0) {
  239. CARLA_SAFE_ASSERT_CONTINUE(urid == fURIs.carlaFileAudio);
  240. } else if (std::strcmp(fDescriptor->label, "midifile") == 0) {
  241. CARLA_SAFE_ASSERT_CONTINUE(urid == fURIs.carlaFileMIDI);
  242. } else {
  243. CARLA_SAFE_ASSERT_CONTINUE(urid == fURIs.carlaFile);
  244. }
  245. // Get value.
  246. const LV2_Atom* fileobj = nullptr;
  247. lv2_atom_object_get(obj, fURIs.patchValue, &fileobj, 0);
  248. CARLA_SAFE_ASSERT_CONTINUE(fileobj != nullptr);
  249. CARLA_SAFE_ASSERT_CONTINUE(fileobj->type == fURIs.atomPath);
  250. const char* const filepath((const char*)(fileobj + 1));
  251. fWorker->schedule_work(fWorker->handle,
  252. static_cast<uint32_t>(std::strlen(filepath) + 1U),
  253. filepath);
  254. }
  255. else if (obj->body.otype == fURIs.patchGet)
  256. {
  257. if (fDescriptor->hints & NATIVE_PLUGIN_NEEDS_UI_OPEN_SAVE)
  258. fNeedsNotifyFileChanged = true;
  259. if (fPreviewData.buffer != nullptr)
  260. fPreviewData.shouldSend = true;
  261. }
  262. continue;
  263. }
  264. if (event->body.type != fURIs.midiEvent)
  265. continue;
  266. // anything past this point assumes plugin with MIDI input
  267. CARLA_SAFE_ASSERT_CONTINUE(fPorts.numMidiIns > 0);
  268. if (event->body.size > 4)
  269. continue;
  270. if (event->time.frames >= frames)
  271. break;
  272. const uint8_t* const data((const uint8_t*)(event + 1));
  273. NativeMidiEvent& nativeEvent(fMidiEvents[fMidiEventCount++]);
  274. nativeEvent.port = (uint8_t)i;
  275. nativeEvent.size = (uint8_t)event->body.size;
  276. nativeEvent.time = (uint32_t)event->time.frames;
  277. uint32_t j=0;
  278. for (uint32_t size=event->body.size; j<size; ++j)
  279. nativeEvent.data[j] = data[j];
  280. for (; j<4; ++j)
  281. nativeEvent.data[j] = 0;
  282. if (fMidiEventCount >= kMaxMidiEvents)
  283. break;
  284. }
  285. }
  286. if (fNeedsNotifyFileChanged || fPreviewData.shouldSend)
  287. {
  288. uint8_t atomBuf[4096];
  289. LV2_Atom* atom = (LV2_Atom*)atomBuf;
  290. LV2_Atom_Sequence* const seq = fPorts.eventsOut[0];
  291. Ports::EventsOutData& mData(fPorts.eventsOutData[0]);
  292. if (fNeedsNotifyFileChanged)
  293. {
  294. fNeedsNotifyFileChanged = false;
  295. LV2_Atom_Forge atomForge = fAtomForge;
  296. lv2_atom_forge_set_buffer(&atomForge, atomBuf, sizeof(atomBuf));
  297. LV2_Atom_Forge_Frame forgeFrame;
  298. lv2_atom_forge_object(&atomForge, &forgeFrame, 0, fURIs.patchSet);
  299. lv2_atom_forge_key(&atomForge, fURIs.patchProperty);
  300. /* */ if (std::strcmp(fDescriptor->label, "audiofile") == 0) {
  301. lv2_atom_forge_urid(&atomForge, fURIs.carlaFileAudio);
  302. } else if (std::strcmp(fDescriptor->label, "midifile") == 0) {
  303. lv2_atom_forge_urid(&atomForge, fURIs.carlaFileMIDI);
  304. } else {
  305. lv2_atom_forge_urid(&atomForge, fURIs.carlaFile);
  306. }
  307. lv2_atom_forge_key(&atomForge, fURIs.patchValue);
  308. lv2_atom_forge_path(&atomForge,
  309. fLoadedFile.buffer(),
  310. static_cast<uint32_t>(fLoadedFile.length()+1));
  311. lv2_atom_forge_pop(&atomForge, &forgeFrame);
  312. if (sizeof(LV2_Atom_Event) + atom->size <= mData.capacity - mData.offset)
  313. {
  314. LV2_Atom_Event* const aev = (LV2_Atom_Event*)(LV2_ATOM_CONTENTS(LV2_Atom_Sequence, seq) + mData.offset);
  315. aev->time.frames = 0;
  316. aev->body.size = atom->size;
  317. aev->body.type = atom->type;
  318. std::memcpy(LV2_ATOM_BODY(&aev->body), atom + 1, atom->size);
  319. const uint32_t size = lv2_atom_pad_size(static_cast<uint32_t>(sizeof(LV2_Atom_Event) + atom->size));
  320. mData.offset += size;
  321. seq->atom.size += size;
  322. }
  323. }
  324. if (fPreviewData.shouldSend)
  325. {
  326. const char ptype = fPreviewData.type;
  327. const uint32_t psize = fPreviewData.size;
  328. const void* const pbuffer = fPreviewData.buffer;
  329. fPreviewData.shouldSend = false;
  330. LV2_Atom_Forge atomForge = fAtomForge;
  331. lv2_atom_forge_set_buffer(&atomForge, atomBuf, sizeof(atomBuf));
  332. LV2_Atom_Forge_Frame forgeFrame;
  333. lv2_atom_forge_object(&atomForge, &forgeFrame, 0, fURIs.patchSet);
  334. lv2_atom_forge_key(&atomForge, fURIs.patchProperty);
  335. lv2_atom_forge_urid(&atomForge, fURIs.carlaPreview);
  336. lv2_atom_forge_key(&atomForge, fURIs.patchValue);
  337. switch (ptype)
  338. {
  339. case 'b':
  340. lv2_atom_forge_vector(&atomForge, sizeof(int32_t), fURIs.atomBool, psize, pbuffer);
  341. break;
  342. case 'i':
  343. lv2_atom_forge_vector(&atomForge, sizeof(int32_t), fURIs.atomInt, psize, pbuffer);
  344. break;
  345. case 'f':
  346. lv2_atom_forge_vector(&atomForge, sizeof(float), fURIs.atomFloat, psize, pbuffer);
  347. break;
  348. default:
  349. carla_stderr2("Preview data buffer has wrong type '%c' (and size %u)", ptype, psize);
  350. break;
  351. }
  352. lv2_atom_forge_pop(&atomForge, &forgeFrame);
  353. if (sizeof(LV2_Atom_Event) + atom->size <= mData.capacity - mData.offset)
  354. {
  355. LV2_Atom_Event* const aev = (LV2_Atom_Event*)(LV2_ATOM_CONTENTS(LV2_Atom_Sequence, seq) + mData.offset);
  356. aev->time.frames = 0;
  357. aev->body.size = atom->size;
  358. aev->body.type = atom->type;
  359. std::memcpy(LV2_ATOM_BODY(&aev->body), atom + 1, atom->size);
  360. const uint32_t size = lv2_atom_pad_size(static_cast<uint32_t>(sizeof(LV2_Atom_Event) + atom->size));
  361. mData.offset += size;
  362. seq->atom.size += size;
  363. }
  364. }
  365. }
  366. }
  367. fDescriptor->process(fHandle, fPorts.audioCVIns, fPorts.audioCVOuts, frames, fMidiEvents, fMidiEventCount);
  368. if (fPluginNeedsIdle == 1)
  369. {
  370. fPluginNeedsIdle = 2;
  371. const char* const msg = "_idle_";
  372. const size_t msgSize = std::strlen(msg);
  373. fWorker->schedule_work(fWorker->handle, static_cast<uint32_t>(msgSize + 1U), msg);
  374. }
  375. if (fWorkerUISignal == -1 && fPorts.hasUI)
  376. {
  377. const char* const msg = "quit";
  378. const size_t msgSize = 5;
  379. LV2_Atom_Sequence* const seq(fPorts.eventsOut[0]);
  380. Ports::EventsOutData& mData(fPorts.eventsOutData[0]);
  381. if (sizeof(LV2_Atom_Event) + msgSize <= mData.capacity - mData.offset)
  382. {
  383. LV2_Atom_Event* const aev = (LV2_Atom_Event*)(LV2_ATOM_CONTENTS(LV2_Atom_Sequence, seq) + mData.offset);
  384. aev->time.frames = 0;
  385. aev->body.size = msgSize;
  386. aev->body.type = fURIs.carlaUiEvents;
  387. std::memcpy(LV2_ATOM_BODY(&aev->body), msg, msgSize);
  388. const uint32_t size = lv2_atom_pad_size(static_cast<uint32_t>(sizeof(LV2_Atom_Event) + msgSize));
  389. mData.offset += size;
  390. seq->atom.size += size;
  391. fWorkerUISignal = 0;
  392. }
  393. }
  394. lv2_post_run(frames);
  395. updateParameterOutputs();
  396. }
  397. // ----------------------------------------------------------------------------------------------------------------
  398. const LV2_Program_Descriptor* lv2_get_program(const uint32_t index)
  399. {
  400. if (fDescriptor->category == NATIVE_PLUGIN_CATEGORY_SYNTH)
  401. return nullptr;
  402. if (fDescriptor->get_midi_program_count == nullptr)
  403. return nullptr;
  404. if (fDescriptor->get_midi_program_info == nullptr)
  405. return nullptr;
  406. if (index >= fDescriptor->get_midi_program_count(fHandle))
  407. return nullptr;
  408. const NativeMidiProgram* const midiProg(fDescriptor->get_midi_program_info(fHandle, index));
  409. if (midiProg == nullptr)
  410. return nullptr;
  411. fProgramDesc.bank = midiProg->bank;
  412. fProgramDesc.program = midiProg->program;
  413. fProgramDesc.name = midiProg->name;
  414. return &fProgramDesc;
  415. }
  416. void lv2_select_program(uint32_t bank, uint32_t program)
  417. {
  418. if (fDescriptor->category == NATIVE_PLUGIN_CATEGORY_SYNTH)
  419. return;
  420. if (fDescriptor->set_midi_program == nullptr)
  421. return;
  422. fDescriptor->set_midi_program(fHandle, 0, bank, program);
  423. for (uint32_t i=0; i < fPorts.numParams; ++i)
  424. {
  425. fPorts.paramsLast[i] = fDescriptor->get_parameter_value(fHandle, i);
  426. if (fPorts.paramsPtr[i] != nullptr)
  427. *fPorts.paramsPtr[i] = fPorts.paramsLast[i];
  428. }
  429. }
  430. // ----------------------------------------------------------------------------------------------------------------
  431. void cleanupLastProjectPath()
  432. {
  433. fLastProjectPath.clear();
  434. }
  435. void saveLastProjectPathIfPossible(const LV2_Feature* const* const features)
  436. {
  437. if (features == nullptr)
  438. return cleanupLastProjectPath();
  439. const LV2_State_Free_Path* freePath = nullptr;
  440. const LV2_State_Make_Path* makePath = nullptr;
  441. for (int i=0; features[i] != nullptr; ++i)
  442. {
  443. /**/ if (freePath == nullptr && std::strcmp(features[i]->URI, LV2_STATE__freePath) == 0)
  444. freePath = (const LV2_State_Free_Path*)features[i]->data;
  445. else if (makePath == nullptr && std::strcmp(features[i]->URI, LV2_STATE__makePath) == 0)
  446. makePath = (const LV2_State_Make_Path*)features[i]->data;
  447. }
  448. if (makePath == nullptr || makePath->path == nullptr)
  449. return cleanupLastProjectPath();
  450. if (freePath == nullptr)
  451. freePath = fFreePath;
  452. char* const newpath = makePath->path(makePath->handle, kPathForCarlaFiles);
  453. if (newpath == nullptr)
  454. return cleanupLastProjectPath();
  455. fLastProjectPath = CarlaString(water::File(newpath).getParentDirectory().getFullPathName().toRawUTF8());
  456. if (freePath != nullptr && freePath->free_path != nullptr)
  457. freePath->free_path(freePath->handle, newpath);
  458. #ifndef CARLA_OS_WIN
  459. // this is not safe to call under windows
  460. else
  461. std::free(newpath);
  462. #endif
  463. }
  464. LV2_State_Status lv2_save(const LV2_State_Store_Function store, const LV2_State_Handle handle,
  465. const uint32_t /*flags*/, const LV2_Feature* const* const features)
  466. {
  467. saveLastProjectPathIfPossible(features);
  468. if (fDescriptor->hints & NATIVE_PLUGIN_NEEDS_UI_OPEN_SAVE)
  469. {
  470. if (fLoadedFile.isEmpty())
  471. return LV2_STATE_SUCCESS;
  472. const LV2_State_Free_Path* freePath = nullptr;
  473. const LV2_State_Map_Path* mapPath = nullptr;
  474. if (features != nullptr)
  475. {
  476. for (int i=0; features[i] != nullptr; ++i)
  477. {
  478. /**/ if (freePath == nullptr && std::strcmp(features[i]->URI, LV2_STATE__freePath) == 0)
  479. freePath = (const LV2_State_Free_Path*)features[i]->data;
  480. else if (mapPath == nullptr && std::strcmp(features[i]->URI, LV2_STATE__mapPath) == 0)
  481. mapPath = (const LV2_State_Map_Path*)features[i]->data;
  482. }
  483. }
  484. if (mapPath == nullptr || mapPath->abstract_path == nullptr)
  485. return LV2_STATE_ERR_NO_FEATURE;
  486. char* path = mapPath->abstract_path(mapPath->handle, fLoadedFile.buffer());
  487. store(handle,
  488. fUridMap->map(fUridMap->handle, "http://kxstudio.sf.net/ns/carla/file"),
  489. path,
  490. std::strlen(path)+1,
  491. fURIs.atomPath,
  492. LV2_STATE_IS_POD|LV2_STATE_IS_PORTABLE);
  493. if (freePath != nullptr && freePath->free_path != nullptr)
  494. freePath->free_path(freePath->handle, path);
  495. #ifndef CARLA_OS_WIN
  496. // this is not safe to call under windows
  497. else
  498. std::free(path);
  499. #endif
  500. return LV2_STATE_SUCCESS;
  501. }
  502. if ((fDescriptor->hints & NATIVE_PLUGIN_USES_STATE) == 0 || fDescriptor->get_state == nullptr)
  503. return LV2_STATE_ERR_UNKNOWN;
  504. if (char* const state = fDescriptor->get_state(fHandle))
  505. {
  506. store(handle,
  507. fUridMap->map(fUridMap->handle, "http://kxstudio.sf.net/ns/carla/chunk"),
  508. state,
  509. std::strlen(state)+1,
  510. fURIs.atomString,
  511. LV2_STATE_IS_POD|LV2_STATE_IS_PORTABLE);
  512. std::free(state);
  513. return LV2_STATE_SUCCESS;
  514. }
  515. return LV2_STATE_ERR_UNKNOWN;
  516. }
  517. LV2_State_Status lv2_restore(const LV2_State_Retrieve_Function retrieve,
  518. const LV2_State_Handle handle,
  519. uint32_t flags,
  520. const LV2_Feature* const* const features)
  521. {
  522. saveLastProjectPathIfPossible(features);
  523. size_t size = 0;
  524. uint32_t type = 0;
  525. if (fDescriptor->hints & NATIVE_PLUGIN_NEEDS_UI_OPEN_SAVE)
  526. {
  527. size = type = 0;
  528. const void* const data = retrieve(handle,
  529. fUridMap->map(fUridMap->handle, "http://kxstudio.sf.net/ns/carla/file"),
  530. &size, &type, &flags);
  531. if (size <= 1 || type == 0)
  532. return LV2_STATE_ERR_NO_PROPERTY;
  533. CARLA_SAFE_ASSERT_RETURN(type == fURIs.atomPath, LV2_STATE_ERR_UNKNOWN);
  534. const LV2_State_Free_Path* freePath = nullptr;
  535. const LV2_State_Map_Path* mapPath = nullptr;
  536. if (features != nullptr)
  537. {
  538. for (int i=0; features[i] != nullptr; ++i)
  539. {
  540. /**/ if (freePath == nullptr && std::strcmp(features[i]->URI, LV2_STATE__freePath) == 0)
  541. freePath = (const LV2_State_Free_Path*)features[i]->data;
  542. else if (mapPath == nullptr && std::strcmp(features[i]->URI, LV2_STATE__mapPath) == 0)
  543. mapPath = (const LV2_State_Map_Path*)features[i]->data;
  544. }
  545. }
  546. if (mapPath == nullptr || mapPath->absolute_path == nullptr)
  547. return LV2_STATE_ERR_NO_FEATURE;
  548. const char* const filename = (const char*)data;
  549. char* const absolute_filename = mapPath->absolute_path(mapPath->handle, filename);
  550. fLoadedFile = absolute_filename;
  551. if (freePath != nullptr && freePath->free_path != nullptr)
  552. freePath->free_path(freePath->handle, absolute_filename);
  553. #ifndef CARLA_OS_WIN
  554. // this is not safe to call under windows
  555. else
  556. std::free(absolute_filename);
  557. #endif
  558. fNeedsNotifyFileChanged = true;
  559. fDescriptor->set_custom_data(fHandle, "file", fLoadedFile);
  560. return LV2_STATE_SUCCESS;
  561. }
  562. if ((fDescriptor->hints & NATIVE_PLUGIN_USES_STATE) == 0 || fDescriptor->set_state == nullptr)
  563. return LV2_STATE_ERR_UNKNOWN;
  564. size = type = 0;
  565. const void* const data = retrieve(handle,
  566. fUridMap->map(fUridMap->handle, "http://kxstudio.sf.net/ns/carla/chunk"),
  567. &size, &type, &flags);
  568. if (size == 0)
  569. return LV2_STATE_ERR_UNKNOWN;
  570. if (type == 0)
  571. return LV2_STATE_ERR_UNKNOWN;
  572. if (data == nullptr)
  573. return LV2_STATE_ERR_UNKNOWN;
  574. if (type != fURIs.atomString)
  575. return LV2_STATE_ERR_BAD_TYPE;
  576. fDescriptor->set_state(fHandle, (const char*)data);
  577. return LV2_STATE_SUCCESS;
  578. }
  579. // ----------------------------------------------------------------------------------------------------------------
  580. LV2_Worker_Status lv2_work(LV2_Worker_Respond_Function, LV2_Worker_Respond_Handle, uint32_t, const void* data)
  581. {
  582. const char* const msg = (const char*)data;
  583. if (std::strcmp(msg, "_idle_") == 0)
  584. {
  585. if (fDescriptor->hints & NATIVE_PLUGIN_REQUESTS_IDLE)
  586. {
  587. fPluginNeedsIdle = 0;
  588. fDescriptor->dispatcher(fHandle, NATIVE_PLUGIN_OPCODE_IDLE, 0, 0, nullptr, 0.0f);
  589. return LV2_WORKER_SUCCESS;
  590. }
  591. return LV2_WORKER_ERR_UNKNOWN;
  592. }
  593. if (fDescriptor->hints & NATIVE_PLUGIN_NEEDS_UI_OPEN_SAVE)
  594. {
  595. fLoadedFile = msg;
  596. fDescriptor->set_custom_data(fHandle, "file", msg);
  597. return LV2_WORKER_SUCCESS;
  598. }
  599. /**/ if (std::strncmp(msg, "control ", 8) == 0)
  600. {
  601. if (fDescriptor->ui_set_parameter_value == nullptr)
  602. return LV2_WORKER_SUCCESS;
  603. if (const char* const msgSplit = std::strstr(msg+8, " "))
  604. {
  605. const char* const msgIndex = msg+8;
  606. CARLA_SAFE_ASSERT_RETURN(msgSplit - msgIndex < 8, LV2_WORKER_ERR_UNKNOWN);
  607. CARLA_SAFE_ASSERT_RETURN(msgSplit[0] != '\0', LV2_WORKER_ERR_UNKNOWN);
  608. char strBufIndex[8];
  609. carla_zeroChars(strBufIndex, 8);
  610. std::strncpy(strBufIndex, msgIndex, static_cast<size_t>(msgSplit - msgIndex));
  611. const int index = std::atoi(msgIndex) - static_cast<int>(fPorts.indexOffset);
  612. CARLA_SAFE_ASSERT_RETURN(index >= 0, LV2_WORKER_ERR_UNKNOWN);
  613. float value;
  614. {
  615. const CarlaScopedLocale csl;
  616. value = static_cast<float>(std::atof(msgSplit+1));
  617. }
  618. fDescriptor->ui_set_parameter_value(fHandle, static_cast<uint32_t>(index), value);
  619. }
  620. }
  621. else if (std::strcmp(msg, "show") == 0)
  622. {
  623. handleUiShow();
  624. }
  625. else if (std::strcmp(msg, "hide") == 0)
  626. {
  627. handleUiHide();
  628. }
  629. else if (std::strcmp(msg, "idle") == 0)
  630. {
  631. handleUiRun();
  632. }
  633. else if (std::strcmp(msg, "quit") == 0)
  634. {
  635. handleUiClosed();
  636. }
  637. else
  638. {
  639. carla_stdout("lv2_work unknown msg '%s'", msg);
  640. return LV2_WORKER_ERR_UNKNOWN;
  641. }
  642. return LV2_WORKER_SUCCESS;
  643. }
  644. LV2_Worker_Status lv2_work_resp(uint32_t /*size*/, const void* /*body*/)
  645. {
  646. return LV2_WORKER_SUCCESS;
  647. }
  648. const LV2_Inline_Display_Image_Surface* lv2_idisp_render(const uint32_t width, const uint32_t height)
  649. {
  650. CARLA_SAFE_ASSERT_RETURN(fDescriptor->hints & NATIVE_PLUGIN_HAS_INLINE_DISPLAY, nullptr);
  651. CARLA_SAFE_ASSERT_RETURN(fDescriptor->render_inline_display, nullptr);
  652. CARLA_SAFE_ASSERT_RETURN(width > 0, nullptr);
  653. CARLA_SAFE_ASSERT_RETURN(height > 0, nullptr);
  654. const NativeInlineDisplayImageSurface* nsur = fDescriptor->render_inline_display(fHandle, width, height);
  655. CARLA_SAFE_ASSERT_RETURN(nsur != nullptr, nullptr);
  656. return (const LV2_Inline_Display_Image_Surface*)(nsur);
  657. }
  658. // ----------------------------------------------------------------------------------------------------------------
  659. void lv2ui_instantiate(LV2UI_Write_Function writeFunction, LV2UI_Controller controller,
  660. LV2UI_Widget* widget, const LV2_Feature* const* features)
  661. {
  662. fUI.writeFunction = writeFunction;
  663. fUI.controller = controller;
  664. if (fHost.uiName != nullptr)
  665. {
  666. delete[] fHost.uiName;
  667. fHost.uiName = nullptr;
  668. }
  669. // ---------------------------------------------------------------
  670. // see if the host supports external-ui
  671. for (int i=0; features[i] != nullptr; ++i)
  672. {
  673. if (std::strcmp(features[i]->URI, LV2_EXTERNAL_UI__Host) == 0 ||
  674. std::strcmp(features[i]->URI, LV2_EXTERNAL_UI_DEPRECATED_URI) == 0)
  675. {
  676. fUI.host = (const LV2_External_UI_Host*)features[i]->data;
  677. }
  678. if (std::strcmp(features[i]->URI, LV2_UI__touch) == 0)
  679. {
  680. fUI.touch = (const LV2UI_Touch*)features[i]->data;
  681. }
  682. }
  683. if (fUI.host != nullptr)
  684. {
  685. fHost.uiName = carla_strdup(fUI.host->plugin_human_id);
  686. *widget = (LV2_External_UI_Widget_Compat*)this;
  687. return;
  688. }
  689. // ---------------------------------------------------------------
  690. // no external-ui support, use showInterface
  691. for (int i=0; features[i] != nullptr; ++i)
  692. {
  693. if (std::strcmp(features[i]->URI, LV2_OPTIONS__options) != 0)
  694. continue;
  695. const LV2_Options_Option* const options((const LV2_Options_Option*)features[i]->data);
  696. CARLA_SAFE_ASSERT_BREAK(options != nullptr);
  697. for (int j=0; options[j].key != 0; ++j)
  698. {
  699. if (options[j].key != fUridMap->map(fUridMap->handle, LV2_UI__windowTitle))
  700. continue;
  701. const char* const title((const char*)options[j].value);
  702. CARLA_SAFE_ASSERT_BREAK(title != nullptr && title[0] != '\0');
  703. fHost.uiName = carla_strdup(title);
  704. break;
  705. }
  706. break;
  707. }
  708. if (fHost.uiName == nullptr)
  709. fHost.uiName = carla_strdup(fDescriptor->name);
  710. *widget = nullptr;
  711. return;
  712. }
  713. void lv2ui_port_event(uint32_t portIndex, uint32_t bufferSize, uint32_t format, const void* buffer) const
  714. {
  715. if (format != 0 || bufferSize != sizeof(float) || buffer == nullptr)
  716. return;
  717. if (portIndex < fPorts.indexOffset || ! fUI.isVisible)
  718. return;
  719. if (fDescriptor->ui_set_parameter_value == nullptr)
  720. return;
  721. const float value(*(const float*)buffer);
  722. fDescriptor->ui_set_parameter_value(fHandle, portIndex-fPorts.indexOffset, value);
  723. }
  724. // ----------------------------------------------------------------------------------------------------------------
  725. void lv2ui_select_program(uint32_t bank, uint32_t program) const
  726. {
  727. if (fDescriptor->category == NATIVE_PLUGIN_CATEGORY_SYNTH)
  728. return;
  729. if (fDescriptor->ui_set_midi_program == nullptr)
  730. return;
  731. fDescriptor->ui_set_midi_program(fHandle, 0, bank, program);
  732. }
  733. // ----------------------------------------------------------------------------------------------------------------
  734. protected:
  735. void handleUiRun() const override
  736. {
  737. if (fDescriptor->ui_idle != nullptr)
  738. fDescriptor->ui_idle(fHandle);
  739. }
  740. void handleUiShow() override
  741. {
  742. if (fDescriptor->ui_show != nullptr)
  743. fDescriptor->ui_show(fHandle, true);
  744. fUI.isVisible = true;
  745. }
  746. void handleUiHide() override
  747. {
  748. if (fDescriptor->ui_show != nullptr)
  749. fDescriptor->ui_show(fHandle, false);
  750. fUI.isVisible = false;
  751. }
  752. // ----------------------------------------------------------------------------------------------------------------
  753. void handleParameterValueChanged(const uint32_t index, const float value) override
  754. {
  755. fDescriptor->set_parameter_value(fHandle, index, value);
  756. }
  757. void handleBufferSizeChanged(const uint32_t bufferSize) override
  758. {
  759. if (fDescriptor->dispatcher == nullptr)
  760. return;
  761. fDescriptor->dispatcher(fHandle, NATIVE_PLUGIN_OPCODE_BUFFER_SIZE_CHANGED, 0, bufferSize, nullptr, 0.0f);
  762. }
  763. void handleSampleRateChanged(const double sampleRate) override
  764. {
  765. if (fDescriptor->dispatcher == nullptr)
  766. return;
  767. fDescriptor->dispatcher(fHandle, NATIVE_PLUGIN_OPCODE_SAMPLE_RATE_CHANGED, 0, 0, nullptr, (float)sampleRate);
  768. }
  769. // ----------------------------------------------------------------------------------------------------------------
  770. bool handleWriteMidiEvent(const NativeMidiEvent* const event)
  771. {
  772. CARLA_SAFE_ASSERT_RETURN(fPorts.numMidiOuts > 0, false);
  773. CARLA_SAFE_ASSERT_RETURN(event != nullptr, false);
  774. CARLA_SAFE_ASSERT_RETURN(event->size > 0, false);
  775. const uint8_t port(event->port);
  776. CARLA_SAFE_ASSERT_RETURN(port < fPorts.numMidiOuts, false);
  777. LV2_Atom_Sequence* const seq(fPorts.eventsOut[port]);
  778. CARLA_SAFE_ASSERT_RETURN(seq != nullptr, false);
  779. Ports::EventsOutData& mData(fPorts.eventsOutData[port]);
  780. if (sizeof(LV2_Atom_Event) + event->size > mData.capacity - mData.offset)
  781. return false;
  782. LV2_Atom_Event* const aev = (LV2_Atom_Event*)(LV2_ATOM_CONTENTS(LV2_Atom_Sequence, seq) + mData.offset);
  783. aev->time.frames = event->time;
  784. aev->body.size = event->size;
  785. aev->body.type = fURIs.midiEvent;
  786. std::memcpy(LV2_ATOM_BODY(&aev->body), event->data, event->size);
  787. const uint32_t size = lv2_atom_pad_size(static_cast<uint32_t>(sizeof(LV2_Atom_Event) + event->size));
  788. mData.offset += size;
  789. seq->atom.size += size;
  790. return true;
  791. }
  792. void handleUiParameterChanged(const uint32_t index, const float value) const
  793. {
  794. if (kIgnoreParameters || fWorkerUISignal)
  795. return;
  796. if (fUI.writeFunction != nullptr && fUI.controller != nullptr)
  797. fUI.writeFunction(fUI.controller, index+fPorts.indexOffset, sizeof(float), 0, &value);
  798. }
  799. void handleUiParameterTouch(const uint32_t index, const bool touch) const
  800. {
  801. if (kIgnoreParameters)
  802. return;
  803. if (fUI.touch != nullptr && fUI.touch->touch != nullptr)
  804. fUI.touch->touch(fUI.touch->handle, index+fPorts.indexOffset, touch);
  805. }
  806. void handleUiResize(const uint32_t, const uint32_t) const
  807. {
  808. // nothing here
  809. }
  810. void handlePreviewBufferData(const char type, const uint32_t size, const void* const buffer) noexcept
  811. {
  812. fPreviewData.type = type;
  813. fPreviewData.size = size;
  814. fPreviewData.buffer = buffer;
  815. fPreviewData.shouldSend = true;
  816. }
  817. void handleUiCustomDataChanged(const char* const key, const char* const value) const
  818. {
  819. carla_stdout("TODO: handleUiCustomDataChanged %s %s", key, value);
  820. //storeCustomData(key, value);
  821. if (fUI.writeFunction == nullptr || fUI.controller == nullptr)
  822. return;
  823. }
  824. void handleUiClosed()
  825. {
  826. fUI.isVisible = false;
  827. if (fWorkerUISignal)
  828. fWorkerUISignal = -1;
  829. if (fUI.host != nullptr && fUI.host->ui_closed != nullptr && fUI.controller != nullptr)
  830. fUI.host->ui_closed(fUI.controller);
  831. fUI.host = nullptr;
  832. fUI.touch = nullptr;
  833. fUI.writeFunction = nullptr;
  834. fUI.controller = nullptr;
  835. }
  836. const char* handleUiOpenFile(const bool /*isDir*/, const char* const /*title*/, const char* const /*filter*/) const
  837. {
  838. // TODO
  839. return nullptr;
  840. }
  841. const char* handleUiSaveFile(const bool /*isDir*/, const char* const /*title*/, const char* const /*filter*/) const
  842. {
  843. // TODO
  844. return nullptr;
  845. }
  846. intptr_t handleDispatcher(const NativeHostDispatcherOpcode opcode, const int32_t index, const intptr_t value, void* const ptr, const float opt)
  847. {
  848. #ifdef DEBUG
  849. if (opcode != NATIVE_HOST_OPCODE_GET_FILE_PATH)
  850. {
  851. carla_debug("NativePlugin::handleDispatcher(%i, %i, " P_INTPTR ", %p, %f)",
  852. opcode, index, value, ptr, static_cast<double>(opt));
  853. }
  854. #endif
  855. intptr_t ret = 0;
  856. switch (opcode)
  857. {
  858. case NATIVE_HOST_OPCODE_NULL:
  859. case NATIVE_HOST_OPCODE_UPDATE_PARAMETER:
  860. case NATIVE_HOST_OPCODE_UPDATE_MIDI_PROGRAM:
  861. case NATIVE_HOST_OPCODE_RELOAD_PARAMETERS:
  862. case NATIVE_HOST_OPCODE_RELOAD_MIDI_PROGRAMS:
  863. case NATIVE_HOST_OPCODE_RELOAD_ALL:
  864. case NATIVE_HOST_OPCODE_HOST_IDLE:
  865. case NATIVE_HOST_OPCODE_INTERNAL_PLUGIN:
  866. // nothing
  867. break;
  868. case NATIVE_HOST_OPCODE_REQUEST_IDLE:
  869. CARLA_SAFE_ASSERT_RETURN(fDescriptor->hints & NATIVE_PLUGIN_REQUESTS_IDLE, 0);
  870. if (fWorker != nullptr && fPluginNeedsIdle == 0)
  871. {
  872. fPluginNeedsIdle = 1;
  873. return 1;
  874. }
  875. return 0;
  876. case NATIVE_HOST_OPCODE_QUEUE_INLINE_DISPLAY:
  877. if (fInlineDisplay != nullptr && fInlineDisplay->queue_draw != nullptr)
  878. {
  879. fInlineDisplay->queue_draw(fInlineDisplay->handle);
  880. return 1;
  881. }
  882. return 0;
  883. case NATIVE_HOST_OPCODE_GET_FILE_PATH:
  884. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr, 0);
  885. if (std::strcmp((char*)ptr, "carla") == 0 && fLastProjectPath != nullptr)
  886. return static_cast<intptr_t>((uintptr_t)fLastProjectPath.buffer());
  887. break;
  888. case NATIVE_HOST_OPCODE_UI_UNAVAILABLE:
  889. handleUiClosed();
  890. break;
  891. case NATIVE_HOST_OPCODE_UI_TOUCH_PARAMETER:
  892. CARLA_SAFE_ASSERT_RETURN(index >= 0, 0);
  893. handleUiParameterTouch(static_cast<uint32_t>(index), value != 0);
  894. break;
  895. case NATIVE_HOST_OPCODE_UI_RESIZE:
  896. CARLA_SAFE_ASSERT_RETURN(index > 0, 0);
  897. CARLA_SAFE_ASSERT_RETURN(value > 0, 0);
  898. handleUiResize(static_cast<uint32_t>(index), static_cast<uint32_t>(value));
  899. break;
  900. case NATIVE_HOST_OPCODE_PREVIEW_BUFFER_DATA:
  901. CARLA_SAFE_ASSERT_RETURN(index != 0, 0);
  902. CARLA_SAFE_ASSERT_RETURN(index >= 'a', 0);
  903. CARLA_SAFE_ASSERT_RETURN(index <= 'z', 0);
  904. CARLA_SAFE_ASSERT_RETURN(value > 0, 0);
  905. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr, 0);
  906. handlePreviewBufferData(static_cast<char>(index), static_cast<uint32_t>(value), (const void*)ptr);
  907. break;
  908. }
  909. return ret;
  910. // unused for now
  911. (void)opt;
  912. }
  913. void updateParameterOutputs()
  914. {
  915. float value;
  916. for (uint32_t i=0; i < fPorts.numParams; ++i)
  917. {
  918. if (! fPorts.paramsOut[i])
  919. continue;
  920. fPorts.paramsLast[i] = value = fDescriptor->get_parameter_value(fHandle, i);
  921. if (fPorts.paramsPtr[i] != nullptr)
  922. *fPorts.paramsPtr[i] = value;
  923. }
  924. }
  925. // -------------------------------------------------------------------
  926. private:
  927. // Native data
  928. NativePluginHandle fHandle;
  929. NativeHostDescriptor fHost;
  930. const NativePluginDescriptor* const fDescriptor;
  931. LV2_Program_Descriptor fProgramDesc;
  932. // carla as plugin does not implement lv2 parameter API yet, needed for feedback
  933. const bool kIgnoreParameters;
  934. LV2_Atom_Forge fAtomForge;
  935. uint32_t fMidiEventCount;
  936. NativeMidiEvent fMidiEvents[kMaxMidiEvents];
  937. CarlaString fLastProjectPath;
  938. CarlaString fLoadedFile;
  939. PreviewData fPreviewData;
  940. volatile bool fNeedsNotifyFileChanged;
  941. volatile int fPluginNeedsIdle;
  942. int fWorkerUISignal;
  943. // -1 needs close, 0 idle, 1 stuff is writing??
  944. // -------------------------------------------------------------------
  945. #define handlePtr ((NativePlugin*)handle)
  946. static uint32_t host_get_buffer_size(NativeHostHandle handle)
  947. {
  948. return handlePtr->fBufferSize;
  949. }
  950. static double host_get_sample_rate(NativeHostHandle handle)
  951. {
  952. return handlePtr->fSampleRate;
  953. }
  954. static bool host_is_offline(NativeHostHandle handle)
  955. {
  956. return handlePtr->fIsOffline;
  957. }
  958. static const NativeTimeInfo* host_get_time_info(NativeHostHandle handle)
  959. {
  960. return &(handlePtr->fTimeInfo);
  961. }
  962. static bool host_write_midi_event(NativeHostHandle handle, const NativeMidiEvent* event)
  963. {
  964. return handlePtr->handleWriteMidiEvent(event);
  965. }
  966. static void host_ui_parameter_changed(NativeHostHandle handle, uint32_t index, float value)
  967. {
  968. handlePtr->handleUiParameterChanged(index, value);
  969. }
  970. static void host_ui_parameter_touch(NativeHostHandle handle, uint32_t index, bool touch)
  971. {
  972. handlePtr->handleUiParameterTouch(index, touch);
  973. }
  974. static void host_ui_custom_data_changed(NativeHostHandle handle, const char* key, const char* value)
  975. {
  976. handlePtr->handleUiCustomDataChanged(key, value);
  977. }
  978. static void host_ui_closed(NativeHostHandle handle)
  979. {
  980. handlePtr->handleUiClosed();
  981. }
  982. static const char* host_ui_open_file(NativeHostHandle handle, bool isDir, const char* title, const char* filter)
  983. {
  984. return handlePtr->handleUiOpenFile(isDir, title, filter);
  985. }
  986. static const char* host_ui_save_file(NativeHostHandle handle, bool isDir, const char* title, const char* filter)
  987. {
  988. return handlePtr->handleUiSaveFile(isDir, title, filter);
  989. }
  990. static intptr_t host_dispatcher(NativeHostHandle handle, NativeHostDispatcherOpcode opcode, int32_t index, intptr_t value, void* ptr, float opt)
  991. {
  992. return handlePtr->handleDispatcher(opcode, index, value, ptr, opt);
  993. }
  994. #undef handlePtr
  995. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(NativePlugin)
  996. };
  997. // -----------------------------------------------------------------------
  998. // LV2 plugin descriptor functions
  999. static LV2_Handle lv2_instantiate(const LV2_Descriptor* lv2Descriptor, double sampleRate, const char* bundlePath, const LV2_Feature* const* features)
  1000. {
  1001. carla_debug("lv2_instantiate(%p, %g, %s, %p)", lv2Descriptor, sampleRate, bundlePath, features);
  1002. const NativePluginDescriptor* pluginDesc = nullptr;
  1003. const char* pluginLabel = nullptr;
  1004. if (std::strncmp(lv2Descriptor->URI, "http://kxstudio.sf.net/carla/plugins/", 37) == 0)
  1005. pluginLabel = lv2Descriptor->URI+37;
  1006. if (pluginLabel == nullptr)
  1007. {
  1008. carla_stderr("Failed to find carla native plugin with URI \"%s\"", lv2Descriptor->URI);
  1009. return nullptr;
  1010. }
  1011. carla_debug("lv2_instantiate() - looking up label \"%s\"", pluginLabel);
  1012. PluginListManager& plm(PluginListManager::getInstance());
  1013. for (LinkedList<const NativePluginDescriptor*>::Itenerator it = plm.descs.begin2(); it.valid(); it.next())
  1014. {
  1015. const NativePluginDescriptor* const& tmpDesc(it.getValue(nullptr));
  1016. CARLA_SAFE_ASSERT_CONTINUE(tmpDesc != nullptr);
  1017. if (std::strcmp(tmpDesc->label, pluginLabel) == 0)
  1018. {
  1019. pluginDesc = tmpDesc;
  1020. break;
  1021. }
  1022. }
  1023. if (pluginDesc == nullptr)
  1024. {
  1025. carla_stderr("Failed to find carla native plugin with label \"%s\"", pluginLabel);
  1026. return nullptr;
  1027. }
  1028. NativePlugin* const plugin(new NativePlugin(pluginDesc, sampleRate, bundlePath, features));
  1029. if (! plugin->init())
  1030. {
  1031. carla_stderr("Failed to init plugin");
  1032. delete plugin;
  1033. return nullptr;
  1034. }
  1035. return (LV2_Handle)plugin;
  1036. }
  1037. #define instancePtr ((NativePlugin*)instance)
  1038. static void lv2_connect_port(LV2_Handle instance, uint32_t port, void* dataLocation)
  1039. {
  1040. instancePtr->lv2_connect_port(port, dataLocation);
  1041. }
  1042. static void lv2_activate(LV2_Handle instance)
  1043. {
  1044. carla_debug("lv2_activate(%p)", instance);
  1045. instancePtr->lv2_activate();
  1046. }
  1047. static void lv2_run(LV2_Handle instance, uint32_t sampleCount)
  1048. {
  1049. instancePtr->lv2_run(sampleCount);
  1050. }
  1051. static void lv2_deactivate(LV2_Handle instance)
  1052. {
  1053. carla_debug("lv2_deactivate(%p)", instance);
  1054. instancePtr->lv2_deactivate();
  1055. }
  1056. static void lv2_cleanup(LV2_Handle instance)
  1057. {
  1058. carla_debug("lv2_cleanup(%p)", instance);
  1059. instancePtr->lv2_cleanup();
  1060. delete instancePtr;
  1061. }
  1062. static uint32_t lv2_get_options(LV2_Handle instance, LV2_Options_Option* options)
  1063. {
  1064. carla_debug("lv2_get_options(%p, %p)", instance, options);
  1065. return instancePtr->lv2_get_options(options);
  1066. }
  1067. static uint32_t lv2_set_options(LV2_Handle instance, const LV2_Options_Option* options)
  1068. {
  1069. carla_debug("lv2_set_options(%p, %p)", instance, options);
  1070. return instancePtr->lv2_set_options(options);
  1071. }
  1072. static const LV2_Program_Descriptor* lv2_get_program(LV2_Handle instance, uint32_t index)
  1073. {
  1074. carla_debug("lv2_get_program(%p, %i)", instance, index);
  1075. return instancePtr->lv2_get_program(index);
  1076. }
  1077. static void lv2_select_program(LV2_Handle instance, uint32_t bank, uint32_t program)
  1078. {
  1079. carla_debug("lv2_select_program(%p, %i, %i)", instance, bank, program);
  1080. return instancePtr->lv2_select_program(bank, program);
  1081. }
  1082. static LV2_State_Status lv2_save(LV2_Handle instance, LV2_State_Store_Function store, LV2_State_Handle handle, uint32_t flags, const LV2_Feature* const* features)
  1083. {
  1084. carla_debug("lv2_save(%p, %p, %p, %i, %p)", instance, store, handle, flags, features);
  1085. return instancePtr->lv2_save(store, handle, flags, features);
  1086. }
  1087. static LV2_State_Status lv2_restore(LV2_Handle instance, LV2_State_Retrieve_Function retrieve, LV2_State_Handle handle, uint32_t flags, const LV2_Feature* const* features)
  1088. {
  1089. carla_debug("lv2_restore(%p, %p, %p, %i, %p)", instance, retrieve, handle, flags, features);
  1090. return instancePtr->lv2_restore(retrieve, handle, flags, features);
  1091. }
  1092. static LV2_Worker_Status lv2_work(LV2_Handle instance, LV2_Worker_Respond_Function respond, LV2_Worker_Respond_Handle handle, uint32_t size, const void* data)
  1093. {
  1094. carla_debug("work(%p, %p, %p, %u, %p)", instance, respond, handle, size, data);
  1095. return instancePtr->lv2_work(respond, handle, size, data);
  1096. }
  1097. static LV2_Worker_Status lv2_work_resp(LV2_Handle instance, uint32_t size, const void* body)
  1098. {
  1099. carla_debug("work_resp(%p, %u, %p)", instance, size, body);
  1100. return instancePtr->lv2_work_resp(size, body);
  1101. }
  1102. static const LV2_Inline_Display_Image_Surface* lv2_idisp_render(LV2_Handle instance, uint32_t w, uint32_t h)
  1103. {
  1104. // carla_debug("lv2_idisp_render(%p, %u, %u)", instance, w, h);
  1105. return instancePtr->lv2_idisp_render(w, h);
  1106. }
  1107. static const void* lv2_extension_data(const char* uri)
  1108. {
  1109. carla_debug("lv2_extension_data(\"%s\")", uri);
  1110. static const LV2_Options_Interface options = { lv2_get_options, lv2_set_options };
  1111. static const LV2_Programs_Interface programs = { lv2_get_program, lv2_select_program };
  1112. static const LV2_State_Interface state = { lv2_save, lv2_restore };
  1113. static const LV2_Worker_Interface worker = { lv2_work, lv2_work_resp, nullptr };
  1114. static const LV2_Inline_Display_Interface idisp = { lv2_idisp_render };
  1115. if (std::strcmp(uri, LV2_OPTIONS__interface) == 0)
  1116. return &options;
  1117. if (std::strcmp(uri, LV2_PROGRAMS__Interface) == 0)
  1118. return &programs;
  1119. if (std::strcmp(uri, LV2_STATE__interface) == 0)
  1120. return &state;
  1121. if (std::strcmp(uri, LV2_WORKER__interface) == 0)
  1122. return &worker;
  1123. if (std::strcmp(uri, LV2_INLINEDISPLAY__interface) == 0)
  1124. return &idisp;
  1125. return nullptr;
  1126. }
  1127. #undef instancePtr
  1128. #ifdef HAVE_PYQT
  1129. // -----------------------------------------------------------------------
  1130. // LV2 UI descriptor functions
  1131. static LV2UI_Handle lv2ui_instantiate(const LV2UI_Descriptor*, const char*, const char*,
  1132. LV2UI_Write_Function writeFunction, LV2UI_Controller controller,
  1133. LV2UI_Widget* widget, const LV2_Feature* const* features)
  1134. {
  1135. carla_debug("lv2ui_instantiate(..., %p, %p, %p)", writeFunction, controller, widget, features);
  1136. NativePlugin* plugin = nullptr;
  1137. for (int i=0; features[i] != nullptr; ++i)
  1138. {
  1139. if (std::strcmp(features[i]->URI, LV2_INSTANCE_ACCESS_URI) == 0)
  1140. {
  1141. plugin = (NativePlugin*)features[i]->data;
  1142. break;
  1143. }
  1144. }
  1145. if (plugin == nullptr)
  1146. {
  1147. carla_stderr("Host doesn't support instance-access, cannot show UI");
  1148. return nullptr;
  1149. }
  1150. plugin->lv2ui_instantiate(writeFunction, controller, widget, features);
  1151. return (LV2UI_Handle)plugin;
  1152. }
  1153. #define uiPtr ((NativePlugin*)ui)
  1154. static void lv2ui_port_event(LV2UI_Handle ui, uint32_t portIndex, uint32_t bufferSize, uint32_t format, const void* buffer)
  1155. {
  1156. carla_debug("lv2ui_port_event(%p, %i, %i, %i, %p)", ui, portIndex, bufferSize, format, buffer);
  1157. uiPtr->lv2ui_port_event(portIndex, bufferSize, format, buffer);
  1158. }
  1159. static void lv2ui_cleanup(LV2UI_Handle ui)
  1160. {
  1161. carla_debug("lv2ui_cleanup(%p)", ui);
  1162. uiPtr->lv2ui_cleanup();
  1163. }
  1164. static void lv2ui_select_program(LV2UI_Handle ui, uint32_t bank, uint32_t program)
  1165. {
  1166. carla_debug("lv2ui_select_program(%p, %i, %i)", ui, bank, program);
  1167. uiPtr->lv2ui_select_program(bank, program);
  1168. }
  1169. static int lv2ui_idle(LV2UI_Handle ui)
  1170. {
  1171. return uiPtr->lv2ui_idle();
  1172. }
  1173. static int lv2ui_show(LV2UI_Handle ui)
  1174. {
  1175. carla_debug("lv2ui_show(%p)", ui);
  1176. return uiPtr->lv2ui_show();
  1177. }
  1178. static int lv2ui_hide(LV2UI_Handle ui)
  1179. {
  1180. carla_debug("lv2ui_hide(%p)", ui);
  1181. return uiPtr->lv2ui_hide();
  1182. }
  1183. static const void* lv2ui_extension_data(const char* uri)
  1184. {
  1185. carla_stdout("lv2ui_extension_data(\"%s\")", uri);
  1186. static const LV2UI_Idle_Interface uiidle = { lv2ui_idle };
  1187. static const LV2UI_Show_Interface uishow = { lv2ui_show, lv2ui_hide };
  1188. static const LV2_Programs_UI_Interface uiprograms = { lv2ui_select_program };
  1189. if (std::strcmp(uri, LV2_UI__idleInterface) == 0)
  1190. return &uiidle;
  1191. if (std::strcmp(uri, LV2_UI__showInterface) == 0)
  1192. return &uishow;
  1193. if (std::strcmp(uri, LV2_PROGRAMS__UIInterface) == 0)
  1194. return &uiprograms;
  1195. return nullptr;
  1196. }
  1197. #endif
  1198. #undef uiPtr
  1199. // -----------------------------------------------------------------------
  1200. // Startup code
  1201. CARLA_PLUGIN_EXPORT
  1202. const LV2_Descriptor* lv2_descriptor(uint32_t index)
  1203. {
  1204. carla_debug("lv2_descriptor(%i)", index);
  1205. PluginListManager& plm(PluginListManager::getInstance());
  1206. if (index >= plm.descs.count())
  1207. {
  1208. carla_debug("lv2_descriptor(%i) - out of bounds", index);
  1209. return nullptr;
  1210. }
  1211. if (index < plm.lv2Descs.count())
  1212. {
  1213. carla_debug("lv2_descriptor(%i) - found previously allocated", index);
  1214. return plm.lv2Descs.getAt(index, nullptr);
  1215. }
  1216. const NativePluginDescriptor* const pluginDesc(plm.descs.getAt(index, nullptr));
  1217. CARLA_SAFE_ASSERT_RETURN(pluginDesc != nullptr, nullptr);
  1218. CarlaString tmpURI;
  1219. tmpURI = "http://kxstudio.sf.net/carla/plugins/";
  1220. tmpURI += pluginDesc->label;
  1221. carla_debug("lv2_descriptor(%i) - not found, allocating new with uri \"%s\"", index, (const char*)tmpURI);
  1222. const LV2_Descriptor lv2DescTmp = {
  1223. /* URI */ carla_strdup(tmpURI),
  1224. /* instantiate */ lv2_instantiate,
  1225. /* connect_port */ lv2_connect_port,
  1226. /* activate */ lv2_activate,
  1227. /* run */ lv2_run,
  1228. /* deactivate */ lv2_deactivate,
  1229. /* cleanup */ lv2_cleanup,
  1230. /* extension_data */ lv2_extension_data
  1231. };
  1232. LV2_Descriptor* lv2Desc;
  1233. try {
  1234. lv2Desc = new LV2_Descriptor;
  1235. } CARLA_SAFE_EXCEPTION_RETURN("new LV2_Descriptor", nullptr);
  1236. std::memcpy(lv2Desc, &lv2DescTmp, sizeof(LV2_Descriptor));
  1237. plm.lv2Descs.append(lv2Desc);
  1238. return lv2Desc;
  1239. }
  1240. #ifdef HAVE_PYQT
  1241. CARLA_PLUGIN_EXPORT
  1242. const LV2UI_Descriptor* lv2ui_descriptor(uint32_t index)
  1243. {
  1244. carla_debug("lv2ui_descriptor(%i)", index);
  1245. static const LV2UI_Descriptor lv2UiExtDesc = {
  1246. /* URI */ "http://kxstudio.sf.net/carla/ui-ext",
  1247. /* instantiate */ lv2ui_instantiate,
  1248. /* cleanup */ lv2ui_cleanup,
  1249. /* port_event */ lv2ui_port_event,
  1250. /* extension_data */ lv2ui_extension_data
  1251. };
  1252. return (index == 0) ? &lv2UiExtDesc : nullptr;
  1253. }
  1254. #endif
  1255. // -----------------------------------------------------------------------