lynx_test_synth_vst3.cpp 18 KB

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