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.

1562 lines
54KB

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