| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787 |
- // fxmeasure — black-box measurement host for third-party audio effects (VST3), Windows console tool.
- //
- // It hosts a plugin the way a DAW does — public parameter API only (names, ranges, value <-> text) — feeds test
- // signals from WAV files and records the outputs. Nothing inside the plugin is inspected (round 99 rule: black-box
- // only); the plugin's own editor is only opened by `editor`, to screenshot it as a user would see it (round 108 UI rule). Build: tools/fxmeasure/build.sh. Analysis scripts: tools/fxmeasure/py.
- //
- // fxmeasure.exe script.txt (one command per line; '#' at the start of a line or " # " starts a comment)
- //
- // Commands:
- // load <file.vst3> [rate] [block] [name] load the first effect in the file (default 48000 Hz, 512 samples), or in a
- // shell (Waves) the one called <name>; name "?" lists the shell's plugins
- // rate <hz> [block] re-prepare at another sample rate / block size
- // sidechain on|off enable every input bus (main + sidechain) or only the main one
- // nonrealtime 0|1 AudioProcessor::setNonRealtime
- // params <out.tsv> [steps] parameter table: index, id, name, label, default, steps, texts at k/steps
- // texts <name|#index> <out.tsv> [steps] value -> text for one parameter at a finer grid
- // set <name|#index> <normalized> set a parameter (normalized 0..1)
- // settext <name|#index> <text> set a parameter from its text (plugin's own text -> value); a text that no value
- // shows (or an unknown parameter in set/settext) stops the script, exit code 3
- // get <name|#index> print value and text
- // defaults every parameter back to its default value
- // reset AudioProcessor::reset
- // transport <bpm> [pos|keep] [0|1] the host tempo, song position (samples) and play state the plugin sees
- // settle <seconds> process silence (parameter smoothing, envelopes)
- // process <in.wav> <out.wav> [sc.wav] run the input (and optional sidechain) through, write a 32-bit float WAV
- // latency print the reported latency in samples
- // savestate <file> / loadstate <file>
- // savecomponent <file> / loadcomponent <file> the raw VST3 component state (as a DAW project stores it)
- // pump <ms> deliver the plugin's pending Win32 messages for a while
- // editor <out.png> [ms] [x y] open the plugin's own editor in a window, let it draw (default 1500 ms), optionally
- // click at (x, y) as a user would (a trial's "Evaluate"), save a PNG (PrintWindow)
- // editor <out.png> <ms> [action]... (round tp172b6) each action runs in order, posted to the editor's own window (no
- // injected input): x y (click), drag x0 y0 x1 y1, hover x y, wheel x y delta, dblclick x y, play <wav> (run the file
- // through the plugin while the editor draws), shot <out.png> (a picture now). Every
- // parameter an action changed is logged ("changed <name> a -> b (text)")
- // echo <text>
- // editor <ms> [x y] show the plugin's own editor in a window at (x, y) for ms milliseconds (for screenshots
- // taken from outside, e.g. with a screen-capture script); prints its screen bounds
- #include <thread>
- #include <atomic>
- #include <juce_audio_processors/juce_audio_processors.h>
- #include <juce_audio_formats/juce_audio_formats.h>
- #include <juce_events/juce_events.h>
- #include <juce_gui_basics/juce_gui_basics.h>
- #include <cstdio>
- #include <cstdlib>
- #include <windows.h>
- namespace
- {
- struct Host
- {
- juce::AudioPluginFormatManager formats;
- std::unique_ptr<juce::AudioPluginInstance> plugin;
- bool failed = false; // a set/settext the script cannot apply: the run stops, exit code 3
- double rate = 48000.0;
- int block = 512;
- bool sidechain = false;
- juce::MidiBuffer midi;
- struct PlayHead final : juce::AudioPlayHead
- {
- juce::int64 samples = 0;
- double rate = 48000.0, bpm = 120.0;
- bool playing = true;
- juce::Optional<PositionInfo> getPosition() const override
- {
- PositionInfo p;
- p.setBpm (bpm);
- p.setTimeSignature (TimeSignature { 4, 4 });
- p.setTimeInSamples (samples);
- p.setTimeInSeconds ((double) samples / rate);
- p.setPpqPosition ((double) samples / rate * bpm / 60.0);
- p.setIsPlaying (playing);
- return p;
- }
- } playHead;
- void log (const juce::String& s) { std::printf ("%s\n", s.toRawUTF8()); std::fflush (stdout); }
- bool prepare()
- {
- if (plugin == nullptr) return false;
- plugin->releaseResources();
- auto layout = plugin->getBusesLayout();
- // some plugins (Valhalla) come up with their main buses disabled: ask for stereo in / out
- if (! layout.inputBuses.isEmpty() && layout.inputBuses[0].size() == 0) layout.inputBuses.getReference (0) = juce::AudioChannelSet::stereo();
- if (! layout.outputBuses.isEmpty() && layout.outputBuses[0].size() == 0) layout.outputBuses.getReference (0) = juce::AudioChannelSet::stereo();
- for (int b = 1; b < layout.inputBuses.size(); ++b)
- if (sidechain) layout.inputBuses.getReference (b) = juce::AudioChannelSet::stereo();
- else layout.inputBuses.getReference (b) = juce::AudioChannelSet::disabled();
- // some plugins (JUCE-based ones among them) report their main buses disabled until a host asks for a layout:
- // ask for stereo in / stereo out, then mono in / stereo out
- if (layout.getMainInputChannels() == 0 && layout.inputBuses.size() > 0)
- layout.inputBuses.getReference (0) = juce::AudioChannelSet::stereo();
- if (layout.getMainOutputChannels() == 0 && layout.outputBuses.size() > 0)
- layout.outputBuses.getReference (0) = juce::AudioChannelSet::stereo();
- // round 170c: a shell plugin (Waves "CLA-2A Stereo") may come up with a 5-channel main bus and then passes the
- // audio through untouched: ask for stereo whenever the plugin supports it
- if (! layout.inputBuses.isEmpty() && ! layout.outputBuses.isEmpty()
- && (layout.inputBuses[0].size() > 2 || layout.outputBuses[0].size() > 2))
- {
- auto stereo = layout;
- stereo.inputBuses.getReference (0) = juce::AudioChannelSet::stereo();
- stereo.outputBuses.getReference (0) = juce::AudioChannelSet::stereo();
- if (plugin->checkBusesLayoutSupported (stereo) || plugin->setBusesLayout (stereo))
- layout = plugin->getBusesLayout();
- log ("stereo request: in=" + juce::String (layout.getMainInputChannels()) + " out=" + juce::String (layout.getMainOutputChannels()));
- }
- if (! plugin->checkBusesLayoutSupported (layout) && layout.inputBuses.size() > 0)
- {
- auto mono = layout;
- mono.inputBuses.getReference (0) = juce::AudioChannelSet::mono();
- if (plugin->checkBusesLayoutSupported (mono))
- layout = mono;
- }
- if (! plugin->setBusesLayout (layout))
- {
- // fall back to enabling the buses one by one
- for (int b = 1; b < plugin->getBusCount (true); ++b)
- if (auto* bus = plugin->getBus (true, b)) bus->enable (sidechain);
- }
- plugin->setRateAndBufferSizeDetails (rate, block);
- plugin->setPlayHead (&playHead);
- playHead.rate = rate;
- plugin->prepareToPlay (rate, block);
- log ("prepared rate=" + juce::String (rate) + " block=" + juce::String (block) + " in=" + juce::String (plugin->getTotalNumInputChannels())
- + " out=" + juce::String (plugin->getTotalNumOutputChannels()) + " mainIn=" + juce::String (plugin->getMainBusNumInputChannels())
- + " latency=" + juce::String (plugin->getLatencySamples()));
- return true;
- }
- juce::AudioProcessorParameter* find (const juce::String& key)
- {
- if (plugin == nullptr) return nullptr;
- const auto& ps = plugin->getParameters();
- if (key.startsWithChar ('#'))
- {
- const int i = key.substring (1).getIntValue();
- return juce::isPositiveAndBelow (i, ps.size()) ? ps[i] : nullptr;
- }
- for (auto* p : ps)
- if (p->getName (256) == key) return p;
- for (auto* p : ps)
- if (p->getName (256).equalsIgnoreCase (key)) return p;
- return nullptr;
- }
- // the plugin's asynchronous messages (latency changes, parameter echoes) are delivered through the Win32 queue
- static void pump (int ms)
- {
- const auto end = juce::Time::getMillisecondCounter() + (juce::uint32) ms;
- do
- {
- MSG msg;
- while (PeekMessageW (&msg, nullptr, 0, 0, PM_REMOVE))
- {
- TranslateMessage (&msg);
- DispatchMessageW (&msg);
- }
- if (ms > 0) Sleep (1);
- } while (juce::Time::getMillisecondCounter() < end);
- }
- // the plugin's editor in a top-level window, captured with PrintWindow (round 108: reference screenshots)
- void editorShot (const juce::File& out, int ms, const juce::StringArray& actions = {})
- {
- std::unique_ptr<juce::AudioProcessorEditor> ed (plugin->createEditorIfNeeded());
- if (ed == nullptr) { log ("error: no editor"); return; }
- juce::DocumentWindow w (plugin->getName(), juce::Colours::black, 0, true);
- w.setUsingNativeTitleBar (true);
- w.setContentNonOwned (ed.get(), true);
- w.setTopLeftPosition (40, 40);
- w.setVisible (true);
- w.toFront (false);
- runSilence ((int) rate / 4);
- pump (ms);
- auto* hwnd = (HWND) w.getPeer()->getNativeHandle();
- // the deepest child window at a client point of hwnd, and the point in that child's coordinates
- const auto hit = [hwnd] (POINT pt, LPARAM& lp)
- {
- HWND target = hwnd;
- for (;;)
- {
- POINT local = pt;
- MapWindowPoints (hwnd, target, &local, 1);
- HWND child = ChildWindowFromPointEx (target, local, CWP_SKIPINVISIBLE);
- if (child == nullptr || child == target) break;
- target = child;
- }
- POINT local = pt;
- MapWindowPoints (hwnd, target, &local, 1);
- lp = MAKELPARAM (local.x, local.y);
- return target;
- };
- std::vector<float> before;
- const auto remember = [&] { before.clear(); for (auto* p : plugin->getParameters()) before.push_back (p->getValue()); };
- const auto logChanges = [&]
- {
- const auto& ps = plugin->getParameters();
- for (int i = 0; i < ps.size() && i < (int) before.size(); ++i)
- if (std::abs (ps[i]->getValue() - before[(size_t) i]) > 1.0e-5f)
- log ("changed " + ps[i]->getName (256) + " " + norm (before[(size_t) i]) + " -> " + norm (ps[i]->getValue()) + " (" + ps[i]->getCurrentValueAsText() + ")");
- };
- for (int i = 0; i < actions.size();)
- {
- remember();
- if (actions[i] == "shot")
- {
- windowPicture (hwnd, juce::File (actions[i + 1]));
- i += 2;
- }
- else if (actions[i] == "play")
- {
- playWhileDrawing (juce::File (actions[i + 1]));
- i += 2;
- }
- else if (actions[i] == "hover")
- {
- LPARAM lp;
- const POINT pt { actions[i + 1].getIntValue(), actions[i + 2].getIntValue() };
- auto* target = hit (pt, lp);
- PostMessageW (target, WM_MOUSEMOVE, 0, lp);
- pump (ms);
- i += 3;
- }
- else if (actions[i] == "wheel") // wheel x y <delta, 120 = one notch up>
- {
- const POINT pt { actions[i + 1].getIntValue(), actions[i + 2].getIntValue() };
- POINT screen = pt;
- ClientToScreen (hwnd, &screen);
- LPARAM lp;
- auto* target = hit (pt, lp);
- PostMessageW (target, WM_MOUSEMOVE, 0, lp);
- pump (60);
- PostMessageW (target, WM_MOUSEWHEEL, MAKEWPARAM (0, (short) actions[i + 3].getIntValue()), MAKELPARAM (screen.x, screen.y));
- pump (ms);
- i += 4;
- }
- else if (actions[i] == "menu") // menu x y: a click that opens a native pop-up menu: its items go to the log, then it is cancelled
- {
- LPARAM lp;
- const POINT pt { actions[i + 1].getIntValue(), actions[i + 2].getIntValue() };
- auto* target = hit (pt, lp);
- std::atomic<bool> done { false };
- std::thread reader ([&done] {
- for (int tries = 0; tries < 200 && ! done.load(); ++tries)
- {
- Sleep (25);
- HWND popup = nullptr;
- while ((popup = FindWindowExW (nullptr, popup, L"#32768", nullptr)) != nullptr)
- {
- DWORD pid = 0;
- GetWindowThreadProcessId (popup, &pid);
- if (pid != GetCurrentProcessId() || ! IsWindowVisible (popup))
- continue;
- Sleep (150);
- logMenu ((HMENU) SendMessageW (popup, 0x01E1 /* MN_GETHMENU */, 0, 0), 0);
- PostMessageW (popup, WM_KEYDOWN, VK_ESCAPE, 0);
- return;
- }
- }
- std::printf ("menu: no pop-up menu opened\n");
- std::fflush (stdout);
- });
- PostMessageW (target, WM_MOUSEMOVE, 0, lp);
- PostMessageW (target, WM_LBUTTONDOWN, MK_LBUTTON, lp);
- pump (80);
- PostMessageW (target, WM_LBUTTONUP, 0, lp);
- pump (ms);
- done = true;
- reader.join();
- i += 3;
- }
- else if (actions[i] == "dblclick")
- {
- LPARAM lp;
- const POINT pt { actions[i + 1].getIntValue(), actions[i + 2].getIntValue() };
- auto* target = hit (pt, lp);
- PostMessageW (target, WM_MOUSEMOVE, 0, lp);
- PostMessageW (target, WM_LBUTTONDOWN, MK_LBUTTON, lp);
- PostMessageW (target, WM_LBUTTONUP, 0, lp);
- PostMessageW (target, WM_LBUTTONDBLCLK, MK_LBUTTON, lp);
- PostMessageW (target, WM_LBUTTONUP, 0, lp);
- pump (ms);
- i += 3;
- }
- else if (actions[i] == "drag")
- {
- const POINT a { actions[i + 1].getIntValue(), actions[i + 2].getIntValue() }, b { actions[i + 3].getIntValue(), actions[i + 4].getIntValue() };
- LPARAM lp;
- auto* target = hit (a, lp);
- PostMessageW (target, WM_MOUSEMOVE, 0, lp);
- pump (60);
- PostMessageW (target, WM_LBUTTONDOWN, MK_LBUTTON, lp);
- pump (80);
- POINT origin { 0, 0 };
- MapWindowPoints (hwnd, target, &origin, 1); // the target keeps the mouse for the whole drag
- for (int k = 1; k <= 12; ++k)
- {
- const auto x = (int) a.x + ((int) b.x - (int) a.x) * k / 12 + (int) origin.x, y = (int) a.y + ((int) b.y - (int) a.y) * k / 12 + (int) origin.y;
- PostMessageW (target, WM_MOUSEMOVE, MK_LBUTTON, MAKELPARAM (x, y));
- pump (25);
- }
- PostMessageW (target, WM_LBUTTONUP, 0, MAKELPARAM ((int) b.x + (int) origin.x, (int) b.y + (int) origin.y));
- pump (ms);
- i += 5;
- }
- else // x y: a click as the user would make it (a trial's "Evaluate" button, then a panel tab)
- {
- LPARAM lp;
- const POINT pt { actions[i].getIntValue(), actions[i + 1].getIntValue() };
- auto* target = hit (pt, lp);
- PostMessageW (target, WM_MOUSEMOVE, 0, lp);
- PostMessageW (target, WM_LBUTTONDOWN, MK_LBUTTON, lp);
- pump (80);
- PostMessageW (target, WM_LBUTTONUP, 0, lp);
- pump (ms);
- i += 2;
- }
- logChanges();
- }
- windowPicture (hwnd, out);
- w.clearContentComponent();
- ed.reset();
- pump (100);
- }
- static void logMenu (HMENU menu, int depth)
- {
- for (int k = 0, n = GetMenuItemCount (menu); k < n; ++k)
- {
- wchar_t name[256] {};
- GetMenuStringW (menu, (UINT) k, name, 255, MF_BYPOSITION);
- const auto state = GetMenuState (menu, (UINT) k, MF_BYPOSITION);
- std::printf ("menu %*s%s%s%s\n", depth * 2, "", juce::String (name).toRawUTF8(), (state & MF_CHECKED) ? " [checked]" : "", (state & MF_GRAYED) ? " [greyed]" : "");
- if (auto* sub = GetSubMenu (menu, k))
- logMenu (sub, depth + 1);
- }
- std::fflush (stdout);
- }
- // a picture of the window's client area (PrintWindow)
- void windowPicture (HWND hwnd, const juce::File& out)
- {
- RECT rc;
- GetClientRect (hwnd, &rc);
- const int width = rc.right - rc.left, height = rc.bottom - rc.top;
- HDC screen = GetDC (nullptr), mem = CreateCompatibleDC (screen);
- HBITMAP bmp = CreateCompatibleBitmap (screen, width, height);
- auto* old = SelectObject (mem, bmp);
- PrintWindow (hwnd, mem, 1 | 2); // PW_CLIENTONLY | PW_RENDERFULLCONTENT
- BITMAPINFO bi {};
- bi.bmiHeader.biSize = sizeof (BITMAPINFOHEADER);
- bi.bmiHeader.biWidth = width;
- bi.bmiHeader.biHeight = -height;
- bi.bmiHeader.biPlanes = 1;
- bi.bmiHeader.biBitCount = 32;
- std::vector<juce::uint8> px ((size_t) width * (size_t) height * 4);
- GetDIBits (mem, bmp, 0, (UINT) height, px.data(), &bi, DIB_RGB_COLORS);
- SelectObject (mem, old);
- DeleteObject (bmp);
- DeleteDC (mem);
- ReleaseDC (nullptr, screen);
- juce::Image img (juce::Image::RGB, width, height, false);
- for (int y = 0; y < height; ++y)
- for (int x = 0; x < width; ++x)
- {
- const auto* q = &px[((size_t) y * (size_t) width + (size_t) x) * 4];
- img.setPixelAt (x, y, juce::Colour (q[2], q[1], q[0]));
- }
- out.deleteFile();
- juce::FileOutputStream os (out);
- juce::PNGImageFormat().writeImageToStream (img, os);
- log ("editor " + juce::String (width) + "x" + juce::String (height) + " -> " + out.getFullPathName());
- }
- // a file through the plugin at about real time, with the editor's messages delivered between blocks (so its meters
- // and live displays move as they do in a host); the output is thrown away
- void playWhileDrawing (const juce::File& in)
- {
- juce::AudioBuffer<float> input;
- if (! readWav (in, input)) { log ("error: cannot read " + in.getFullPathName()); return; }
- const int mainIn = juce::jmax (1, plugin->getMainBusNumInputChannels());
- const int totalIn = plugin->getTotalNumInputChannels();
- const int ch = juce::jmax (totalIn, plugin->getTotalNumOutputChannels());
- juce::AudioBuffer<float> buf (ch, block);
- const auto start = juce::Time::getMillisecondCounter();
- for (int pos = 0; pos < input.getNumSamples(); pos += block)
- {
- const int n = juce::jmin (block, input.getNumSamples() - pos);
- buf.setSize (ch, n, false, false, true);
- buf.clear();
- for (int c = 0; c < juce::jmin (mainIn, totalIn); ++c)
- buf.copyFrom (c, 0, input, juce::jmin (c, input.getNumChannels() - 1), pos, n);
- midi.clear();
- plugin->processBlock (buf, midi);
- playHead.samples += n;
- const auto due = start + (juce::uint32) ((double) (pos + n) * 1000.0 / rate);
- do pump (1); while (juce::Time::getMillisecondCounter() < due);
- }
- log ("played " + in.getFileName());
- }
- void runSilence (int samples)
- {
- pump (0);
- const int ch = juce::jmax (plugin->getTotalNumInputChannels(), plugin->getTotalNumOutputChannels());
- juce::AudioBuffer<float> buf (ch, block);
- while (samples > 0)
- {
- const int n = juce::jmin (block, samples);
- buf.setSize (ch, n, false, false, true);
- buf.clear();
- midi.clear();
- plugin->processBlock (buf, midi);
- playHead.samples += n;
- samples -= n;
- }
- }
- bool readWav (const juce::File& f, juce::AudioBuffer<float>& out)
- {
- juce::WavAudioFormat wav;
- std::unique_ptr<juce::AudioFormatReader> r (wav.createReaderFor (f.createInputStream().release(), true));
- if (r == nullptr) return false;
- out.setSize ((int) r->numChannels, (int) r->lengthInSamples);
- r->read (&out, 0, (int) r->lengthInSamples, 0, true, true);
- return true;
- }
- void process (const juce::File& in, const juce::File& outFile, const juce::File& sc)
- {
- juce::AudioBuffer<float> input, side;
- if (! readWav (in, input)) { log ("error: cannot read " + in.getFullPathName()); return; }
- const bool haveSide = sc != juce::File() && readWav (sc, side);
- const int mainIn = juce::jmax (1, plugin->getMainBusNumInputChannels());
- const int totalIn = plugin->getTotalNumInputChannels();
- const int totalOut = plugin->getTotalNumOutputChannels();
- const int ch = juce::jmax (totalIn, totalOut);
- const int len = input.getNumSamples();
- juce::AudioBuffer<float> result (totalOut, len);
- juce::AudioBuffer<float> buf (ch, block);
- for (int pos = 0; pos < len; pos += block)
- {
- const int n = juce::jmin (block, len - pos);
- buf.setSize (ch, n, false, false, true);
- buf.clear();
- for (int c = 0; c < juce::jmin (mainIn, totalIn); ++c)
- buf.copyFrom (c, 0, input, juce::jmin (c, input.getNumChannels() - 1), pos, n);
- if (haveSide)
- for (int c = mainIn; c < totalIn; ++c)
- buf.copyFrom (c, 0, side, juce::jmin (c - mainIn, side.getNumChannels() - 1), juce::jmin (pos, side.getNumSamples() - n), n);
- midi.clear();
- plugin->processBlock (buf, midi);
- playHead.samples += n;
- for (int c = 0; c < totalOut; ++c)
- result.copyFrom (c, pos, buf, c, 0, n);
- }
- outFile.deleteFile();
- juce::WavAudioFormat wav;
- std::unique_ptr<juce::OutputStream> os (outFile.createOutputStream().release());
- std::unique_ptr<juce::AudioFormatWriter> w (wav.createWriterFor (os.get(), rate, (unsigned) totalOut, 32, {}, 0));
- if (w == nullptr) { log ("error: cannot write " + outFile.getFullPathName()); return; }
- os.release();
- w->writeFromAudioSampleBuffer (result, 0, len);
- w.reset();
- log ("processed " + juce::String (len) + " samples -> " + outFile.getFileName() + " latency=" + juce::String (plugin->getLatencySamples()));
- }
- static juce::String norm (float v) { return juce::String (v, 6); }
- void params (const juce::File& out, int steps)
- {
- juce::String t;
- t << "index\tid\tname\tlabel\tdefault\tdefaultText\tnumSteps\tdiscrete\tboolean\tautomatable";
- for (int k = 0; k <= steps; ++k) t << "\tv" << norm ((float) k / (float) steps);
- t << "\n";
- const auto& ps = plugin->getParameters();
- for (int i = 0; i < ps.size(); ++i)
- {
- auto* p = ps[i];
- juce::String id;
- if (auto* hp = dynamic_cast<juce::HostedAudioProcessorParameter*> (p)) id = hp->getParameterID();
- const float d = p->getDefaultValue();
- t << i << "\t" << id << "\t" << p->getName (256) << "\t" << p->getLabel() << "\t" << norm (d) << "\t" << p->getText (d, 256) << "\t"
- << p->getNumSteps() << "\t" << (int) p->isDiscrete() << "\t" << (int) p->isBoolean() << "\t" << (int) p->isAutomatable();
- for (int k = 0; k <= steps; ++k) t << "\t" << p->getText ((float) k / (float) steps, 256);
- t << "\n";
- }
- out.replaceWithText (t);
- log ("params " + juce::String (ps.size()) + " -> " + out.getFileName());
- }
- void texts (juce::AudioProcessorParameter* p, const juce::File& out, int steps)
- {
- juce::String t;
- for (int k = 0; k <= steps; ++k)
- {
- const float v = (float) k / (float) steps;
- t << norm (v) << "\t" << p->getText (v, 256) << "\n";
- }
- out.replaceWithText (t);
- log ("texts " + p->getName (256) + " -> " + out.getFileName());
- }
- // whether a parameter text shows the asked text: names equal (case ignored), numbers within 0.1 % ("12.0 kHz" = 12000)
- static bool shows (const juce::String& shown, const juce::String& text)
- {
- const auto first = text.trimStart()[0];
- if (! ((first >= '0' && first <= '9') || first == '-' || first == '+' || first == '.'))
- return shown.trim().equalsIgnoreCase (text.trim());
- const double want = text.getDoubleValue();
- const double got = shown.getDoubleValue() * (shown.containsIgnoreCase ("khz") && ! text.containsIgnoreCase ("k") ? 1000.0 : 1.0);
- return std::abs (got - want) <= 1e-3 * juce::jmax (1.0, std::abs (want));
- }
- // text -> normalized value: numbers go through the plugin's own parser; names (enumerations) are found by scanning
- // the value -> text mapping (the middle of the range that shows the text). −1 when no value shows the text (round
- // tp172b7: Pro-MB's "Minimum Phase" was not a text of its mode; the old fallback set 0 = Linear Phase silently)
- static float textToValue (juce::AudioProcessorParameter* p, const juce::String& text)
- {
- const auto first = text.trimStart()[0];
- const int n = 4000;
- if ((first >= '0' && first <= '9') || first == '-' || first == '+' || first == '.')
- {
- const double want = text.getDoubleValue();
- const float v = p->getValueForText (text);
- if (v >= 0.0f && v <= 1.0f && shows (p->getText (v, 256), text)) // (a parser may return an unnormalized value)
- return v;
- int lo = -1, hi = -1; // stepped numbers the parser does not take: scan for the value
- for (int k = 0; k <= n; ++k)
- if (std::abs (p->getText ((float) k / n, 256).getDoubleValue() - want) <= 1e-6 * juce::jmax (1.0, std::abs (want))) { if (lo < 0) lo = k; hi = k; }
- else if (lo >= 0) break;
- return lo < 0 ? -1.0f : (float) (lo + hi) / (2.0f * n);
- }
- int lo = -1, hi = -1;
- for (int k = 0; k <= n; ++k)
- if (p->getText ((float) k / n, 256).trim().equalsIgnoreCase (text.trim())) { if (lo < 0) lo = k; hi = k; }
- else if (lo >= 0) break;
- return lo < 0 ? -1.0f : (float) (lo + hi) / (2.0f * n);
- }
- void setParam (juce::AudioProcessorParameter* p, float v)
- {
- p->setValue (v);
- }
- void run (const juce::StringArray& lines)
- {
- for (auto line : lines)
- {
- // '#' starts a comment at the start of a line or after a space when a space follows ("# note"), so that
- // `set #12 0.5` (a parameter by index) works (round 170c)
- line = line.trim();
- if (line.startsWithChar ('#'))
- continue;
- line = line.upToFirstOccurrenceOf (" # ", false, false).trim();
- if (line.isEmpty()) continue;
- juce::StringArray a;
- a.addTokens (line, " \t", "\"");
- a.removeEmptyStrings();
- for (auto& s : a) s = s.unquoted();
- const auto cmd = a[0];
- pump (0);
- if (cmd == "pump") { pump (a[1].getIntValue()); continue; }
- if (cmd == "buses") // round 170c: which main layouts the plugin accepts (1…8 channels in / out)
- {
- if (plugin == nullptr) { log ("error: no plugin"); continue; }
- juce::String ok;
- for (int i = 1; i <= 8; ++i)
- for (int o = 1; o <= 8; ++o)
- {
- auto l = plugin->getBusesLayout();
- if (l.inputBuses.isEmpty() || l.outputBuses.isEmpty()) continue;
- l.inputBuses.getReference (0) = juce::AudioChannelSet::canonicalChannelSet (i);
- l.outputBuses.getReference (0) = juce::AudioChannelSet::canonicalChannelSet (o);
- if (plugin->checkBusesLayoutSupported (l)) ok << " " << i << "/" << o;
- }
- log ("buses now in=" + juce::String (plugin->getMainBusNumInputChannels()) + " out=" + juce::String (plugin->getMainBusNumOutputChannels()) + " supported:" + ok);
- continue;
- }
- if (cmd == "echo") { log (line.fromFirstOccurrenceOf (" ", false, false)); continue; }
- if (cmd == "editor" && ! a[1].endsWithIgnoreCase (".png")) // `editor <out.png> …` is the PrintWindow shot below
- {
- if (plugin == nullptr) { log ("error: no plugin"); continue; }
- std::unique_ptr<juce::AudioProcessorEditor> ed (plugin->createEditorIfNeeded());
- if (ed == nullptr) { log ("error: no editor"); continue; }
- juce::DocumentWindow win ("fxmeasure editor", juce::Colours::black, 0, true);
- win.setUsingNativeTitleBar (false);
- win.setTitleBarHeight (0);
- win.setContentNonOwned (ed.get(), true);
- win.setTopLeftPosition (a.size() > 3 ? a[2].getIntValue() : 100, a.size() > 3 ? a[3].getIntValue() : 100);
- win.setVisible (true);
- win.toFront (true);
- const auto b = ed->getScreenBounds();
- log ("editor " + juce::String (b.getX()) + " " + juce::String (b.getY()) + " " + juce::String (b.getWidth()) + " " + juce::String (b.getHeight()));
- pump (a[1].getIntValue());
- win.clearContentComponent();
- ed.reset();
- continue;
- }
- if (cmd == "load")
- {
- if (a.size() > 2) rate = a[2].getDoubleValue();
- if (a.size() > 3) block = a[3].getIntValue();
- juce::OwnedArray<juce::PluginDescription> types;
- // a big shell takes many minutes to describe: the descriptions are cached in fxmeasure-cache.xml (cwd)
- const juce::File cache = juce::File::getCurrentWorkingDirectory().getChildFile ("fxmeasure-cache.xml");
- juce::KnownPluginList known;
- if (auto xml = juce::parseXML (cache)) known.recreateFromXml (*xml);
- for (const auto& t : known.getTypes())
- if (t.fileOrIdentifier == a[1]) types.add (new juce::PluginDescription (t));
- if (types.isEmpty())
- {
- for (auto* f : formats.getFormats())
- if (f->fileMightContainThisPluginType (a[1])) f->findAllTypesForFile (types, a[1]);
- for (auto* t : types) known.addType (*t);
- if (auto xml = known.createXml()) xml->writeTo (cache);
- }
- if (types.isEmpty()) { log ("error: no plugin in " + a[1]); continue; }
- // a shell (one file, many plugins: Waves) — `load <file> <rate> <block> <name>` picks the plugin whose
- // name equals <name> (else the first one containing it); `list` prints them all
- if (a.size() > 4 && a[4] == "?") { for (auto* t : types) log ("plugin " + t->name + " | " + t->createIdentifierString()); continue; }
- int pick = 0;
- if (a.size() > 4)
- {
- const auto want = line.fromFirstOccurrenceOf (a[3], false, false).fromFirstOccurrenceOf (" ", false, false).trim().unquoted();
- pick = -1;
- for (int i = 0; i < types.size() && pick < 0; ++i) if (types[i]->name.equalsIgnoreCase (want)) pick = i;
- for (int i = 0; i < types.size() && pick < 0; ++i) if (types[i]->name.containsIgnoreCase (want)) pick = i;
- if (pick < 0) { log ("error: no plugin named " + want + " in " + a[1] + " (" + juce::String (types.size()) + " plugins)"); continue; }
- }
- juce::String err;
- plugin = formats.createPluginInstance (*types[pick], rate, block, err);
- // round 170c: a Waves shell's first instance in a process comes up as another of its plugins (LYNX's
- // createRightInstance, PluginHost.cpp): created again it is the right one (the wrong ones stay alive
- // until then). Without this every Waves measurement ran a surround meter (bit-identical output).
- {
- std::vector<std::unique_ptr<juce::AudioPluginInstance>> wrong;
- for (int attempt = 0; attempt < 3 && plugin != nullptr && plugin->getName() != types[pick]->name; ++attempt)
- {
- log ("mismatch: asked " + types[pick]->name + ", got " + plugin->getName() + " (again)");
- wrong.push_back (std::move (plugin));
- plugin = formats.createPluginInstance (*types[pick], rate, block, err);
- }
- if (plugin != nullptr && plugin->getName() != types[pick]->name)
- {
- log ("error: the shell handed out " + plugin->getName() + " for " + types[pick]->name);
- plugin.reset();
- continue;
- }
- }
- if (plugin == nullptr) { log ("error: " + err); continue; }
- log ("instance " + plugin->getName());
- log ("loaded " + types[pick]->name + " by " + types[pick]->manufacturerName + " v" + types[pick]->version + " params=" + juce::String (plugin->getParameters().size())
- + " inBuses=" + juce::String (plugin->getBusCount (true)) + " outBuses=" + juce::String (plugin->getBusCount (false)));
- prepare();
- continue;
- }
- if (plugin == nullptr) { log ("error: no plugin loaded for " + cmd); continue; }
- if (cmd == "rate") { rate = a[1].getDoubleValue(); if (a.size() > 2) block = a[2].getIntValue(); prepare(); }
- else if (cmd == "sidechain") { sidechain = a[1] == "on"; prepare(); }
- else if (cmd == "nonrealtime") { plugin->setNonRealtime (a[1].getIntValue() != 0); log ("nonrealtime " + a[1]); }
- else if (cmd == "params") params (juce::File (a[1]), a.size() > 2 ? a[2].getIntValue() : 10);
- else if (cmd == "texts")
- {
- if (auto* p = find (a[1])) texts (p, juce::File (a[2]), a.size() > 3 ? a[3].getIntValue() : 200);
- else log ("error: no parameter " + a[1]);
- }
- else if (cmd == "set" || cmd == "settext")
- {
- auto* p = find (a[1]);
- if (p == nullptr) { log ("error: no parameter " + a[1] + " (script stopped)"); failed = true; return; }
- const auto valueText = line.fromFirstOccurrenceOf (a[1], false, false).trim().unquoted();
- const float v = cmd == "set" ? valueText.getFloatValue() : textToValue (p, valueText);
- if (cmd == "settext" && v < 0.0f)
- {
- log ("error: no value of " + p->getName (256) + " shows the text \"" + valueText + "\" (script stopped)");
- failed = true;
- return;
- }
- setParam (p, juce::jlimit (0.0f, 1.0f, v));
- log ("set " + p->getName (256) + " = " + norm (p->getValue()) + " (" + p->getCurrentValueAsText() + ")");
- if (cmd == "settext" && ! shows (p->getCurrentValueAsText(), valueText))
- {
- // round tp172b7: the plugin now shows another text than asked (its value -> text scan misled us)
- log ("error: " + p->getName (256) + " shows \"" + p->getCurrentValueAsText() + "\", not \"" + valueText + "\" (script stopped)");
- failed = true;
- return;
- }
- }
- else if (cmd == "get")
- {
- if (auto* p = find (a[1])) log ("get " + p->getName (256) + " = " + norm (p->getValue()) + " (" + p->getCurrentValueAsText() + ")");
- else log ("error: no parameter " + a[1]);
- }
- else if (cmd == "defaults")
- {
- for (auto* p : plugin->getParameters()) setParam (p, p->getDefaultValue());
- log ("defaults");
- }
- else if (cmd == "reset") { plugin->reset(); log ("reset"); }
- else if (cmd == "transport")
- {
- // transport <bpm> [samplePosition|keep] [playing 0|1]: the host's tempo and song position
- playHead.bpm = a[1].getDoubleValue();
- if (a.size() > 2 && a[2] != "keep") playHead.samples = a[2].getLargeIntValue();
- if (a.size() > 3) playHead.playing = a[3].getIntValue() != 0;
- log ("transport " + juce::String (playHead.bpm) + " " + juce::String (playHead.samples));
- }
- else if (cmd == "settle") runSilence ((int) (a[1].getDoubleValue() * rate));
- else if (cmd == "process") process (juce::File (a[1]), juce::File (a[2]), a.size() > 3 ? juce::File (a[3]) : juce::File());
- else if (cmd == "editor")
- {
- juce::StringArray actions; // see the header: clicks, drag, hover, play, shot, in order
- for (int i = 3; i < a.size(); ++i)
- actions.add (a[i]);
- editorShot (juce::File (a[1]), a.size() > 2 ? a[2].getIntValue() : 1500, actions);
- }
- else if (cmd == "latency") { pump (50); log ("latency " + juce::String (plugin->getLatencySamples())); }
- else if (cmd == "savestate")
- {
- juce::MemoryBlock m;
- plugin->getStateInformation (m);
- juce::File (a[1]).replaceWithData (m.getData(), m.getSize());
- log ("savestate " + juce::String ((int) m.getSize()) + " bytes");
- }
- else if (cmd == "loadstate")
- {
- juce::MemoryBlock m;
- juce::File (a[1]).loadFileAsData (m);
- plugin->setStateInformation (m.getData(), (int) m.getSize());
- log ("loadstate");
- }
- else if (cmd == "savecomponent" || cmd == "loadcomponent")
- {
- // the raw VST3 component state (what a DAW project stores), inside JUCE's VST3PluginState wrapper
- juce::MemoryBlock m;
- plugin->getStateInformation (m);
- auto xml = juce::AudioProcessor::getXmlFromBinary (m.getData(), (int) m.getSize());
- if (xml == nullptr) { log ("error: no VST3 state"); continue; }
- auto* comp = xml->getChildByName ("IComponent");
- if (comp == nullptr) { log ("error: no IComponent"); continue; }
- juce::MemoryBlock raw;
- if (cmd == "savecomponent")
- {
- raw.fromBase64Encoding (comp->getAllSubText());
- juce::File (a[1]).replaceWithData (raw.getData(), raw.getSize());
- log ("savecomponent " + juce::String ((int) raw.getSize()) + " bytes");
- }
- else
- {
- juce::File (a[1]).loadFileAsData (raw);
- comp->deleteAllTextElements();
- comp->addTextElement (raw.toBase64Encoding());
- if (auto* ctl = xml->getChildByName ("IEditController")) xml->removeChildElement (ctl, true);
- juce::MemoryBlock out;
- juce::AudioProcessor::copyXmlToBinary (*xml, out);
- plugin->setStateInformation (out.getData(), (int) out.getSize());
- log ("loadcomponent " + juce::String ((int) raw.getSize()) + " bytes");
- }
- }
- else log ("error: unknown command " + cmd);
- }
- }
- };
- } // namespace
- int main (int argc, char** argv)
- {
- if (argc < 2) { std::printf ("usage: fxmeasure script.txt\n"); return 2; }
- std::printf ("fxmeasure start\n"); std::fflush (stdout);
- juce::ScopedJuceInitialiser_GUI init;
- std::printf ("init done\n"); std::fflush (stdout);
- Host host;
- host.formats.addFormat (new juce::VST3PluginFormat());
- juce::StringArray lines;
- juce::File::getCurrentWorkingDirectory().getChildFile (juce::String::fromUTF8 (argv[1])).readLines (lines);
- std::printf ("%d lines\n", lines.size()); std::fflush (stdout);
- host.run (lines);
- host.plugin.reset();
- std::printf (host.failed ? "FAILED\n" : "done\n"); std::fflush (stdout);
- std::_Exit (host.failed ? 3 : 0); // skip global teardown (some plugins hang there)
- }
|