fxmeasure.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  1. // fxmeasure — black-box measurement host for third-party audio effects (VST3), Windows console tool.
  2. //
  3. // It hosts a plugin the way a DAW does — public parameter API only (names, ranges, value <-> text) — feeds test
  4. // signals from WAV files and records the outputs. Nothing inside the plugin is inspected (round 99 rule: black-box
  5. // 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.
  6. //
  7. // fxmeasure.exe script.txt (one command per line; '#' at the start of a line or " # " starts a comment)
  8. //
  9. // Commands:
  10. // load <file.vst3> [rate] [block] [name] load the first effect in the file (default 48000 Hz, 512 samples), or in a
  11. // shell (Waves) the one called <name>; name "?" lists the shell's plugins
  12. // rate <hz> [block] re-prepare at another sample rate / block size
  13. // sidechain on|off enable every input bus (main + sidechain) or only the main one
  14. // nonrealtime 0|1 AudioProcessor::setNonRealtime
  15. // params <out.tsv> [steps] parameter table: index, id, name, label, default, steps, texts at k/steps
  16. // texts <name|#index> <out.tsv> [steps] value -> text for one parameter at a finer grid
  17. // set <name|#index> <normalized> set a parameter (normalized 0..1)
  18. // settext <name|#index> <text> set a parameter from its text (plugin's own text -> value); a text that no value
  19. // shows (or an unknown parameter in set/settext) stops the script, exit code 3
  20. // get <name|#index> print value and text
  21. // defaults every parameter back to its default value
  22. // reset AudioProcessor::reset
  23. // transport <bpm> [pos|keep] [0|1] the host tempo, song position (samples) and play state the plugin sees
  24. // settle <seconds> process silence (parameter smoothing, envelopes)
  25. // process <in.wav> <out.wav> [sc.wav] run the input (and optional sidechain) through, write a 32-bit float WAV
  26. // latency print the reported latency in samples
  27. // savestate <file> / loadstate <file>
  28. // savecomponent <file> / loadcomponent <file> the raw VST3 component state (as a DAW project stores it)
  29. // pump <ms> deliver the plugin's pending Win32 messages for a while
  30. // editor <out.png> [ms] [x y] open the plugin's own editor in a window, let it draw (default 1500 ms), optionally
  31. // click at (x, y) as a user would (a trial's "Evaluate"), save a PNG (PrintWindow)
  32. // editor <out.png> <ms> [action]... (round tp172b6) each action runs in order, posted to the editor's own window (no
  33. // 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
  34. // through the plugin while the editor draws), shot <out.png> (a picture now). Every
  35. // parameter an action changed is logged ("changed <name> a -> b (text)")
  36. // echo <text>
  37. // editor <ms> [x y] show the plugin's own editor in a window at (x, y) for ms milliseconds (for screenshots
  38. // taken from outside, e.g. with a screen-capture script); prints its screen bounds
  39. #include <thread>
  40. #include <atomic>
  41. #include <juce_audio_processors/juce_audio_processors.h>
  42. #include <juce_audio_formats/juce_audio_formats.h>
  43. #include <juce_events/juce_events.h>
  44. #include <juce_gui_basics/juce_gui_basics.h>
  45. #include <cstdio>
  46. #include <cstdlib>
  47. #include <windows.h>
  48. namespace
  49. {
  50. struct Host
  51. {
  52. juce::AudioPluginFormatManager formats;
  53. std::unique_ptr<juce::AudioPluginInstance> plugin;
  54. bool failed = false; // a set/settext the script cannot apply: the run stops, exit code 3
  55. double rate = 48000.0;
  56. int block = 512;
  57. bool sidechain = false;
  58. juce::MidiBuffer midi;
  59. struct PlayHead final : juce::AudioPlayHead
  60. {
  61. juce::int64 samples = 0;
  62. double rate = 48000.0, bpm = 120.0;
  63. bool playing = true;
  64. juce::Optional<PositionInfo> getPosition() const override
  65. {
  66. PositionInfo p;
  67. p.setBpm (bpm);
  68. p.setTimeSignature (TimeSignature { 4, 4 });
  69. p.setTimeInSamples (samples);
  70. p.setTimeInSeconds ((double) samples / rate);
  71. p.setPpqPosition ((double) samples / rate * bpm / 60.0);
  72. p.setIsPlaying (playing);
  73. return p;
  74. }
  75. } playHead;
  76. void log (const juce::String& s) { std::printf ("%s\n", s.toRawUTF8()); std::fflush (stdout); }
  77. bool prepare()
  78. {
  79. if (plugin == nullptr) return false;
  80. plugin->releaseResources();
  81. auto layout = plugin->getBusesLayout();
  82. // some plugins (Valhalla) come up with their main buses disabled: ask for stereo in / out
  83. if (! layout.inputBuses.isEmpty() && layout.inputBuses[0].size() == 0) layout.inputBuses.getReference (0) = juce::AudioChannelSet::stereo();
  84. if (! layout.outputBuses.isEmpty() && layout.outputBuses[0].size() == 0) layout.outputBuses.getReference (0) = juce::AudioChannelSet::stereo();
  85. for (int b = 1; b < layout.inputBuses.size(); ++b)
  86. if (sidechain) layout.inputBuses.getReference (b) = juce::AudioChannelSet::stereo();
  87. else layout.inputBuses.getReference (b) = juce::AudioChannelSet::disabled();
  88. // some plugins (JUCE-based ones among them) report their main buses disabled until a host asks for a layout:
  89. // ask for stereo in / stereo out, then mono in / stereo out
  90. if (layout.getMainInputChannels() == 0 && layout.inputBuses.size() > 0)
  91. layout.inputBuses.getReference (0) = juce::AudioChannelSet::stereo();
  92. if (layout.getMainOutputChannels() == 0 && layout.outputBuses.size() > 0)
  93. layout.outputBuses.getReference (0) = juce::AudioChannelSet::stereo();
  94. // round 170c: a shell plugin (Waves "CLA-2A Stereo") may come up with a 5-channel main bus and then passes the
  95. // audio through untouched: ask for stereo whenever the plugin supports it
  96. if (! layout.inputBuses.isEmpty() && ! layout.outputBuses.isEmpty()
  97. && (layout.inputBuses[0].size() > 2 || layout.outputBuses[0].size() > 2))
  98. {
  99. auto stereo = layout;
  100. stereo.inputBuses.getReference (0) = juce::AudioChannelSet::stereo();
  101. stereo.outputBuses.getReference (0) = juce::AudioChannelSet::stereo();
  102. if (plugin->checkBusesLayoutSupported (stereo) || plugin->setBusesLayout (stereo))
  103. layout = plugin->getBusesLayout();
  104. log ("stereo request: in=" + juce::String (layout.getMainInputChannels()) + " out=" + juce::String (layout.getMainOutputChannels()));
  105. }
  106. if (! plugin->checkBusesLayoutSupported (layout) && layout.inputBuses.size() > 0)
  107. {
  108. auto mono = layout;
  109. mono.inputBuses.getReference (0) = juce::AudioChannelSet::mono();
  110. if (plugin->checkBusesLayoutSupported (mono))
  111. layout = mono;
  112. }
  113. if (! plugin->setBusesLayout (layout))
  114. {
  115. // fall back to enabling the buses one by one
  116. for (int b = 1; b < plugin->getBusCount (true); ++b)
  117. if (auto* bus = plugin->getBus (true, b)) bus->enable (sidechain);
  118. }
  119. plugin->setRateAndBufferSizeDetails (rate, block);
  120. plugin->setPlayHead (&playHead);
  121. playHead.rate = rate;
  122. plugin->prepareToPlay (rate, block);
  123. log ("prepared rate=" + juce::String (rate) + " block=" + juce::String (block) + " in=" + juce::String (plugin->getTotalNumInputChannels())
  124. + " out=" + juce::String (plugin->getTotalNumOutputChannels()) + " mainIn=" + juce::String (plugin->getMainBusNumInputChannels())
  125. + " latency=" + juce::String (plugin->getLatencySamples()));
  126. return true;
  127. }
  128. juce::AudioProcessorParameter* find (const juce::String& key)
  129. {
  130. if (plugin == nullptr) return nullptr;
  131. const auto& ps = plugin->getParameters();
  132. if (key.startsWithChar ('#'))
  133. {
  134. const int i = key.substring (1).getIntValue();
  135. return juce::isPositiveAndBelow (i, ps.size()) ? ps[i] : nullptr;
  136. }
  137. for (auto* p : ps)
  138. if (p->getName (256) == key) return p;
  139. for (auto* p : ps)
  140. if (p->getName (256).equalsIgnoreCase (key)) return p;
  141. return nullptr;
  142. }
  143. // the plugin's asynchronous messages (latency changes, parameter echoes) are delivered through the Win32 queue
  144. static void pump (int ms)
  145. {
  146. const auto end = juce::Time::getMillisecondCounter() + (juce::uint32) ms;
  147. do
  148. {
  149. MSG msg;
  150. while (PeekMessageW (&msg, nullptr, 0, 0, PM_REMOVE))
  151. {
  152. TranslateMessage (&msg);
  153. DispatchMessageW (&msg);
  154. }
  155. if (ms > 0) Sleep (1);
  156. } while (juce::Time::getMillisecondCounter() < end);
  157. }
  158. // the plugin's editor in a top-level window, captured with PrintWindow (round 108: reference screenshots)
  159. void editorShot (const juce::File& out, int ms, const juce::StringArray& actions = {})
  160. {
  161. std::unique_ptr<juce::AudioProcessorEditor> ed (plugin->createEditorIfNeeded());
  162. if (ed == nullptr) { log ("error: no editor"); return; }
  163. juce::DocumentWindow w (plugin->getName(), juce::Colours::black, 0, true);
  164. w.setUsingNativeTitleBar (true);
  165. w.setContentNonOwned (ed.get(), true);
  166. w.setTopLeftPosition (40, 40);
  167. w.setVisible (true);
  168. w.toFront (false);
  169. runSilence ((int) rate / 4);
  170. pump (ms);
  171. auto* hwnd = (HWND) w.getPeer()->getNativeHandle();
  172. // the deepest child window at a client point of hwnd, and the point in that child's coordinates
  173. const auto hit = [hwnd] (POINT pt, LPARAM& lp)
  174. {
  175. HWND target = hwnd;
  176. for (;;)
  177. {
  178. POINT local = pt;
  179. MapWindowPoints (hwnd, target, &local, 1);
  180. HWND child = ChildWindowFromPointEx (target, local, CWP_SKIPINVISIBLE);
  181. if (child == nullptr || child == target) break;
  182. target = child;
  183. }
  184. POINT local = pt;
  185. MapWindowPoints (hwnd, target, &local, 1);
  186. lp = MAKELPARAM (local.x, local.y);
  187. return target;
  188. };
  189. std::vector<float> before;
  190. const auto remember = [&] { before.clear(); for (auto* p : plugin->getParameters()) before.push_back (p->getValue()); };
  191. const auto logChanges = [&]
  192. {
  193. const auto& ps = plugin->getParameters();
  194. for (int i = 0; i < ps.size() && i < (int) before.size(); ++i)
  195. if (std::abs (ps[i]->getValue() - before[(size_t) i]) > 1.0e-5f)
  196. log ("changed " + ps[i]->getName (256) + " " + norm (before[(size_t) i]) + " -> " + norm (ps[i]->getValue()) + " (" + ps[i]->getCurrentValueAsText() + ")");
  197. };
  198. for (int i = 0; i < actions.size();)
  199. {
  200. remember();
  201. if (actions[i] == "shot")
  202. {
  203. windowPicture (hwnd, juce::File (actions[i + 1]));
  204. i += 2;
  205. }
  206. else if (actions[i] == "play")
  207. {
  208. playWhileDrawing (juce::File (actions[i + 1]));
  209. i += 2;
  210. }
  211. else if (actions[i] == "hover")
  212. {
  213. LPARAM lp;
  214. const POINT pt { actions[i + 1].getIntValue(), actions[i + 2].getIntValue() };
  215. auto* target = hit (pt, lp);
  216. PostMessageW (target, WM_MOUSEMOVE, 0, lp);
  217. pump (ms);
  218. i += 3;
  219. }
  220. else if (actions[i] == "wheel") // wheel x y <delta, 120 = one notch up>
  221. {
  222. const POINT pt { actions[i + 1].getIntValue(), actions[i + 2].getIntValue() };
  223. POINT screen = pt;
  224. ClientToScreen (hwnd, &screen);
  225. LPARAM lp;
  226. auto* target = hit (pt, lp);
  227. PostMessageW (target, WM_MOUSEMOVE, 0, lp);
  228. pump (60);
  229. PostMessageW (target, WM_MOUSEWHEEL, MAKEWPARAM (0, (short) actions[i + 3].getIntValue()), MAKELPARAM (screen.x, screen.y));
  230. pump (ms);
  231. i += 4;
  232. }
  233. 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
  234. {
  235. LPARAM lp;
  236. const POINT pt { actions[i + 1].getIntValue(), actions[i + 2].getIntValue() };
  237. auto* target = hit (pt, lp);
  238. std::atomic<bool> done { false };
  239. std::thread reader ([&done] {
  240. for (int tries = 0; tries < 200 && ! done.load(); ++tries)
  241. {
  242. Sleep (25);
  243. HWND popup = nullptr;
  244. while ((popup = FindWindowExW (nullptr, popup, L"#32768", nullptr)) != nullptr)
  245. {
  246. DWORD pid = 0;
  247. GetWindowThreadProcessId (popup, &pid);
  248. if (pid != GetCurrentProcessId() || ! IsWindowVisible (popup))
  249. continue;
  250. Sleep (150);
  251. logMenu ((HMENU) SendMessageW (popup, 0x01E1 /* MN_GETHMENU */, 0, 0), 0);
  252. PostMessageW (popup, WM_KEYDOWN, VK_ESCAPE, 0);
  253. return;
  254. }
  255. }
  256. std::printf ("menu: no pop-up menu opened\n");
  257. std::fflush (stdout);
  258. });
  259. PostMessageW (target, WM_MOUSEMOVE, 0, lp);
  260. PostMessageW (target, WM_LBUTTONDOWN, MK_LBUTTON, lp);
  261. pump (80);
  262. PostMessageW (target, WM_LBUTTONUP, 0, lp);
  263. pump (ms);
  264. done = true;
  265. reader.join();
  266. i += 3;
  267. }
  268. else if (actions[i] == "dblclick")
  269. {
  270. LPARAM lp;
  271. const POINT pt { actions[i + 1].getIntValue(), actions[i + 2].getIntValue() };
  272. auto* target = hit (pt, lp);
  273. PostMessageW (target, WM_MOUSEMOVE, 0, lp);
  274. PostMessageW (target, WM_LBUTTONDOWN, MK_LBUTTON, lp);
  275. PostMessageW (target, WM_LBUTTONUP, 0, lp);
  276. PostMessageW (target, WM_LBUTTONDBLCLK, MK_LBUTTON, lp);
  277. PostMessageW (target, WM_LBUTTONUP, 0, lp);
  278. pump (ms);
  279. i += 3;
  280. }
  281. else if (actions[i] == "drag")
  282. {
  283. const POINT a { actions[i + 1].getIntValue(), actions[i + 2].getIntValue() }, b { actions[i + 3].getIntValue(), actions[i + 4].getIntValue() };
  284. LPARAM lp;
  285. auto* target = hit (a, lp);
  286. PostMessageW (target, WM_MOUSEMOVE, 0, lp);
  287. pump (60);
  288. PostMessageW (target, WM_LBUTTONDOWN, MK_LBUTTON, lp);
  289. pump (80);
  290. POINT origin { 0, 0 };
  291. MapWindowPoints (hwnd, target, &origin, 1); // the target keeps the mouse for the whole drag
  292. for (int k = 1; k <= 12; ++k)
  293. {
  294. 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;
  295. PostMessageW (target, WM_MOUSEMOVE, MK_LBUTTON, MAKELPARAM (x, y));
  296. pump (25);
  297. }
  298. PostMessageW (target, WM_LBUTTONUP, 0, MAKELPARAM ((int) b.x + (int) origin.x, (int) b.y + (int) origin.y));
  299. pump (ms);
  300. i += 5;
  301. }
  302. else // x y: a click as the user would make it (a trial's "Evaluate" button, then a panel tab)
  303. {
  304. LPARAM lp;
  305. const POINT pt { actions[i].getIntValue(), actions[i + 1].getIntValue() };
  306. auto* target = hit (pt, lp);
  307. PostMessageW (target, WM_MOUSEMOVE, 0, lp);
  308. PostMessageW (target, WM_LBUTTONDOWN, MK_LBUTTON, lp);
  309. pump (80);
  310. PostMessageW (target, WM_LBUTTONUP, 0, lp);
  311. pump (ms);
  312. i += 2;
  313. }
  314. logChanges();
  315. }
  316. windowPicture (hwnd, out);
  317. w.clearContentComponent();
  318. ed.reset();
  319. pump (100);
  320. }
  321. static void logMenu (HMENU menu, int depth)
  322. {
  323. for (int k = 0, n = GetMenuItemCount (menu); k < n; ++k)
  324. {
  325. wchar_t name[256] {};
  326. GetMenuStringW (menu, (UINT) k, name, 255, MF_BYPOSITION);
  327. const auto state = GetMenuState (menu, (UINT) k, MF_BYPOSITION);
  328. std::printf ("menu %*s%s%s%s\n", depth * 2, "", juce::String (name).toRawUTF8(), (state & MF_CHECKED) ? " [checked]" : "", (state & MF_GRAYED) ? " [greyed]" : "");
  329. if (auto* sub = GetSubMenu (menu, k))
  330. logMenu (sub, depth + 1);
  331. }
  332. std::fflush (stdout);
  333. }
  334. // a picture of the window's client area (PrintWindow)
  335. void windowPicture (HWND hwnd, const juce::File& out)
  336. {
  337. RECT rc;
  338. GetClientRect (hwnd, &rc);
  339. const int width = rc.right - rc.left, height = rc.bottom - rc.top;
  340. HDC screen = GetDC (nullptr), mem = CreateCompatibleDC (screen);
  341. HBITMAP bmp = CreateCompatibleBitmap (screen, width, height);
  342. auto* old = SelectObject (mem, bmp);
  343. PrintWindow (hwnd, mem, 1 | 2); // PW_CLIENTONLY | PW_RENDERFULLCONTENT
  344. BITMAPINFO bi {};
  345. bi.bmiHeader.biSize = sizeof (BITMAPINFOHEADER);
  346. bi.bmiHeader.biWidth = width;
  347. bi.bmiHeader.biHeight = -height;
  348. bi.bmiHeader.biPlanes = 1;
  349. bi.bmiHeader.biBitCount = 32;
  350. std::vector<juce::uint8> px ((size_t) width * (size_t) height * 4);
  351. GetDIBits (mem, bmp, 0, (UINT) height, px.data(), &bi, DIB_RGB_COLORS);
  352. SelectObject (mem, old);
  353. DeleteObject (bmp);
  354. DeleteDC (mem);
  355. ReleaseDC (nullptr, screen);
  356. juce::Image img (juce::Image::RGB, width, height, false);
  357. for (int y = 0; y < height; ++y)
  358. for (int x = 0; x < width; ++x)
  359. {
  360. const auto* q = &px[((size_t) y * (size_t) width + (size_t) x) * 4];
  361. img.setPixelAt (x, y, juce::Colour (q[2], q[1], q[0]));
  362. }
  363. out.deleteFile();
  364. juce::FileOutputStream os (out);
  365. juce::PNGImageFormat().writeImageToStream (img, os);
  366. log ("editor " + juce::String (width) + "x" + juce::String (height) + " -> " + out.getFullPathName());
  367. }
  368. // a file through the plugin at about real time, with the editor's messages delivered between blocks (so its meters
  369. // and live displays move as they do in a host); the output is thrown away
  370. void playWhileDrawing (const juce::File& in)
  371. {
  372. juce::AudioBuffer<float> input;
  373. if (! readWav (in, input)) { log ("error: cannot read " + in.getFullPathName()); return; }
  374. const int mainIn = juce::jmax (1, plugin->getMainBusNumInputChannels());
  375. const int totalIn = plugin->getTotalNumInputChannels();
  376. const int ch = juce::jmax (totalIn, plugin->getTotalNumOutputChannels());
  377. juce::AudioBuffer<float> buf (ch, block);
  378. const auto start = juce::Time::getMillisecondCounter();
  379. for (int pos = 0; pos < input.getNumSamples(); pos += block)
  380. {
  381. const int n = juce::jmin (block, input.getNumSamples() - pos);
  382. buf.setSize (ch, n, false, false, true);
  383. buf.clear();
  384. for (int c = 0; c < juce::jmin (mainIn, totalIn); ++c)
  385. buf.copyFrom (c, 0, input, juce::jmin (c, input.getNumChannels() - 1), pos, n);
  386. midi.clear();
  387. plugin->processBlock (buf, midi);
  388. playHead.samples += n;
  389. const auto due = start + (juce::uint32) ((double) (pos + n) * 1000.0 / rate);
  390. do pump (1); while (juce::Time::getMillisecondCounter() < due);
  391. }
  392. log ("played " + in.getFileName());
  393. }
  394. void runSilence (int samples)
  395. {
  396. pump (0);
  397. const int ch = juce::jmax (plugin->getTotalNumInputChannels(), plugin->getTotalNumOutputChannels());
  398. juce::AudioBuffer<float> buf (ch, block);
  399. while (samples > 0)
  400. {
  401. const int n = juce::jmin (block, samples);
  402. buf.setSize (ch, n, false, false, true);
  403. buf.clear();
  404. midi.clear();
  405. plugin->processBlock (buf, midi);
  406. playHead.samples += n;
  407. samples -= n;
  408. }
  409. }
  410. bool readWav (const juce::File& f, juce::AudioBuffer<float>& out)
  411. {
  412. juce::WavAudioFormat wav;
  413. std::unique_ptr<juce::AudioFormatReader> r (wav.createReaderFor (f.createInputStream().release(), true));
  414. if (r == nullptr) return false;
  415. out.setSize ((int) r->numChannels, (int) r->lengthInSamples);
  416. r->read (&out, 0, (int) r->lengthInSamples, 0, true, true);
  417. return true;
  418. }
  419. void process (const juce::File& in, const juce::File& outFile, const juce::File& sc)
  420. {
  421. juce::AudioBuffer<float> input, side;
  422. if (! readWav (in, input)) { log ("error: cannot read " + in.getFullPathName()); return; }
  423. const bool haveSide = sc != juce::File() && readWav (sc, side);
  424. const int mainIn = juce::jmax (1, plugin->getMainBusNumInputChannels());
  425. const int totalIn = plugin->getTotalNumInputChannels();
  426. const int totalOut = plugin->getTotalNumOutputChannels();
  427. const int ch = juce::jmax (totalIn, totalOut);
  428. const int len = input.getNumSamples();
  429. juce::AudioBuffer<float> result (totalOut, len);
  430. juce::AudioBuffer<float> buf (ch, block);
  431. for (int pos = 0; pos < len; pos += block)
  432. {
  433. const int n = juce::jmin (block, len - pos);
  434. buf.setSize (ch, n, false, false, true);
  435. buf.clear();
  436. for (int c = 0; c < juce::jmin (mainIn, totalIn); ++c)
  437. buf.copyFrom (c, 0, input, juce::jmin (c, input.getNumChannels() - 1), pos, n);
  438. if (haveSide)
  439. for (int c = mainIn; c < totalIn; ++c)
  440. buf.copyFrom (c, 0, side, juce::jmin (c - mainIn, side.getNumChannels() - 1), juce::jmin (pos, side.getNumSamples() - n), n);
  441. midi.clear();
  442. plugin->processBlock (buf, midi);
  443. playHead.samples += n;
  444. for (int c = 0; c < totalOut; ++c)
  445. result.copyFrom (c, pos, buf, c, 0, n);
  446. }
  447. outFile.deleteFile();
  448. juce::WavAudioFormat wav;
  449. std::unique_ptr<juce::OutputStream> os (outFile.createOutputStream().release());
  450. std::unique_ptr<juce::AudioFormatWriter> w (wav.createWriterFor (os.get(), rate, (unsigned) totalOut, 32, {}, 0));
  451. if (w == nullptr) { log ("error: cannot write " + outFile.getFullPathName()); return; }
  452. os.release();
  453. w->writeFromAudioSampleBuffer (result, 0, len);
  454. w.reset();
  455. log ("processed " + juce::String (len) + " samples -> " + outFile.getFileName() + " latency=" + juce::String (plugin->getLatencySamples()));
  456. }
  457. static juce::String norm (float v) { return juce::String (v, 6); }
  458. void params (const juce::File& out, int steps)
  459. {
  460. juce::String t;
  461. t << "index\tid\tname\tlabel\tdefault\tdefaultText\tnumSteps\tdiscrete\tboolean\tautomatable";
  462. for (int k = 0; k <= steps; ++k) t << "\tv" << norm ((float) k / (float) steps);
  463. t << "\n";
  464. const auto& ps = plugin->getParameters();
  465. for (int i = 0; i < ps.size(); ++i)
  466. {
  467. auto* p = ps[i];
  468. juce::String id;
  469. if (auto* hp = dynamic_cast<juce::HostedAudioProcessorParameter*> (p)) id = hp->getParameterID();
  470. const float d = p->getDefaultValue();
  471. t << i << "\t" << id << "\t" << p->getName (256) << "\t" << p->getLabel() << "\t" << norm (d) << "\t" << p->getText (d, 256) << "\t"
  472. << p->getNumSteps() << "\t" << (int) p->isDiscrete() << "\t" << (int) p->isBoolean() << "\t" << (int) p->isAutomatable();
  473. for (int k = 0; k <= steps; ++k) t << "\t" << p->getText ((float) k / (float) steps, 256);
  474. t << "\n";
  475. }
  476. out.replaceWithText (t);
  477. log ("params " + juce::String (ps.size()) + " -> " + out.getFileName());
  478. }
  479. void texts (juce::AudioProcessorParameter* p, const juce::File& out, int steps)
  480. {
  481. juce::String t;
  482. for (int k = 0; k <= steps; ++k)
  483. {
  484. const float v = (float) k / (float) steps;
  485. t << norm (v) << "\t" << p->getText (v, 256) << "\n";
  486. }
  487. out.replaceWithText (t);
  488. log ("texts " + p->getName (256) + " -> " + out.getFileName());
  489. }
  490. // whether a parameter text shows the asked text: names equal (case ignored), numbers within 0.1 % ("12.0 kHz" = 12000)
  491. static bool shows (const juce::String& shown, const juce::String& text)
  492. {
  493. const auto first = text.trimStart()[0];
  494. if (! ((first >= '0' && first <= '9') || first == '-' || first == '+' || first == '.'))
  495. return shown.trim().equalsIgnoreCase (text.trim());
  496. const double want = text.getDoubleValue();
  497. const double got = shown.getDoubleValue() * (shown.containsIgnoreCase ("khz") && ! text.containsIgnoreCase ("k") ? 1000.0 : 1.0);
  498. return std::abs (got - want) <= 1e-3 * juce::jmax (1.0, std::abs (want));
  499. }
  500. // text -> normalized value: numbers go through the plugin's own parser; names (enumerations) are found by scanning
  501. // the value -> text mapping (the middle of the range that shows the text). −1 when no value shows the text (round
  502. // tp172b7: Pro-MB's "Minimum Phase" was not a text of its mode; the old fallback set 0 = Linear Phase silently)
  503. static float textToValue (juce::AudioProcessorParameter* p, const juce::String& text)
  504. {
  505. const auto first = text.trimStart()[0];
  506. const int n = 4000;
  507. if ((first >= '0' && first <= '9') || first == '-' || first == '+' || first == '.')
  508. {
  509. const double want = text.getDoubleValue();
  510. const float v = p->getValueForText (text);
  511. if (v >= 0.0f && v <= 1.0f && shows (p->getText (v, 256), text)) // (a parser may return an unnormalized value)
  512. return v;
  513. int lo = -1, hi = -1; // stepped numbers the parser does not take: scan for the value
  514. for (int k = 0; k <= n; ++k)
  515. 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; }
  516. else if (lo >= 0) break;
  517. return lo < 0 ? -1.0f : (float) (lo + hi) / (2.0f * n);
  518. }
  519. int lo = -1, hi = -1;
  520. for (int k = 0; k <= n; ++k)
  521. if (p->getText ((float) k / n, 256).trim().equalsIgnoreCase (text.trim())) { if (lo < 0) lo = k; hi = k; }
  522. else if (lo >= 0) break;
  523. return lo < 0 ? -1.0f : (float) (lo + hi) / (2.0f * n);
  524. }
  525. void setParam (juce::AudioProcessorParameter* p, float v)
  526. {
  527. p->setValue (v);
  528. }
  529. void run (const juce::StringArray& lines)
  530. {
  531. for (auto line : lines)
  532. {
  533. // '#' starts a comment at the start of a line or after a space when a space follows ("# note"), so that
  534. // `set #12 0.5` (a parameter by index) works (round 170c)
  535. line = line.trim();
  536. if (line.startsWithChar ('#'))
  537. continue;
  538. line = line.upToFirstOccurrenceOf (" # ", false, false).trim();
  539. if (line.isEmpty()) continue;
  540. juce::StringArray a;
  541. a.addTokens (line, " \t", "\"");
  542. a.removeEmptyStrings();
  543. for (auto& s : a) s = s.unquoted();
  544. const auto cmd = a[0];
  545. pump (0);
  546. if (cmd == "pump") { pump (a[1].getIntValue()); continue; }
  547. if (cmd == "buses") // round 170c: which main layouts the plugin accepts (1…8 channels in / out)
  548. {
  549. if (plugin == nullptr) { log ("error: no plugin"); continue; }
  550. juce::String ok;
  551. for (int i = 1; i <= 8; ++i)
  552. for (int o = 1; o <= 8; ++o)
  553. {
  554. auto l = plugin->getBusesLayout();
  555. if (l.inputBuses.isEmpty() || l.outputBuses.isEmpty()) continue;
  556. l.inputBuses.getReference (0) = juce::AudioChannelSet::canonicalChannelSet (i);
  557. l.outputBuses.getReference (0) = juce::AudioChannelSet::canonicalChannelSet (o);
  558. if (plugin->checkBusesLayoutSupported (l)) ok << " " << i << "/" << o;
  559. }
  560. log ("buses now in=" + juce::String (plugin->getMainBusNumInputChannels()) + " out=" + juce::String (plugin->getMainBusNumOutputChannels()) + " supported:" + ok);
  561. continue;
  562. }
  563. if (cmd == "echo") { log (line.fromFirstOccurrenceOf (" ", false, false)); continue; }
  564. if (cmd == "editor" && ! a[1].endsWithIgnoreCase (".png")) // `editor <out.png> …` is the PrintWindow shot below
  565. {
  566. if (plugin == nullptr) { log ("error: no plugin"); continue; }
  567. std::unique_ptr<juce::AudioProcessorEditor> ed (plugin->createEditorIfNeeded());
  568. if (ed == nullptr) { log ("error: no editor"); continue; }
  569. juce::DocumentWindow win ("fxmeasure editor", juce::Colours::black, 0, true);
  570. win.setUsingNativeTitleBar (false);
  571. win.setTitleBarHeight (0);
  572. win.setContentNonOwned (ed.get(), true);
  573. win.setTopLeftPosition (a.size() > 3 ? a[2].getIntValue() : 100, a.size() > 3 ? a[3].getIntValue() : 100);
  574. win.setVisible (true);
  575. win.toFront (true);
  576. const auto b = ed->getScreenBounds();
  577. log ("editor " + juce::String (b.getX()) + " " + juce::String (b.getY()) + " " + juce::String (b.getWidth()) + " " + juce::String (b.getHeight()));
  578. pump (a[1].getIntValue());
  579. win.clearContentComponent();
  580. ed.reset();
  581. continue;
  582. }
  583. if (cmd == "load")
  584. {
  585. if (a.size() > 2) rate = a[2].getDoubleValue();
  586. if (a.size() > 3) block = a[3].getIntValue();
  587. juce::OwnedArray<juce::PluginDescription> types;
  588. // a big shell takes many minutes to describe: the descriptions are cached in fxmeasure-cache.xml (cwd)
  589. const juce::File cache = juce::File::getCurrentWorkingDirectory().getChildFile ("fxmeasure-cache.xml");
  590. juce::KnownPluginList known;
  591. if (auto xml = juce::parseXML (cache)) known.recreateFromXml (*xml);
  592. for (const auto& t : known.getTypes())
  593. if (t.fileOrIdentifier == a[1]) types.add (new juce::PluginDescription (t));
  594. if (types.isEmpty())
  595. {
  596. for (auto* f : formats.getFormats())
  597. if (f->fileMightContainThisPluginType (a[1])) f->findAllTypesForFile (types, a[1]);
  598. for (auto* t : types) known.addType (*t);
  599. if (auto xml = known.createXml()) xml->writeTo (cache);
  600. }
  601. if (types.isEmpty()) { log ("error: no plugin in " + a[1]); continue; }
  602. // a shell (one file, many plugins: Waves) — `load <file> <rate> <block> <name>` picks the plugin whose
  603. // name equals <name> (else the first one containing it); `list` prints them all
  604. if (a.size() > 4 && a[4] == "?") { for (auto* t : types) log ("plugin " + t->name + " | " + t->createIdentifierString()); continue; }
  605. int pick = 0;
  606. if (a.size() > 4)
  607. {
  608. const auto want = line.fromFirstOccurrenceOf (a[3], false, false).fromFirstOccurrenceOf (" ", false, false).trim().unquoted();
  609. pick = -1;
  610. for (int i = 0; i < types.size() && pick < 0; ++i) if (types[i]->name.equalsIgnoreCase (want)) pick = i;
  611. for (int i = 0; i < types.size() && pick < 0; ++i) if (types[i]->name.containsIgnoreCase (want)) pick = i;
  612. if (pick < 0) { log ("error: no plugin named " + want + " in " + a[1] + " (" + juce::String (types.size()) + " plugins)"); continue; }
  613. }
  614. juce::String err;
  615. plugin = formats.createPluginInstance (*types[pick], rate, block, err);
  616. // round 170c: a Waves shell's first instance in a process comes up as another of its plugins (LYNX's
  617. // createRightInstance, PluginHost.cpp): created again it is the right one (the wrong ones stay alive
  618. // until then). Without this every Waves measurement ran a surround meter (bit-identical output).
  619. {
  620. std::vector<std::unique_ptr<juce::AudioPluginInstance>> wrong;
  621. for (int attempt = 0; attempt < 3 && plugin != nullptr && plugin->getName() != types[pick]->name; ++attempt)
  622. {
  623. log ("mismatch: asked " + types[pick]->name + ", got " + plugin->getName() + " (again)");
  624. wrong.push_back (std::move (plugin));
  625. plugin = formats.createPluginInstance (*types[pick], rate, block, err);
  626. }
  627. if (plugin != nullptr && plugin->getName() != types[pick]->name)
  628. {
  629. log ("error: the shell handed out " + plugin->getName() + " for " + types[pick]->name);
  630. plugin.reset();
  631. continue;
  632. }
  633. }
  634. if (plugin == nullptr) { log ("error: " + err); continue; }
  635. log ("instance " + plugin->getName());
  636. log ("loaded " + types[pick]->name + " by " + types[pick]->manufacturerName + " v" + types[pick]->version + " params=" + juce::String (plugin->getParameters().size())
  637. + " inBuses=" + juce::String (plugin->getBusCount (true)) + " outBuses=" + juce::String (plugin->getBusCount (false)));
  638. prepare();
  639. continue;
  640. }
  641. if (plugin == nullptr) { log ("error: no plugin loaded for " + cmd); continue; }
  642. if (cmd == "rate") { rate = a[1].getDoubleValue(); if (a.size() > 2) block = a[2].getIntValue(); prepare(); }
  643. else if (cmd == "sidechain") { sidechain = a[1] == "on"; prepare(); }
  644. else if (cmd == "nonrealtime") { plugin->setNonRealtime (a[1].getIntValue() != 0); log ("nonrealtime " + a[1]); }
  645. else if (cmd == "params") params (juce::File (a[1]), a.size() > 2 ? a[2].getIntValue() : 10);
  646. else if (cmd == "texts")
  647. {
  648. if (auto* p = find (a[1])) texts (p, juce::File (a[2]), a.size() > 3 ? a[3].getIntValue() : 200);
  649. else log ("error: no parameter " + a[1]);
  650. }
  651. else if (cmd == "set" || cmd == "settext")
  652. {
  653. auto* p = find (a[1]);
  654. if (p == nullptr) { log ("error: no parameter " + a[1] + " (script stopped)"); failed = true; return; }
  655. const auto valueText = line.fromFirstOccurrenceOf (a[1], false, false).trim().unquoted();
  656. const float v = cmd == "set" ? valueText.getFloatValue() : textToValue (p, valueText);
  657. if (cmd == "settext" && v < 0.0f)
  658. {
  659. log ("error: no value of " + p->getName (256) + " shows the text \"" + valueText + "\" (script stopped)");
  660. failed = true;
  661. return;
  662. }
  663. setParam (p, juce::jlimit (0.0f, 1.0f, v));
  664. log ("set " + p->getName (256) + " = " + norm (p->getValue()) + " (" + p->getCurrentValueAsText() + ")");
  665. if (cmd == "settext" && ! shows (p->getCurrentValueAsText(), valueText))
  666. {
  667. // round tp172b7: the plugin now shows another text than asked (its value -> text scan misled us)
  668. log ("error: " + p->getName (256) + " shows \"" + p->getCurrentValueAsText() + "\", not \"" + valueText + "\" (script stopped)");
  669. failed = true;
  670. return;
  671. }
  672. }
  673. else if (cmd == "get")
  674. {
  675. if (auto* p = find (a[1])) log ("get " + p->getName (256) + " = " + norm (p->getValue()) + " (" + p->getCurrentValueAsText() + ")");
  676. else log ("error: no parameter " + a[1]);
  677. }
  678. else if (cmd == "defaults")
  679. {
  680. for (auto* p : plugin->getParameters()) setParam (p, p->getDefaultValue());
  681. log ("defaults");
  682. }
  683. else if (cmd == "reset") { plugin->reset(); log ("reset"); }
  684. else if (cmd == "transport")
  685. {
  686. // transport <bpm> [samplePosition|keep] [playing 0|1]: the host's tempo and song position
  687. playHead.bpm = a[1].getDoubleValue();
  688. if (a.size() > 2 && a[2] != "keep") playHead.samples = a[2].getLargeIntValue();
  689. if (a.size() > 3) playHead.playing = a[3].getIntValue() != 0;
  690. log ("transport " + juce::String (playHead.bpm) + " " + juce::String (playHead.samples));
  691. }
  692. else if (cmd == "settle") runSilence ((int) (a[1].getDoubleValue() * rate));
  693. else if (cmd == "process") process (juce::File (a[1]), juce::File (a[2]), a.size() > 3 ? juce::File (a[3]) : juce::File());
  694. else if (cmd == "editor")
  695. {
  696. juce::StringArray actions; // see the header: clicks, drag, hover, play, shot, in order
  697. for (int i = 3; i < a.size(); ++i)
  698. actions.add (a[i]);
  699. editorShot (juce::File (a[1]), a.size() > 2 ? a[2].getIntValue() : 1500, actions);
  700. }
  701. else if (cmd == "latency") { pump (50); log ("latency " + juce::String (plugin->getLatencySamples())); }
  702. else if (cmd == "savestate")
  703. {
  704. juce::MemoryBlock m;
  705. plugin->getStateInformation (m);
  706. juce::File (a[1]).replaceWithData (m.getData(), m.getSize());
  707. log ("savestate " + juce::String ((int) m.getSize()) + " bytes");
  708. }
  709. else if (cmd == "loadstate")
  710. {
  711. juce::MemoryBlock m;
  712. juce::File (a[1]).loadFileAsData (m);
  713. plugin->setStateInformation (m.getData(), (int) m.getSize());
  714. log ("loadstate");
  715. }
  716. else if (cmd == "savecomponent" || cmd == "loadcomponent")
  717. {
  718. // the raw VST3 component state (what a DAW project stores), inside JUCE's VST3PluginState wrapper
  719. juce::MemoryBlock m;
  720. plugin->getStateInformation (m);
  721. auto xml = juce::AudioProcessor::getXmlFromBinary (m.getData(), (int) m.getSize());
  722. if (xml == nullptr) { log ("error: no VST3 state"); continue; }
  723. auto* comp = xml->getChildByName ("IComponent");
  724. if (comp == nullptr) { log ("error: no IComponent"); continue; }
  725. juce::MemoryBlock raw;
  726. if (cmd == "savecomponent")
  727. {
  728. raw.fromBase64Encoding (comp->getAllSubText());
  729. juce::File (a[1]).replaceWithData (raw.getData(), raw.getSize());
  730. log ("savecomponent " + juce::String ((int) raw.getSize()) + " bytes");
  731. }
  732. else
  733. {
  734. juce::File (a[1]).loadFileAsData (raw);
  735. comp->deleteAllTextElements();
  736. comp->addTextElement (raw.toBase64Encoding());
  737. if (auto* ctl = xml->getChildByName ("IEditController")) xml->removeChildElement (ctl, true);
  738. juce::MemoryBlock out;
  739. juce::AudioProcessor::copyXmlToBinary (*xml, out);
  740. plugin->setStateInformation (out.getData(), (int) out.getSize());
  741. log ("loadcomponent " + juce::String ((int) raw.getSize()) + " bytes");
  742. }
  743. }
  744. else log ("error: unknown command " + cmd);
  745. }
  746. }
  747. };
  748. } // namespace
  749. int main (int argc, char** argv)
  750. {
  751. if (argc < 2) { std::printf ("usage: fxmeasure script.txt\n"); return 2; }
  752. std::printf ("fxmeasure start\n"); std::fflush (stdout);
  753. juce::ScopedJuceInitialiser_GUI init;
  754. std::printf ("init done\n"); std::fflush (stdout);
  755. Host host;
  756. host.formats.addFormat (new juce::VST3PluginFormat());
  757. juce::StringArray lines;
  758. juce::File::getCurrentWorkingDirectory().getChildFile (juce::String::fromUTF8 (argv[1])).readLines (lines);
  759. std::printf ("%d lines\n", lines.size()); std::fflush (stdout);
  760. host.run (lines);
  761. host.plugin.reset();
  762. std::printf (host.failed ? "FAILED\n" : "done\n"); std::fflush (stdout);
  763. std::_Exit (host.failed ? 3 : 0); // skip global teardown (some plugins hang there)
  764. }