lynx_test_synth_vst3.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. // A minimal VST3 instrument for checking what LYNX sends a hosted synth (round 169c, issue #32). It is built only
  2. // against the VST3 SDK's pluginterfaces (no SDK helper classes) and on purpose has NO IMidiMapping, like many
  3. // third-party synths (KV331 SynthMaster 2): a MIDI controller such as All Notes Off (CC 123) can never reach it.
  4. //
  5. // V=<JUCE>/modules/juce_audio_processors/format_types/VST3_SDK
  6. // zig c++ -shared -O2 -std=c++17 -target x86_64-windows-gnu -I$V tools/testplugin/lynx_test_synth_vst3.cpp \
  7. // $V/pluginterfaces/base/funknown.cpp -lole32 -o "LYNX Test Synth.vst3"
  8. // Linux (round 190fg): g++ -shared -fPIC -O2 -std=c++17 -I$V tools/testplugin/lynx_test_synth_vst3.cpp \
  9. // $V/pluginterfaces/base/funknown.cpp -o "LYNX Test Synth.vst3/Contents/x86_64-linux/LYNX Test Synth.so"
  10. //
  11. // Sound: one sine voice per note on (a second note on of a sounding key adds a second voice, as a polyphonic synth
  12. // does). The voices are kept by noteId, the VST3 way (round 190fg): a note off with an id ends the voice of that id;
  13. // without one (-1) it ends the oldest voice of its key. With the environment variable LYNX_TEST_SYNTH_LOG = a file path
  14. // it appends to <path>.<instance> one line per process call ("P<instance> <ppq> <samples> <playing> <rt|off> <voices>") and per
  15. // event ("E<instance> on|off <key> <sampleOffset> <noteId>"): what the host sent and when.
  16. // Round 190hn (issue #138): LYNX_TEST_SYNTH_BOOT_MS = n makes each instance behave like a hardware emulator booting its
  17. // firmware (gearmulator's JE-8086, ...): for its first n ms of processed audio after it was made, note ons are dropped
  18. // ("E<instance> drop <key> <sampleOffset>" in the log), as a booting firmware drops what arrives meanwhile.
  19. // Round 190jb (exports with the live instances): LYNX_TEST_SYNTH_SEED = 1 gives each instance a random seed of its own,
  20. // made when the instance is made and never saved (an analogue-drift emulation's, a plugin's licence-dependent seed...):
  21. // every key plays detuned by up to ±50 cents and from a phase that depend on that seed. A new instance plays the same
  22. // notes at other pitches; only the instance that played renders what was heard.
  23. #define INIT_CLASS_IID
  24. #include "pluginterfaces/base/funknown.h"
  25. #include "pluginterfaces/base/ipluginbase.h"
  26. #include "pluginterfaces/base/ibstream.h"
  27. #include "pluginterfaces/vst/ivstaudioprocessor.h"
  28. #include "pluginterfaces/vst/ivstcomponent.h"
  29. #include "pluginterfaces/vst/ivsteditcontroller.h"
  30. #include "pluginterfaces/vst/ivstevents.h"
  31. #include "pluginterfaces/vst/ivstprocesscontext.h"
  32. #include "pluginterfaces/gui/iplugview.h"
  33. #include <atomic>
  34. #include <chrono>
  35. #include <cmath>
  36. #include <cstdint>
  37. #include <cstdio>
  38. #include <cstdlib>
  39. #include <cstring>
  40. using namespace Steinberg;
  41. using namespace Steinberg::Vst;
  42. namespace
  43. {
  44. const FUID synthUid (0x4C594E58, 0x54535931, 0x36396331, 0x56535433); // "LYNXTSY169c1VST3"
  45. void copyString (String128 to, const char* from)
  46. {
  47. int i = 0;
  48. for (; from[i] != 0 && i < 127; ++i)
  49. to[i] = (char16) from[i];
  50. to[i] = 0;
  51. }
  52. class TestSynth final : public IComponent, public IAudioProcessor, public IEditController
  53. {
  54. public:
  55. TestSynth() = default;
  56. virtual ~TestSynth()
  57. {
  58. if (log != nullptr)
  59. std::fclose (log);
  60. }
  61. // FUnknown
  62. tresult PLUGIN_API queryInterface (const TUID iid, void** obj) override
  63. {
  64. if (FUnknownPrivate::iidEqual (iid, FUnknown::iid) || FUnknownPrivate::iidEqual (iid, IPluginBase::iid)
  65. || FUnknownPrivate::iidEqual (iid, IComponent::iid))
  66. {
  67. addRef();
  68. *obj = static_cast<IComponent*> (this);
  69. return kResultOk;
  70. }
  71. if (FUnknownPrivate::iidEqual (iid, IAudioProcessor::iid))
  72. {
  73. addRef();
  74. *obj = static_cast<IAudioProcessor*> (this);
  75. return kResultOk;
  76. }
  77. if (FUnknownPrivate::iidEqual (iid, IEditController::iid))
  78. {
  79. addRef();
  80. *obj = static_cast<IEditController*> (this);
  81. return kResultOk;
  82. }
  83. *obj = nullptr;
  84. return kNoInterface;
  85. }
  86. uint32 PLUGIN_API addRef() override { return ++refs; }
  87. uint32 PLUGIN_API release() override
  88. {
  89. const auto r = --refs;
  90. if (r == 0)
  91. delete this;
  92. return r;
  93. }
  94. // IPluginBase (shared by the component and the controller)
  95. tresult PLUGIN_API initialize (FUnknown*) override
  96. {
  97. if (const char* boot = std::getenv ("LYNX_TEST_SYNTH_BOOT_MS"); boot != nullptr)
  98. bootMs = std::atof (boot);
  99. if (const char* seeded = std::getenv ("LYNX_TEST_SYNTH_SEED"); seeded != nullptr && std::atoi (seeded) != 0 && seed == 0)
  100. {
  101. // (the clock and the instance's address: each instance its own, whatever the C++ library's random_device)
  102. auto h = (std::uint64_t) std::chrono::high_resolution_clock::now().time_since_epoch().count() ^ (std::uint64_t) (std::uintptr_t) this;
  103. h ^= h >> 33;
  104. h *= 0xff51afd7ed558ccdULL;
  105. h ^= h >> 33;
  106. seed = (std::uint32_t) h | 1u;
  107. }
  108. if (log == nullptr)
  109. if (const char* path = std::getenv ("LYNX_TEST_SYNTH_LOG"); path != nullptr && *path != 0)
  110. {
  111. char name[1024];
  112. std::snprintf (name, sizeof (name), "%s.%d", path, id); // one file per instance (threads)
  113. log = std::fopen (name, "a");
  114. }
  115. return kResultOk;
  116. }
  117. tresult PLUGIN_API terminate() override { return kResultOk; }
  118. // IComponent
  119. tresult PLUGIN_API getControllerClassId (TUID) override { return kNotImplemented; } // single component
  120. tresult PLUGIN_API setIoMode (IoMode) override { return kResultOk; }
  121. int32 PLUGIN_API getBusCount (MediaType type, BusDirection dir) override
  122. {
  123. if (type == kAudio && dir == kOutput)
  124. return 1;
  125. if (type == kEvent && dir == kInput)
  126. return 1;
  127. return 0;
  128. }
  129. tresult PLUGIN_API getBusInfo (MediaType type, BusDirection dir, int32 index, BusInfo& bus) override
  130. {
  131. if (index != 0)
  132. return kInvalidArgument;
  133. std::memset (&bus, 0, sizeof (bus));
  134. bus.mediaType = type;
  135. bus.direction = dir;
  136. bus.busType = kMain;
  137. bus.flags = BusInfo::kDefaultActive;
  138. if (type == kAudio && dir == kOutput)
  139. {
  140. bus.channelCount = 2;
  141. copyString (bus.name, "Out");
  142. return kResultOk;
  143. }
  144. if (type == kEvent && dir == kInput)
  145. {
  146. bus.channelCount = 16;
  147. copyString (bus.name, "MIDI In");
  148. return kResultOk;
  149. }
  150. return kInvalidArgument;
  151. }
  152. tresult PLUGIN_API getRoutingInfo (RoutingInfo&, RoutingInfo&) override { return kNotImplemented; }
  153. tresult PLUGIN_API activateBus (MediaType, BusDirection, int32, TBool) override { return kResultOk; }
  154. tresult PLUGIN_API setActive (TBool state) override
  155. {
  156. if (! state)
  157. voiceCount = 0;
  158. return kResultOk;
  159. }
  160. tresult PLUGIN_API setState (IBStream*) override { return kResultOk; }
  161. tresult PLUGIN_API getState (IBStream* s) override
  162. {
  163. if (s != nullptr)
  164. {
  165. int32 written = 0;
  166. const char tag[4] = { 'L', 'T', 'S', '1' };
  167. s->write ((void*) tag, 4, &written);
  168. }
  169. return kResultOk;
  170. }
  171. // IAudioProcessor
  172. tresult PLUGIN_API setBusArrangements (SpeakerArrangement*, int32 numIns, SpeakerArrangement* outs, int32 numOuts) override
  173. {
  174. return numIns == 0 && numOuts == 1 && outs[0] == SpeakerArr::kStereo ? kResultTrue : kResultFalse;
  175. }
  176. tresult PLUGIN_API getBusArrangement (BusDirection dir, int32 index, SpeakerArrangement& arr) override
  177. {
  178. if (dir == kOutput && index == 0)
  179. {
  180. arr = SpeakerArr::kStereo;
  181. return kResultOk;
  182. }
  183. return kInvalidArgument;
  184. }
  185. tresult PLUGIN_API canProcessSampleSize (int32 size) override { return size == kSample32 ? kResultTrue : kResultFalse; }
  186. uint32 PLUGIN_API getLatencySamples() override { return 0; }
  187. tresult PLUGIN_API setupProcessing (ProcessSetup& setup) override
  188. {
  189. rate = setup.sampleRate > 0.0 ? setup.sampleRate : 44100.0;
  190. offline = setup.processMode == kOffline;
  191. return kResultOk;
  192. }
  193. tresult PLUGIN_API setProcessing (TBool) override { return kResultOk; }
  194. uint32 PLUGIN_API getTailSamples() override { return 0; }
  195. tresult PLUGIN_API process (ProcessData& data) override
  196. {
  197. const auto n = data.numSamples;
  198. if (log != nullptr)
  199. {
  200. const auto* c = data.processContext;
  201. const auto playing = c != nullptr && (c->state & ProcessContext::kPlaying) != 0;
  202. const auto ppq = c != nullptr && (c->state & ProcessContext::kProjectTimeMusicValid) != 0 ? c->projectTimeMusic : -1.0;
  203. std::fprintf (log, "P%d %.9f %d %d %s %d\n", id, ppq, (int) n, playing ? 1 : 0, offline ? "off" : "rt", voiceCount);
  204. }
  205. float* left = nullptr;
  206. float* right = nullptr;
  207. if (data.numOutputs > 0 && data.outputs[0].numChannels >= 2 && n > 0)
  208. {
  209. left = data.outputs[0].channelBuffers32[0];
  210. right = data.outputs[0].channelBuffers32[1];
  211. std::memset (left, 0, sizeof (float) * (size_t) n);
  212. std::memset (right, 0, sizeof (float) * (size_t) n);
  213. }
  214. auto* events = data.inputEvents;
  215. const auto eventCount = events != nullptr ? events->getEventCount() : 0;
  216. int32 next = 0;
  217. Event e {};
  218. auto take = [&] (int32 i) { return events != nullptr && events->getEvent (i, e) == kResultOk; };
  219. bool have = next < eventCount && take (next);
  220. for (int32 s = 0; s < n || (have && n == 0); ++s)
  221. {
  222. while (have && e.sampleOffset <= s)
  223. {
  224. apply (e);
  225. ++next;
  226. have = next < eventCount && take (next);
  227. }
  228. if (n == 0)
  229. break;
  230. ++processed;
  231. float v = 0.0f;
  232. for (int i = 0; i < voiceCount; ++i)
  233. {
  234. auto& voice = voices[i];
  235. v += 0.1f * (float) std::sin (voice.phase);
  236. voice.phase += voice.step;
  237. if (voice.phase > 6.283185307179586)
  238. voice.phase -= 6.283185307179586;
  239. }
  240. if (left != nullptr)
  241. {
  242. left[s] = v;
  243. right[s] = v;
  244. }
  245. }
  246. while (have) // (events past the block's end)
  247. {
  248. apply (e);
  249. ++next;
  250. have = next < eventCount && take (next);
  251. }
  252. if (log != nullptr && eventCount > 0)
  253. std::fflush (log);
  254. return kResultOk;
  255. }
  256. // IEditController (no parameters, no editor)
  257. tresult PLUGIN_API setComponentState (IBStream*) override { return kResultOk; }
  258. int32 PLUGIN_API getParameterCount() override { return 0; }
  259. tresult PLUGIN_API getParameterInfo (int32, ParameterInfo&) override { return kInvalidArgument; }
  260. tresult PLUGIN_API getParamStringByValue (ParamID, ParamValue, String128) override { return kInvalidArgument; }
  261. tresult PLUGIN_API getParamValueByString (ParamID, TChar*, ParamValue&) override { return kInvalidArgument; }
  262. ParamValue PLUGIN_API normalizedParamToPlain (ParamID, ParamValue v) override { return v; }
  263. ParamValue PLUGIN_API plainParamToNormalized (ParamID, ParamValue v) override { return v; }
  264. ParamValue PLUGIN_API getParamNormalized (ParamID) override { return 0.0; }
  265. tresult PLUGIN_API setParamNormalized (ParamID, ParamValue) override { return kResultOk; }
  266. tresult PLUGIN_API setComponentHandler (IComponentHandler*) override { return kResultOk; }
  267. IPlugView* PLUGIN_API createView (FIDString) override { return nullptr; }
  268. private:
  269. struct Voice
  270. {
  271. int key = 0;
  272. int32 noteId = -1;
  273. double phase = 0.0, step = 0.0;
  274. };
  275. void apply (const Event& e)
  276. {
  277. if (e.type == Event::kNoteOnEvent)
  278. {
  279. if (e.noteOn.velocity <= 0.0f)
  280. {
  281. noteOff (e.noteOn.pitch, e.sampleOffset, -1);
  282. return;
  283. }
  284. if ((double) processed < bootMs * 0.001 * rate) // (still booting: the note is lost)
  285. {
  286. if (log != nullptr)
  287. std::fprintf (log, "E%d drop %d %d\n", id, (int) e.noteOn.pitch, (int) e.sampleOffset);
  288. return;
  289. }
  290. if (log != nullptr)
  291. std::fprintf (log, "E%d on %d %d %d\n", id, (int) e.noteOn.pitch, (int) e.sampleOffset, (int) e.noteOn.noteId);
  292. if (voiceCount < maxVoices)
  293. {
  294. auto& v = voices[voiceCount++];
  295. v.key = e.noteOn.pitch;
  296. v.noteId = e.noteOn.noteId;
  297. v.phase = 0.0;
  298. v.step = 6.283185307179586 * 440.0 * std::pow (2.0, (e.noteOn.pitch - 69) / 12.0) / rate;
  299. if (seed != 0) // (round 190jb: this instance's own pitch and phase for the key)
  300. {
  301. auto h = seed ^ ((std::uint32_t) e.noteOn.pitch * 2654435761u);
  302. h ^= h >> 15;
  303. h *= 0x2c1b3c6du;
  304. h ^= h >> 12;
  305. const auto cents = ((double) (h % 10001u) / 10000.0 - 0.5) * 100.0;
  306. v.step *= std::pow (2.0, cents / 1200.0);
  307. v.phase = (double) ((h >> 8) % 6283u) / 1000.0;
  308. }
  309. }
  310. }
  311. else if (e.type == Event::kNoteOffEvent)
  312. noteOff (e.noteOff.pitch, e.sampleOffset, e.noteOff.noteId);
  313. }
  314. void noteOff (int key, int offset, int32 noteId)
  315. {
  316. if (log != nullptr)
  317. std::fprintf (log, "E%d off %d %d %d\n", id, key, offset, (int) noteId);
  318. for (int i = 0; i < voiceCount; ++i)
  319. if (noteId >= 0 ? voices[i].noteId == noteId : voices[i].key == key)
  320. {
  321. for (int j = i + 1; j < voiceCount; ++j)
  322. voices[j - 1] = voices[j];
  323. --voiceCount;
  324. return;
  325. }
  326. }
  327. static constexpr int maxVoices = 64;
  328. Voice voices[maxVoices];
  329. int voiceCount = 0;
  330. double rate = 44100.0;
  331. double bootMs = 0.0; // (round 190hn) LYNX_TEST_SYNTH_BOOT_MS
  332. std::uint32_t seed = 0; // (round 190jb) LYNX_TEST_SYNTH_SEED: this instance's own, never saved
  333. long long processed = 0; // samples processed since the instance was made
  334. bool offline = false;
  335. std::FILE* log = nullptr;
  336. std::atomic<uint32> refs { 1 };
  337. static inline std::atomic<int> made { 0 };
  338. const int id = ++made; // (each instance's lines carry its number)
  339. };
  340. class Factory final : public IPluginFactory2
  341. {
  342. public:
  343. tresult PLUGIN_API queryInterface (const TUID iid, void** obj) override
  344. {
  345. if (FUnknownPrivate::iidEqual (iid, FUnknown::iid) || FUnknownPrivate::iidEqual (iid, IPluginFactory::iid)
  346. || FUnknownPrivate::iidEqual (iid, IPluginFactory2::iid))
  347. {
  348. *obj = static_cast<IPluginFactory2*> (this);
  349. return kResultOk;
  350. }
  351. *obj = nullptr;
  352. return kNoInterface;
  353. }
  354. uint32 PLUGIN_API addRef() override { return 1; }
  355. uint32 PLUGIN_API release() override { return 1; }
  356. tresult PLUGIN_API getFactoryInfo (PFactoryInfo* info) override
  357. {
  358. std::memset (info, 0, sizeof (*info));
  359. std::strcpy (info->vendor, "LYNX");
  360. std::strcpy (info->url, "https://github.com/Ka1-S/LYNX-SHARE");
  361. info->flags = PFactoryInfo::kUnicode;
  362. return kResultOk;
  363. }
  364. int32 PLUGIN_API countClasses() override { return 1; }
  365. tresult PLUGIN_API getClassInfo (int32 index, PClassInfo* info) override
  366. {
  367. if (index != 0)
  368. return kInvalidArgument;
  369. std::memset (info, 0, sizeof (*info));
  370. synthUid.toTUID (info->cid);
  371. info->cardinality = PClassInfo::kManyInstances;
  372. std::strcpy (info->category, kVstAudioEffectClass);
  373. std::strcpy (info->name, "LYNX Test Synth");
  374. return kResultOk;
  375. }
  376. tresult PLUGIN_API getClassInfo2 (int32 index, PClassInfo2* info) override
  377. {
  378. if (index != 0)
  379. return kInvalidArgument;
  380. std::memset (info, 0, sizeof (*info));
  381. synthUid.toTUID (info->cid);
  382. info->cardinality = PClassInfo::kManyInstances;
  383. std::strcpy (info->category, kVstAudioEffectClass);
  384. std::strcpy (info->name, "LYNX Test Synth");
  385. std::strcpy (info->subCategories, "Instrument|Synth");
  386. std::strcpy (info->vendor, "LYNX");
  387. std::strcpy (info->version, "1.0.0");
  388. std::strcpy (info->sdkVersion, "VST 3.7");
  389. return kResultOk;
  390. }
  391. tresult PLUGIN_API createInstance (FIDString cid, FIDString iid, void** obj) override
  392. {
  393. if (! FUnknownPrivate::iidEqual (cid, synthUid.toTUID()))
  394. {
  395. *obj = nullptr;
  396. return kNoInterface;
  397. }
  398. auto* synth = new TestSynth();
  399. const auto result = synth->queryInterface (iid, obj);
  400. synth->release();
  401. return result;
  402. }
  403. };
  404. Factory factory;
  405. } // namespace
  406. extern "C"
  407. {
  408. #if defined(_WIN32)
  409. __declspec (dllexport) IPluginFactory* PLUGIN_API GetPluginFactory() { return static_cast<IPluginFactory2*> (&factory); }
  410. __declspec (dllexport) bool InitDll() { return true; }
  411. __declspec (dllexport) bool ExitDll() { return true; }
  412. #else
  413. // (round 190fg: a Linux build, the bundle's Contents/x86_64-linux/<name>.so)
  414. __attribute__ ((visibility ("default"))) IPluginFactory* PLUGIN_API GetPluginFactory() { return static_cast<IPluginFactory2*> (&factory); }
  415. __attribute__ ((visibility ("default"))) bool ModuleEntry (void*) { return true; }
  416. __attribute__ ((visibility ("default"))) bool ModuleExit() { return true; }
  417. #endif
  418. }