lynx_test_synth_vst3.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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> <tempo>") 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. // (round 190sj: the tempo it was given last, -1 for none; synthlog.py reads the first six fields)
  204. const auto tempo = c != nullptr && (c->state & ProcessContext::kTempoValid) != 0 ? c->tempo : -1.0;
  205. std::fprintf (log, "P%d %.9f %d %d %s %d %.3f\n", id, ppq, (int) n, playing ? 1 : 0, offline ? "off" : "rt", voiceCount, tempo);
  206. }
  207. float* left = nullptr;
  208. float* right = nullptr;
  209. if (data.numOutputs > 0 && data.outputs[0].numChannels >= 2 && n > 0)
  210. {
  211. left = data.outputs[0].channelBuffers32[0];
  212. right = data.outputs[0].channelBuffers32[1];
  213. std::memset (left, 0, sizeof (float) * (size_t) n);
  214. std::memset (right, 0, sizeof (float) * (size_t) n);
  215. }
  216. auto* events = data.inputEvents;
  217. const auto eventCount = events != nullptr ? events->getEventCount() : 0;
  218. int32 next = 0;
  219. Event e {};
  220. auto take = [&] (int32 i) { return events != nullptr && events->getEvent (i, e) == kResultOk; };
  221. bool have = next < eventCount && take (next);
  222. for (int32 s = 0; s < n || (have && n == 0); ++s)
  223. {
  224. while (have && e.sampleOffset <= s)
  225. {
  226. apply (e);
  227. ++next;
  228. have = next < eventCount && take (next);
  229. }
  230. if (n == 0)
  231. break;
  232. ++processed;
  233. float v = 0.0f;
  234. for (int i = 0; i < voiceCount; ++i)
  235. {
  236. auto& voice = voices[i];
  237. v += 0.1f * (float) std::sin (voice.phase);
  238. voice.phase += voice.step;
  239. if (voice.phase > 6.283185307179586)
  240. voice.phase -= 6.283185307179586;
  241. }
  242. if (left != nullptr)
  243. {
  244. left[s] = v;
  245. right[s] = v;
  246. }
  247. }
  248. while (have) // (events past the block's end)
  249. {
  250. apply (e);
  251. ++next;
  252. have = next < eventCount && take (next);
  253. }
  254. if (log != nullptr && eventCount > 0)
  255. std::fflush (log);
  256. return kResultOk;
  257. }
  258. // IEditController (no parameters, no editor)
  259. tresult PLUGIN_API setComponentState (IBStream*) override { return kResultOk; }
  260. int32 PLUGIN_API getParameterCount() override { return 0; }
  261. tresult PLUGIN_API getParameterInfo (int32, ParameterInfo&) override { return kInvalidArgument; }
  262. tresult PLUGIN_API getParamStringByValue (ParamID, ParamValue, String128) override { return kInvalidArgument; }
  263. tresult PLUGIN_API getParamValueByString (ParamID, TChar*, ParamValue&) override { return kInvalidArgument; }
  264. ParamValue PLUGIN_API normalizedParamToPlain (ParamID, ParamValue v) override { return v; }
  265. ParamValue PLUGIN_API plainParamToNormalized (ParamID, ParamValue v) override { return v; }
  266. ParamValue PLUGIN_API getParamNormalized (ParamID) override { return 0.0; }
  267. tresult PLUGIN_API setParamNormalized (ParamID, ParamValue) override { return kResultOk; }
  268. tresult PLUGIN_API setComponentHandler (IComponentHandler*) override { return kResultOk; }
  269. IPlugView* PLUGIN_API createView (FIDString) override { return nullptr; }
  270. private:
  271. struct Voice
  272. {
  273. int key = 0;
  274. int32 noteId = -1;
  275. double phase = 0.0, step = 0.0;
  276. };
  277. void apply (const Event& e)
  278. {
  279. if (e.type == Event::kNoteOnEvent)
  280. {
  281. if (e.noteOn.velocity <= 0.0f)
  282. {
  283. noteOff (e.noteOn.pitch, e.sampleOffset, -1);
  284. return;
  285. }
  286. if ((double) processed < bootMs * 0.001 * rate) // (still booting: the note is lost)
  287. {
  288. if (log != nullptr)
  289. std::fprintf (log, "E%d drop %d %d\n", id, (int) e.noteOn.pitch, (int) e.sampleOffset);
  290. return;
  291. }
  292. if (log != nullptr)
  293. std::fprintf (log, "E%d on %d %d %d\n", id, (int) e.noteOn.pitch, (int) e.sampleOffset, (int) e.noteOn.noteId);
  294. if (voiceCount < maxVoices)
  295. {
  296. auto& v = voices[voiceCount++];
  297. v.key = e.noteOn.pitch;
  298. v.noteId = e.noteOn.noteId;
  299. v.phase = 0.0;
  300. v.step = 6.283185307179586 * 440.0 * std::pow (2.0, (e.noteOn.pitch - 69) / 12.0) / rate;
  301. if (seed != 0) // (round 190jb: this instance's own pitch and phase for the key)
  302. {
  303. auto h = seed ^ ((std::uint32_t) e.noteOn.pitch * 2654435761u);
  304. h ^= h >> 15;
  305. h *= 0x2c1b3c6du;
  306. h ^= h >> 12;
  307. const auto cents = ((double) (h % 10001u) / 10000.0 - 0.5) * 100.0;
  308. v.step *= std::pow (2.0, cents / 1200.0);
  309. v.phase = (double) ((h >> 8) % 6283u) / 1000.0;
  310. }
  311. }
  312. }
  313. else if (e.type == Event::kNoteOffEvent)
  314. noteOff (e.noteOff.pitch, e.sampleOffset, e.noteOff.noteId);
  315. }
  316. void noteOff (int key, int offset, int32 noteId)
  317. {
  318. if (log != nullptr)
  319. std::fprintf (log, "E%d off %d %d %d\n", id, key, offset, (int) noteId);
  320. for (int i = 0; i < voiceCount; ++i)
  321. if (noteId >= 0 ? voices[i].noteId == noteId : voices[i].key == key)
  322. {
  323. for (int j = i + 1; j < voiceCount; ++j)
  324. voices[j - 1] = voices[j];
  325. --voiceCount;
  326. return;
  327. }
  328. }
  329. static constexpr int maxVoices = 64;
  330. Voice voices[maxVoices];
  331. int voiceCount = 0;
  332. double rate = 44100.0;
  333. double bootMs = 0.0; // (round 190hn) LYNX_TEST_SYNTH_BOOT_MS
  334. std::uint32_t seed = 0; // (round 190jb) LYNX_TEST_SYNTH_SEED: this instance's own, never saved
  335. long long processed = 0; // samples processed since the instance was made
  336. bool offline = false;
  337. std::FILE* log = nullptr;
  338. std::atomic<uint32> refs { 1 };
  339. static inline std::atomic<int> made { 0 };
  340. const int id = ++made; // (each instance's lines carry its number)
  341. };
  342. class Factory final : public IPluginFactory2
  343. {
  344. public:
  345. tresult PLUGIN_API queryInterface (const TUID iid, void** obj) override
  346. {
  347. if (FUnknownPrivate::iidEqual (iid, FUnknown::iid) || FUnknownPrivate::iidEqual (iid, IPluginFactory::iid)
  348. || FUnknownPrivate::iidEqual (iid, IPluginFactory2::iid))
  349. {
  350. *obj = static_cast<IPluginFactory2*> (this);
  351. return kResultOk;
  352. }
  353. *obj = nullptr;
  354. return kNoInterface;
  355. }
  356. uint32 PLUGIN_API addRef() override { return 1; }
  357. uint32 PLUGIN_API release() override { return 1; }
  358. tresult PLUGIN_API getFactoryInfo (PFactoryInfo* info) override
  359. {
  360. std::memset (info, 0, sizeof (*info));
  361. std::strcpy (info->vendor, "LYNX");
  362. std::strcpy (info->url, "https://github.com/Ka1-S/LYNX-SHARE");
  363. info->flags = PFactoryInfo::kUnicode;
  364. return kResultOk;
  365. }
  366. int32 PLUGIN_API countClasses() override { return 1; }
  367. tresult PLUGIN_API getClassInfo (int32 index, PClassInfo* info) override
  368. {
  369. if (index != 0)
  370. return kInvalidArgument;
  371. std::memset (info, 0, sizeof (*info));
  372. synthUid.toTUID (info->cid);
  373. info->cardinality = PClassInfo::kManyInstances;
  374. std::strcpy (info->category, kVstAudioEffectClass);
  375. std::strcpy (info->name, "LYNX Test Synth");
  376. return kResultOk;
  377. }
  378. tresult PLUGIN_API getClassInfo2 (int32 index, PClassInfo2* info) override
  379. {
  380. if (index != 0)
  381. return kInvalidArgument;
  382. std::memset (info, 0, sizeof (*info));
  383. synthUid.toTUID (info->cid);
  384. info->cardinality = PClassInfo::kManyInstances;
  385. std::strcpy (info->category, kVstAudioEffectClass);
  386. std::strcpy (info->name, "LYNX Test Synth");
  387. std::strcpy (info->subCategories, "Instrument|Synth");
  388. std::strcpy (info->vendor, "LYNX");
  389. std::strcpy (info->version, "1.0.0");
  390. std::strcpy (info->sdkVersion, "VST 3.7");
  391. return kResultOk;
  392. }
  393. tresult PLUGIN_API createInstance (FIDString cid, FIDString iid, void** obj) override
  394. {
  395. if (! FUnknownPrivate::iidEqual (cid, synthUid.toTUID()))
  396. {
  397. *obj = nullptr;
  398. return kNoInterface;
  399. }
  400. auto* synth = new TestSynth();
  401. const auto result = synth->queryInterface (iid, obj);
  402. synth->release();
  403. return result;
  404. }
  405. };
  406. Factory factory;
  407. } // namespace
  408. extern "C"
  409. {
  410. #if defined(_WIN32)
  411. __declspec (dllexport) IPluginFactory* PLUGIN_API GetPluginFactory() { return static_cast<IPluginFactory2*> (&factory); }
  412. __declspec (dllexport) bool InitDll() { return true; }
  413. __declspec (dllexport) bool ExitDll() { return true; }
  414. #else
  415. // (round 190fg: a Linux build, the bundle's Contents/x86_64-linux/<name>.so)
  416. __attribute__ ((visibility ("default"))) IPluginFactory* PLUGIN_API GetPluginFactory() { return static_cast<IPluginFactory2*> (&factory); }
  417. __attribute__ ((visibility ("default"))) bool ModuleEntry (void*) { return true; }
  418. __attribute__ ((visibility ("default"))) bool ModuleExit() { return true; }
  419. #endif
  420. }