ClapFormat.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928
  1. #include "engine/ClapFormat.h"
  2. #include "engine/Vst2Format.h"
  3. #include <array>
  4. #include <atomic>
  5. #include <map>
  6. #include <mutex>
  7. #include <unordered_map>
  8. #include <juce_gui_extra/juce_gui_extra.h>
  9. #include <clap/clap.h>
  10. #if JUCE_WINDOWS
  11. #include <windows.h>
  12. #endif
  13. namespace lynx
  14. {
  15. namespace
  16. {
  17. // --- module (the .clap DLL) --------------------------------------------------
  18. // clap_entry.init/deinit apply once per DLL: a loaded module is shared by
  19. // all instances and unloaded when the last one goes away.
  20. class ClapModule
  21. {
  22. public:
  23. static std::shared_ptr<ClapModule> open (const juce::String& path)
  24. {
  25. static std::mutex mutex;
  26. static std::map<juce::String, std::weak_ptr<ClapModule>> modules;
  27. const std::lock_guard<std::mutex> lock (mutex);
  28. if (auto alive = modules[path].lock())
  29. return alive;
  30. auto module = std::shared_ptr<ClapModule> (new ClapModule());
  31. if (! module->library.open (path))
  32. return nullptr;
  33. const auto* entry = static_cast<const clap_plugin_entry_t*> (module->library.getFunction ("clap_entry"));
  34. if (entry == nullptr || ! clap_version_is_compatible (entry->clap_version) || ! entry->init (path.toRawUTF8()))
  35. return nullptr;
  36. module->entry = entry;
  37. module->factory = static_cast<const clap_plugin_factory_t*> (entry->get_factory (CLAP_PLUGIN_FACTORY_ID));
  38. if (module->factory == nullptr)
  39. return nullptr;
  40. modules[path] = module;
  41. return module;
  42. }
  43. ~ClapModule()
  44. {
  45. if (entry != nullptr)
  46. entry->deinit();
  47. library.close();
  48. }
  49. const clap_plugin_factory_t* factory = nullptr;
  50. private:
  51. ClapModule() = default;
  52. juce::DynamicLibrary library;
  53. const clap_plugin_entry_t* entry = nullptr;
  54. };
  55. bool hasFeature (const clap_plugin_descriptor_t& d, const char* feature)
  56. {
  57. for (auto* f = d.features; f != nullptr && *f != nullptr; ++f)
  58. if (std::strcmp (*f, feature) == 0)
  59. return true;
  60. return false;
  61. }
  62. int idHash (const char* pluginId)
  63. {
  64. return juce::String::fromUTF8 (pluginId).hashCode();
  65. }
  66. juce::PluginDescription describe (const clap_plugin_descriptor_t& d, const juce::File& file, int pluginsInFile)
  67. {
  68. juce::PluginDescription p;
  69. p.name = juce::String::fromUTF8 (d.name);
  70. p.descriptiveName = juce::String::fromUTF8 (d.description != nullptr ? d.description : d.name);
  71. p.pluginFormatName = ClapPluginFormat::formatName;
  72. p.manufacturerName = juce::String::fromUTF8 (d.vendor != nullptr ? d.vendor : "");
  73. p.version = juce::String::fromUTF8 (d.version != nullptr ? d.version : "");
  74. p.fileOrIdentifier = file.getFullPathName();
  75. p.lastFileModTime = file.getLastModificationTime();
  76. p.lastInfoUpdateTime = juce::Time::getCurrentTime();
  77. p.uniqueId = p.deprecatedUid = idHash (d.id);
  78. p.isInstrument = hasFeature (d, CLAP_PLUGIN_FEATURE_INSTRUMENT);
  79. p.numInputChannels = p.isInstrument ? 0 : 2;
  80. p.numOutputChannels = 2;
  81. p.hasSharedContainer = pluginsInFile > 1;
  82. juce::StringArray features;
  83. for (auto* f = d.features; f != nullptr && *f != nullptr; ++f)
  84. features.add (juce::String::fromUTF8 (*f));
  85. p.category = features.joinIntoString ("|");
  86. return p;
  87. }
  88. // --- input event list (no allocation on the audio thread) -------------------------
  89. class EventList
  90. {
  91. public:
  92. EventList()
  93. {
  94. pool.resize (64 * 1024);
  95. offsets.reserve (4096);
  96. list.ctx = this;
  97. list.size = [] (const clap_input_events_t* l) { return (uint32_t) static_cast<EventList*> (l->ctx)->offsets.size(); };
  98. list.get = [] (const clap_input_events_t* l, uint32_t i) -> const clap_event_header_t* {
  99. auto* self = static_cast<EventList*> (l->ctx);
  100. return i < self->offsets.size() ? reinterpret_cast<const clap_event_header_t*> (self->pool.data() + self->offsets[i])
  101. : nullptr;
  102. };
  103. }
  104. void clear() noexcept
  105. {
  106. offsets.clear();
  107. used = 0;
  108. }
  109. template <typename Event>
  110. void add (const Event& e) noexcept
  111. {
  112. const auto size = (sizeof (Event) + 7) & ~(std::size_t) 7;
  113. if (used + size > pool.size() || offsets.size() == offsets.capacity())
  114. return; // full: drop it (never allocates)
  115. std::memcpy (pool.data() + used, &e, sizeof (Event));
  116. offsets.push_back ((uint32_t) used);
  117. used += size;
  118. }
  119. const clap_input_events_t* get() const noexcept { return &list; }
  120. private:
  121. std::vector<std::uint8_t> pool;
  122. std::vector<uint32_t> offsets;
  123. std::size_t used = 0;
  124. clap_input_events_t list {};
  125. };
  126. template <typename Event>
  127. Event makeEvent (uint16_t type, uint32_t time)
  128. {
  129. Event e {};
  130. e.header.size = sizeof (Event);
  131. e.header.time = time;
  132. e.header.space_id = CLAP_CORE_EVENT_SPACE_ID;
  133. e.header.type = type;
  134. e.header.flags = 0;
  135. return e;
  136. }
  137. class ClapInstance;
  138. // --- parameter ---------------------------------------------------------------------
  139. class ClapParameter final : public juce::HostedAudioProcessorParameter
  140. {
  141. public:
  142. ClapParameter (ClapInstance& o, const clap_param_info_t& info, double current)
  143. : owner (o),
  144. id (info.id),
  145. cookie (info.cookie),
  146. minimum (info.min_value),
  147. maximum (info.max_value),
  148. defaultValue (info.default_value),
  149. flags (info.flags),
  150. name (juce::String::fromUTF8 (info.name))
  151. {
  152. normalised.store (toNormalised (current));
  153. }
  154. juce::String getParameterID() const override { return juce::String ((juce::int64) id); }
  155. float getValue() const override { return normalised.load(); }
  156. void setValue (float v) override;
  157. float getDefaultValue() const override { return toNormalised (defaultValue); }
  158. juce::String getName (int maximumLength) const override { return name.substring (0, maximumLength); }
  159. juce::String getLabel() const override { return {}; }
  160. float getValueForText (const juce::String& text) const override { return toNormalised (text.getDoubleValue()); }
  161. juce::String getText (float v, int) const override;
  162. bool isAutomatable() const override { return (flags & CLAP_PARAM_IS_AUTOMATABLE) != 0; }
  163. bool isDiscrete() const override { return (flags & CLAP_PARAM_IS_STEPPED) != 0; }
  164. int getNumSteps() const override
  165. {
  166. return isDiscrete() ? juce::jmax (2, (int) (maximum - minimum) + 1) : AudioProcessorParameter::getNumSteps();
  167. }
  168. double toPlain (float v) const noexcept { return minimum + (maximum - minimum) * (double) v; }
  169. float toNormalised (double plain) const noexcept
  170. {
  171. return maximum > minimum ? (float) juce::jlimit (0.0, 1.0, (plain - minimum) / (maximum - minimum)) : 0.0f;
  172. }
  173. void setFromPlugin (double plain) noexcept { normalised.store (toNormalised (plain)); }
  174. ClapInstance& owner;
  175. const clap_id id;
  176. void* const cookie;
  177. private:
  178. const double minimum, maximum, defaultValue;
  179. const uint32_t flags;
  180. const juce::String name;
  181. std::atomic<float> normalised { 0.0f };
  182. };
  183. // --- plugin UI window ----------------------------------------------------------------
  184. class ClapEditor;
  185. // --- instance ------------------------------------------------------------------------
  186. class ClapInstance final : public juce::AudioPluginInstance
  187. {
  188. public:
  189. ClapInstance (std::shared_ptr<ClapModule> m, const clap_plugin_t* p, const juce::PluginDescription& d)
  190. : AudioPluginInstance (busesFor (d)),
  191. plugin (p),
  192. module (std::move (m)),
  193. description (d)
  194. {
  195. }
  196. // Second phase (needs `this` ready as host_data): init + extensions + parameters.
  197. bool initialise()
  198. {
  199. if (! plugin->init (plugin))
  200. return false;
  201. initialised = true;
  202. params = static_cast<const clap_plugin_params_t*> (plugin->get_extension (plugin, CLAP_EXT_PARAMS));
  203. state = static_cast<const clap_plugin_state_t*> (plugin->get_extension (plugin, CLAP_EXT_STATE));
  204. gui = static_cast<const clap_plugin_gui_t*> (plugin->get_extension (plugin, CLAP_EXT_GUI));
  205. latency = static_cast<const clap_plugin_latency_t*> (plugin->get_extension (plugin, CLAP_EXT_LATENCY));
  206. audioPorts = static_cast<const clap_plugin_audio_ports_t*> (plugin->get_extension (plugin, CLAP_EXT_AUDIO_PORTS));
  207. if (const auto* notes = static_cast<const clap_plugin_note_ports_t*> (plugin->get_extension (plugin, CLAP_EXT_NOTE_PORTS)))
  208. {
  209. clap_note_port_info_t info {};
  210. if (notes->count (plugin, true) > 0 && notes->get (plugin, 0, true, &info))
  211. midiDialect = (info.supported_dialects & CLAP_NOTE_DIALECT_CLAP) == 0;
  212. }
  213. inputChannels = mainPortChannels (true, description.isInstrument ? 0 : 2);
  214. outputChannels = juce::jmax (1, mainPortChannels (false, 2));
  215. if (gui != nullptr && ! gui->is_api_supported (plugin, CLAP_WINDOW_API_WIN32, false))
  216. gui = nullptr;
  217. if (params != nullptr)
  218. {
  219. const auto count = params->count (plugin);
  220. for (uint32_t i = 0; i < count; ++i)
  221. {
  222. clap_param_info_t info {};
  223. if (! params->get_info (plugin, i, &info) || (info.flags & CLAP_PARAM_IS_HIDDEN) != 0)
  224. continue;
  225. double value = info.default_value;
  226. params->get_value (plugin, info.id, &value);
  227. auto parameter = std::make_unique<ClapParameter> (*this, info, value);
  228. byId[info.id] = parameter.get();
  229. addHostedParameter (std::move (parameter));
  230. }
  231. }
  232. return true;
  233. }
  234. ~ClapInstance() override
  235. {
  236. *alive = false;
  237. if (active)
  238. {
  239. if (processing)
  240. plugin->stop_processing (plugin);
  241. plugin->deactivate (plugin);
  242. }
  243. if (plugin != nullptr)
  244. plugin->destroy (plugin);
  245. }
  246. static const clap_host_t* hostFor (ClapInstance* self) { return &self->host; }
  247. // --- AudioProcessor -------------------------------------------------------------
  248. const juce::String getName() const override { return description.name; }
  249. void fillInPluginDescription (juce::PluginDescription& d) const override { d = description; }
  250. void prepareToPlay (double sampleRate, int blockSize) override
  251. {
  252. releaseResources();
  253. if (! plugin->activate (plugin, sampleRate, 1, (uint32_t) juce::jmax (1, blockSize)))
  254. return;
  255. active = true;
  256. maxBlock = juce::jmax (1, blockSize);
  257. scratch.setSize (juce::jmax (2, outputChannels), maxBlock);
  258. if (latency != nullptr)
  259. setLatencySamples ((int) latency->get (plugin));
  260. }
  261. void releaseResources() override
  262. {
  263. if (! active)
  264. return;
  265. if (processing)
  266. plugin->stop_processing (plugin);
  267. plugin->deactivate (plugin);
  268. processing = false;
  269. active = false;
  270. }
  271. void processBlock (juce::AudioBuffer<float>& buffer, juce::MidiBuffer& midi) override
  272. {
  273. const auto n = buffer.getNumSamples();
  274. audioThread.store (std::this_thread::get_id());
  275. if (! active || n > maxBlock)
  276. {
  277. buffer.clear();
  278. return;
  279. }
  280. if (! processing)
  281. processing = plugin->start_processing (plugin);
  282. events.clear();
  283. // parameters changed by the host (automation, UI)
  284. PendingParam change;
  285. while (pendingParams.pop (change))
  286. {
  287. auto e = makeEvent<clap_event_param_value_t> (CLAP_EVENT_PARAM_VALUE, 0);
  288. e.param_id = change.id;
  289. e.cookie = change.cookie;
  290. e.note_id = -1;
  291. e.port_index = e.channel = e.key = -1;
  292. e.value = change.value;
  293. events.add (e);
  294. }
  295. for (const auto m : midi)
  296. addMidi (m.getMessage(), (uint32_t) juce::jlimit (0, n - 1, m.samplePosition));
  297. std::array<float*, 16> inputs {};
  298. std::array<float*, 16> outputs {};
  299. for (int ch = 0; ch < inputChannels && ch < (int) inputs.size(); ++ch)
  300. inputs[(std::size_t) ch] = buffer.getWritePointer (juce::jmin (ch, buffer.getNumChannels() - 1));
  301. for (int ch = 0; ch < outputChannels && ch < (int) outputs.size(); ++ch)
  302. {
  303. outputs[(std::size_t) ch] = scratch.getWritePointer (ch);
  304. juce::FloatVectorOperations::clear (outputs[(std::size_t) ch], n);
  305. }
  306. clap_audio_buffer_t in {};
  307. in.data32 = inputs.data();
  308. in.channel_count = (uint32_t) inputChannels;
  309. clap_audio_buffer_t out {};
  310. out.data32 = outputs.data();
  311. out.channel_count = (uint32_t) outputChannels;
  312. clap_output_events_t outEvents {};
  313. outEvents.ctx = this;
  314. outEvents.try_push = [] (const clap_output_events_t* list, const clap_event_header_t* e) {
  315. auto* self = static_cast<ClapInstance*> (list->ctx);
  316. if (e->space_id == CLAP_CORE_EVENT_SPACE_ID && e->type == CLAP_EVENT_PARAM_VALUE)
  317. {
  318. const auto* v = reinterpret_cast<const clap_event_param_value_t*> (e);
  319. if (auto it = self->byId.find (v->param_id); it != self->byId.end())
  320. it->second->setFromPlugin (v->value);
  321. }
  322. return true;
  323. };
  324. clap_process_t process {};
  325. process.steady_time = steadyTime;
  326. process.frames_count = (uint32_t) n;
  327. process.audio_inputs = inputChannels > 0 ? &in : nullptr;
  328. process.audio_inputs_count = inputChannels > 0 ? 1u : 0u;
  329. process.audio_outputs = &out;
  330. process.audio_outputs_count = 1;
  331. process.in_events = events.get();
  332. process.out_events = &outEvents;
  333. plugin->process (plugin, &process);
  334. steadyTime += n;
  335. for (int ch = 0; ch < buffer.getNumChannels(); ++ch)
  336. buffer.copyFrom (ch, 0, scratch, juce::jmin (ch, outputChannels - 1), 0, n);
  337. }
  338. double getTailLengthSeconds() const override { return 0.0; }
  339. bool acceptsMidi() const override { return description.isInstrument; }
  340. bool producesMidi() const override { return false; }
  341. juce::AudioProcessorEditor* createEditor() override;
  342. bool hasEditor() const override { return gui != nullptr; }
  343. int getNumPrograms() override { return 1; }
  344. int getCurrentProgram() override { return 0; }
  345. void setCurrentProgram (int) override {}
  346. const juce::String getProgramName (int) override { return {}; }
  347. void changeProgramName (int, const juce::String&) override {}
  348. void getStateInformation (juce::MemoryBlock& data) override
  349. {
  350. if (state == nullptr)
  351. return;
  352. juce::MemoryOutputStream out (data, false);
  353. clap_ostream_t stream {};
  354. stream.ctx = &out;
  355. stream.write = [] (const clap_ostream_t* s, const void* buffer, uint64_t size) -> int64_t {
  356. return static_cast<juce::MemoryOutputStream*> (s->ctx)->write (buffer, (size_t) size) ? (int64_t) size : -1;
  357. };
  358. state->save (plugin, &stream);
  359. }
  360. void setStateInformation (const void* data, int size) override
  361. {
  362. if (state == nullptr)
  363. return;
  364. juce::MemoryInputStream in (data, (size_t) size, false);
  365. clap_istream_t stream {};
  366. stream.ctx = &in;
  367. stream.read = [] (const clap_istream_t* s, void* buffer, uint64_t bytes) -> int64_t {
  368. return static_cast<juce::MemoryInputStream*> (s->ctx)->read (buffer, (int) juce::jmin<uint64_t> (bytes, 1 << 30));
  369. };
  370. if (state->load (plugin, &stream) && params != nullptr)
  371. for (auto& [paramId, parameter] : byId)
  372. {
  373. double value = 0.0;
  374. if (params->get_value (plugin, paramId, &value))
  375. parameter->setFromPlugin (value);
  376. }
  377. }
  378. // --- used by the parameters and the editor ---------------------------------------------
  379. void queueParam (clap_id id, void* cookie, double value) { pendingParams.push ({ id, cookie, value }); }
  380. juce::String paramText (clap_id id, double value) const
  381. {
  382. char text[256] {};
  383. if (params != nullptr && juce::MessageManager::existsAndIsCurrentThread() && params->value_to_text (plugin, id, value, text, sizeof (text)))
  384. return juce::String::fromUTF8 (text);
  385. return juce::String (value, 3);
  386. }
  387. const clap_plugin_t* plugin;
  388. const clap_plugin_gui_t* gui = nullptr;
  389. juce::Component::SafePointer<juce::Component> editor;
  390. private:
  391. struct PendingParam
  392. {
  393. clap_id id = 0;
  394. void* cookie = nullptr;
  395. double value = 0.0;
  396. };
  397. // single-producer queue (UI thread) to the audio thread
  398. class ParamQueue
  399. {
  400. public:
  401. bool push (const PendingParam& p) noexcept
  402. {
  403. const auto w = write.load();
  404. const auto next = (w + 1) % items.size();
  405. if (next == read.load())
  406. return false;
  407. items[w] = p;
  408. write.store (next);
  409. return true;
  410. }
  411. bool pop (PendingParam& p) noexcept
  412. {
  413. const auto r = read.load();
  414. if (r == write.load())
  415. return false;
  416. p = items[r];
  417. read.store ((r + 1) % items.size());
  418. return true;
  419. }
  420. private:
  421. std::array<PendingParam, 1024> items {};
  422. std::atomic<std::size_t> write { 0 }, read { 0 };
  423. };
  424. static BusesProperties busesFor (const juce::PluginDescription& d)
  425. {
  426. BusesProperties buses;
  427. if (! d.isInstrument)
  428. buses = buses.withInput ("Input", juce::AudioChannelSet::stereo(), true);
  429. return buses.withOutput ("Output", juce::AudioChannelSet::stereo(), true);
  430. }
  431. int mainPortChannels (bool input, int fallback) const
  432. {
  433. if (audioPorts == nullptr)
  434. return fallback;
  435. if (audioPorts->count (plugin, input) == 0)
  436. return 0;
  437. clap_audio_port_info_t info {};
  438. return audioPorts->get (plugin, 0, input, &info) ? juce::jmin (16, (int) info.channel_count) : fallback;
  439. }
  440. void addMidi (const juce::MidiMessage& m, uint32_t time)
  441. {
  442. const auto channel = (int16_t) juce::jlimit (0, 15, m.getChannel() - 1);
  443. if (! midiDialect && (m.isNoteOn() || m.isNoteOff()))
  444. {
  445. const auto on = m.isNoteOn();
  446. auto e = makeEvent<clap_event_note_t> (on ? CLAP_EVENT_NOTE_ON : CLAP_EVENT_NOTE_OFF, time);
  447. e.note_id = -1;
  448. e.port_index = 0;
  449. e.channel = channel;
  450. e.key = (int16_t) m.getNoteNumber();
  451. e.velocity = on ? m.getFloatVelocity() : 0.0;
  452. events.add (e);
  453. heldNotes[(std::size_t) channel * 128 + (std::size_t) m.getNoteNumber()] = on;
  454. return;
  455. }
  456. if (! midiDialect && (m.isAllNotesOff() || m.isAllSoundOff()))
  457. {
  458. // CLAP has no "all notes off": release each held note
  459. for (std::size_t i = 0; i < heldNotes.size(); ++i)
  460. if (heldNotes[i])
  461. {
  462. auto e = makeEvent<clap_event_note_t> (m.isAllSoundOff() ? CLAP_EVENT_NOTE_CHOKE : CLAP_EVENT_NOTE_OFF, time);
  463. e.note_id = -1;
  464. e.port_index = 0;
  465. e.channel = (int16_t) (i / 128);
  466. e.key = (int16_t) (i % 128);
  467. events.add (e);
  468. heldNotes[i] = false;
  469. }
  470. return;
  471. }
  472. if (m.getRawDataSize() <= 3)
  473. {
  474. auto e = makeEvent<clap_event_midi_t> (CLAP_EVENT_MIDI, time);
  475. e.port_index = 0;
  476. std::memcpy (e.data, m.getRawData(), (std::size_t) m.getRawDataSize());
  477. events.add (e);
  478. }
  479. }
  480. // --- the host as seen by the plugin -----------------------------------------------------
  481. static ClapInstance* from (const clap_host_t* h) { return static_cast<ClapInstance*> (h->host_data); }
  482. void onMainThread (std::function<void()> fn)
  483. {
  484. juce::MessageManager::callAsync ([flag = alive, fn = std::move (fn)] {
  485. if (*flag)
  486. fn();
  487. });
  488. }
  489. clap_host_t makeHost()
  490. {
  491. clap_host_t h {};
  492. h.clap_version = CLAP_VERSION;
  493. h.host_data = this;
  494. h.name = "LYNX";
  495. h.vendor = "LYNX";
  496. h.url = "";
  497. h.version = JUCE_APPLICATION_VERSION_STRING;
  498. h.get_extension = [] (const clap_host_t* hh, const char* id) -> const void* {
  499. auto* self = from (hh);
  500. if (std::strcmp (id, CLAP_EXT_LOG) == 0) return &self->hostLog;
  501. if (std::strcmp (id, CLAP_EXT_THREAD_CHECK) == 0) return &self->hostThreadCheck;
  502. if (std::strcmp (id, CLAP_EXT_PARAMS) == 0) return &self->hostParams;
  503. if (std::strcmp (id, CLAP_EXT_STATE) == 0) return &self->hostState;
  504. if (std::strcmp (id, CLAP_EXT_LATENCY) == 0) return &self->hostLatency;
  505. if (std::strcmp (id, CLAP_EXT_GUI) == 0) return &self->hostGui;
  506. return nullptr;
  507. };
  508. h.request_restart = [] (const clap_host_t* hh) {
  509. // restart on the UI thread with the same settings (new latency, ports...)
  510. auto* self = from (hh);
  511. self->onMainThread ([self] {
  512. if (self->active)
  513. {
  514. const auto rate = self->getSampleRate();
  515. const auto block = self->maxBlock;
  516. self->suspendProcessing (true);
  517. self->prepareToPlay (rate, block);
  518. self->suspendProcessing (false);
  519. }
  520. });
  521. };
  522. h.request_process = [] (const clap_host_t*) {};
  523. h.request_callback = [] (const clap_host_t* hh) {
  524. auto* self = from (hh);
  525. self->onMainThread ([self] { self->plugin->on_main_thread (self->plugin); });
  526. };
  527. return h;
  528. }
  529. std::shared_ptr<ClapModule> module;
  530. juce::PluginDescription description;
  531. std::shared_ptr<std::atomic<bool>> alive = std::make_shared<std::atomic<bool>> (true);
  532. public:
  533. clap_host_t host = makeHost();
  534. private:
  535. const clap_plugin_params_t* params = nullptr;
  536. const clap_plugin_state_t* state = nullptr;
  537. const clap_plugin_latency_t* latency = nullptr;
  538. const clap_plugin_audio_ports_t* audioPorts = nullptr;
  539. bool midiDialect = false;
  540. bool initialised = false;
  541. bool active = false, processing = false;
  542. int maxBlock = 0;
  543. int inputChannels = 0, outputChannels = 2;
  544. int64_t steadyTime = 0;
  545. juce::AudioBuffer<float> scratch;
  546. EventList events;
  547. ParamQueue pendingParams;
  548. std::unordered_map<clap_id, ClapParameter*> byId;
  549. std::array<bool, 16 * 128> heldNotes {};
  550. std::atomic<std::thread::id> audioThread {};
  551. clap_host_log_t hostLog { [] (const clap_host_t*, clap_log_severity, const char* msg) { juce::ignoreUnused (msg); DBG ("CLAP: " << msg); } };
  552. clap_host_thread_check_t hostThreadCheck {
  553. [] (const clap_host_t*) { return juce::MessageManager::existsAndIsCurrentThread(); },
  554. [] (const clap_host_t* hh) { return from (hh)->audioThread.load() == std::this_thread::get_id(); }
  555. };
  556. clap_host_params_t hostParams {
  557. [] (const clap_host_t*, clap_param_rescan_flags) {},
  558. [] (const clap_host_t*, clap_id, clap_param_clear_flags) {},
  559. [] (const clap_host_t*) {}
  560. };
  561. clap_host_state_t hostState { [] (const clap_host_t*) {} };
  562. clap_host_latency_t hostLatency { [] (const clap_host_t* hh) {
  563. auto* self = from (hh);
  564. self->onMainThread ([self] {
  565. if (self->latency != nullptr && self->active)
  566. self->setLatencySamples ((int) self->latency->get (self->plugin));
  567. });
  568. } };
  569. clap_host_gui_t hostGui {
  570. [] (const clap_host_t*) {},
  571. [] (const clap_host_t* hh, uint32_t w, uint32_t h) {
  572. auto* self = from (hh);
  573. self->onMainThread ([self, w, h] {
  574. if (auto* e = self->editor.getComponent())
  575. {
  576. const auto scale = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale;
  577. e->setSize (juce::roundToInt (w / scale), juce::roundToInt (h / scale));
  578. }
  579. });
  580. return true;
  581. },
  582. [] (const clap_host_t*) { return false; },
  583. [] (const clap_host_t*) { return false; },
  584. [] (const clap_host_t*, bool) {}
  585. };
  586. };
  587. void ClapParameter::setValue (float v)
  588. {
  589. normalised.store (v);
  590. owner.queueParam (id, cookie, toPlain (v));
  591. }
  592. juce::String ClapParameter::getText (float v, int) const
  593. {
  594. return owner.paramText (id, toPlain (v));
  595. }
  596. // The plugin's native UI inside a child window (HWND) embedded in the component.
  597. class ClapEditor final : public juce::AudioProcessorEditor,
  598. private juce::Timer
  599. {
  600. public:
  601. explicit ClapEditor (ClapInstance& p)
  602. : AudioProcessorEditor (p),
  603. owner (p)
  604. {
  605. const auto scale = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale;
  606. setSize (480, 320);
  607. if (owner.gui != nullptr && owner.gui->create (owner.plugin, CLAP_WINDOW_API_WIN32, false))
  608. {
  609. created = true;
  610. owner.gui->set_scale (owner.plugin, scale);
  611. uint32_t w = 0, h = 0;
  612. if (owner.gui->get_size (owner.plugin, &w, &h) && w > 0 && h > 0)
  613. setSize (juce::roundToInt (w / scale), juce::roundToInt (h / scale));
  614. }
  615. addAndMakeVisible (holder);
  616. owner.editor = this;
  617. startTimer (20);
  618. }
  619. ~ClapEditor() override
  620. {
  621. stopTimer();
  622. if (created)
  623. {
  624. owner.gui->hide (owner.plugin);
  625. owner.gui->destroy (owner.plugin);
  626. }
  627. holder.setHWND (nullptr);
  628. #if JUCE_WINDOWS
  629. if (container != nullptr)
  630. DestroyWindow ((HWND) container);
  631. #endif
  632. }
  633. void resized() override { holder.setBounds (getLocalBounds()); }
  634. void paint (juce::Graphics& g) override
  635. {
  636. if (! created)
  637. {
  638. g.fillAll (juce::Colours::black);
  639. g.setColour (juce::Colours::white);
  640. g.drawText (juce::String::fromUTF8 ("This plugin has no UI of its own"), getLocalBounds(), juce::Justification::centred);
  641. }
  642. }
  643. private:
  644. void timerCallback() override
  645. {
  646. #if JUCE_WINDOWS
  647. // the child window needs a real window as parent: wait until on screen
  648. auto* peer = getPeer();
  649. if (! created || peer == nullptr || container != nullptr)
  650. return;
  651. stopTimer();
  652. const auto scale = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale;
  653. container = CreateWindowExW (0, L"STATIC", L"", WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, 0, 0,
  654. juce::roundToInt (getWidth() * scale), juce::roundToInt (getHeight() * scale),
  655. (HWND) peer->getNativeHandle(), nullptr, nullptr, nullptr);
  656. holder.setHWND (container);
  657. holder.setBounds (getLocalBounds());
  658. clap_window_t window {};
  659. window.api = CLAP_WINDOW_API_WIN32;
  660. window.win32 = container;
  661. owner.gui->set_parent (owner.plugin, &window);
  662. owner.gui->show (owner.plugin);
  663. #else
  664. stopTimer();
  665. #endif
  666. }
  667. ClapInstance& owner;
  668. juce::HWNDComponent holder;
  669. void* container = nullptr;
  670. bool created = false;
  671. };
  672. juce::AudioProcessorEditor* ClapInstance::createEditor()
  673. {
  674. return gui != nullptr ? new ClapEditor (*this) : nullptr;
  675. }
  676. } // namespace
  677. // --- format ----------------------------------------------------------------------------
  678. void ClapPluginFormat::findAllTypesForFile (juce::OwnedArray<juce::PluginDescription>& results, const juce::String& path)
  679. {
  680. if (! fileMightContainThisPluginType (path))
  681. return;
  682. const auto module = ClapModule::open (path);
  683. if (module == nullptr)
  684. return;
  685. const auto count = module->factory->get_plugin_count (module->factory);
  686. for (uint32_t i = 0; i < count; ++i)
  687. if (const auto* d = module->factory->get_plugin_descriptor (module->factory, i))
  688. results.add (new juce::PluginDescription (describe (*d, juce::File (path), (int) count)));
  689. }
  690. bool ClapPluginFormat::fileMightContainThisPluginType (const juce::String& path)
  691. {
  692. const juce::File f (path);
  693. return f.hasFileExtension (".clap") && f.exists();
  694. }
  695. juce::String ClapPluginFormat::getNameOfPluginFromIdentifier (const juce::String& path)
  696. {
  697. return juce::File (path).getFileNameWithoutExtension();
  698. }
  699. bool ClapPluginFormat::pluginNeedsRescanning (const juce::PluginDescription& d)
  700. {
  701. return juce::File (d.fileOrIdentifier).getLastModificationTime() != d.lastFileModTime;
  702. }
  703. bool ClapPluginFormat::doesPluginStillExist (const juce::PluginDescription& d)
  704. {
  705. return juce::File (d.fileOrIdentifier).exists();
  706. }
  707. juce::StringArray ClapPluginFormat::searchPathsForPlugins (const juce::FileSearchPath& directories, bool recursive, bool)
  708. {
  709. juce::StringArray found;
  710. for (int i = 0; i < directories.getNumPaths(); ++i)
  711. for (const auto& f : directories[i].findChildFiles (juce::File::findFilesAndDirectories, recursive, "*.clap"))
  712. found.addIfNotAlreadyThere (f.getFullPathName());
  713. return found;
  714. }
  715. juce::FileSearchPath ClapPluginFormat::getDefaultLocationsToSearch()
  716. {
  717. juce::FileSearchPath paths;
  718. #if JUCE_WINDOWS
  719. paths.add (juce::File::getSpecialLocation (juce::File::globalApplicationsDirectory).getChildFile ("Common Files/CLAP"));
  720. paths.add (juce::File::getSpecialLocation (juce::File::windowsLocalAppData).getChildFile ("Programs/Common/CLAP"));
  721. #endif
  722. return paths;
  723. }
  724. void ClapPluginFormat::createPluginInstance (const juce::PluginDescription& d, double sampleRate, int blockSize,
  725. PluginCreationCallback callback)
  726. {
  727. auto module = ClapModule::open (d.fileOrIdentifier);
  728. if (module == nullptr)
  729. {
  730. callback (nullptr, juce::String::fromUTF8 ("could not load ") + d.fileOrIdentifier);
  731. return;
  732. }
  733. const auto count = module->factory->get_plugin_count (module->factory);
  734. for (uint32_t i = 0; i < count; ++i)
  735. {
  736. const auto* desc = module->factory->get_plugin_descriptor (module->factory, i);
  737. if (desc == nullptr || idHash (desc->id) != d.uniqueId)
  738. continue;
  739. // the host must exist before create_plugin; the instance is created with the plugin afterwards
  740. auto instance = std::unique_ptr<ClapInstance> (new ClapInstance (module, nullptr, d));
  741. const auto* plugin = module->factory->create_plugin (module->factory, ClapInstance::hostFor (instance.get()), desc->id);
  742. if (plugin == nullptr)
  743. break;
  744. instance->plugin = plugin;
  745. if (! instance->initialise())
  746. {
  747. callback (nullptr, juce::String::fromUTF8 ("the plugin refused to start"));
  748. return;
  749. }
  750. instance->setRateAndBufferSizeDetails (sampleRate, blockSize);
  751. callback (std::move (instance), {});
  752. return;
  753. }
  754. callback (nullptr, juce::String::fromUTF8 ("plugin not found in file ") + d.fileOrIdentifier);
  755. }
  756. void addPluginFormats (juce::AudioPluginFormatManager& manager)
  757. {
  758. manager.addDefaultFormats();
  759. manager.addFormat (new ClapPluginFormat());
  760. manager.addFormat (new Vst2PluginFormat());
  761. }
  762. } // namespace lynx