4
0

fxrender.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. // fxrender: renders WAV files through one of LYNX's built-in effects, offline (round tp172b).
  2. //
  3. // The LYNX side of the black-box parity harness (tools/fxmeasure renders the originals): the same stimulus through
  4. // a LYNX effect at matched settings, so scripts/fxparity.py can score the pair like FL's own render tests.
  5. //
  6. // fxrender <effect name | kind index> [options] <in.wav> <out.wav> [<in.wav> <out.wav> ...]
  7. // --rate <hz> sample rate the effect is prepared at (default: the input file's)
  8. // --block <n> block size (default 512)
  9. // --ff <translator> <file> a FabFilter state (raw component or JUCE host state) translated as LYNX loads one
  10. // (core/FabFilterStates.h: pro-c3, pro-mb, pro-g, saturn2, pro-q4, pro-ds, pro-l2)
  11. // --sub <name> <file> the substitute LYNX opens for the plugin named <name> (core/PluginSubstitutes.h), built
  12. // from that plugin's saved component state <file>; the <effect> argument is then
  13. // ignored (any name, e.g. "-") and replaced by the substitute's effect
  14. // --set <i>=<v> parameter i to the normalized value v
  15. // --text <i>=<value> parameter i to the value whose text (formatEffectParam) matches: a number = the
  16. // closest numeric text, otherwise the same text (case-insensitive)
  17. // --songpos <samples> the song position before each block (<samples> at the file's first sample, 120 BPM)
  18. // --ticks <ppq> [mode] also split blocks at song ticks (a host that cuts its buffers on a <ppq> grid; mode 0 floor,
  19. // 1 round, 2 ceil of the tick's sample position)
  20. // --settle <s> silence processed before each file (default 0.5 s, after a reset)
  21. // --settlesong with --songpos: the song position runs through the settle too (round 190nh)
  22. // --slotmix apply the slot's dry / wet (a substitute's or translator's slot mix) as the mixer does
  23. // (round 190jh: dry + (wet - dry) * mix below 0.999; off by default so older banks reproduce)
  24. // --list print the parameters (index, name, value, text) and exit
  25. // --dump <file> write the parameters ("index value" lines; LYNX --parityshot reads them)
  26. // Every input is processed from a reset; the output is a 32-bit float stereo WAV, not latency-compensated (the
  27. // latency is printed). Inputs: 32-bit float or 16 / 24-bit PCM WAV, mono or stereo.
  28. // Build (with the core, like the other tools): see scripts/build-local.sh, or
  29. // $CXX $FLAGS $CORE $WAVPACK tools/fxrender.cpp -o build-local/fxrender
  30. #include <algorithm>
  31. #include <cctype>
  32. #include <cmath>
  33. #include <cstdint>
  34. #include <cstdio>
  35. #include <cstdlib>
  36. #include <cstring>
  37. #include <fstream>
  38. #include <iterator>
  39. #include <string>
  40. #include <vector>
  41. #include "core/Effects.h"
  42. #include "core/FabFilterStates.h"
  43. #include "core/PluginSubstitutes.h"
  44. using namespace lynx;
  45. namespace
  46. {
  47. struct Audio
  48. {
  49. int rate = 48000;
  50. std::vector<float> l, r;
  51. };
  52. bool readWav (const std::string& path, Audio& a)
  53. {
  54. std::ifstream f (path, std::ios::binary);
  55. std::vector<std::uint8_t> d ((std::istreambuf_iterator<char> (f)), {});
  56. if (d.size() < 12 || std::memcmp (d.data(), "RIFF", 4) != 0)
  57. return false;
  58. int format = 0, channels = 0, bits = 0;
  59. for (std::size_t i = 12; i + 8 <= d.size();)
  60. {
  61. std::uint32_t size;
  62. std::memcpy (&size, d.data() + i + 4, 4);
  63. if (std::memcmp (d.data() + i, "fmt ", 4) == 0)
  64. {
  65. std::uint16_t fmt, ch, bps;
  66. std::uint32_t sr;
  67. std::memcpy (&fmt, d.data() + i + 8, 2);
  68. std::memcpy (&ch, d.data() + i + 10, 2);
  69. std::memcpy (&sr, d.data() + i + 12, 4);
  70. std::memcpy (&bps, d.data() + i + 22, 2);
  71. format = fmt == 0xFFFE ? (bps == 32 ? 3 : 1) : fmt;
  72. channels = ch;
  73. bits = bps;
  74. a.rate = (int) sr;
  75. }
  76. else if (std::memcmp (d.data() + i, "data", 4) == 0 && channels > 0)
  77. {
  78. const auto* p = d.data() + i + 8;
  79. const std::size_t bytes = std::min<std::size_t> (size, d.size() - i - 8);
  80. const int width = bits / 8;
  81. const std::size_t frames = bytes / (std::size_t) (width * channels);
  82. a.l.resize (frames);
  83. a.r.resize (frames);
  84. for (std::size_t n = 0; n < frames; ++n)
  85. for (int c = 0; c < std::min (channels, 2); ++c)
  86. {
  87. const auto* s = p + (n * (std::size_t) channels + (std::size_t) c) * (std::size_t) width;
  88. float v = 0.0f;
  89. if (format == 3 && width == 4)
  90. std::memcpy (&v, s, 4);
  91. else if (width == 2)
  92. v = (float) (std::int16_t) (s[0] | (s[1] << 8)) / 32768.0f;
  93. else if (width == 3)
  94. v = (float) ((std::int32_t) ((std::uint32_t) s[0] << 8 | (std::uint32_t) s[1] << 16 | (std::uint32_t) s[2] << 24) >> 8) / 8388608.0f;
  95. else if (width == 4)
  96. v = (float) ((double) (std::int32_t) (s[0] | (s[1] << 8) | (s[2] << 16) | ((std::uint32_t) s[3] << 24)) / 2147483648.0);
  97. (c == 0 ? a.l : a.r)[n] = v;
  98. }
  99. if (channels == 1)
  100. a.r = a.l;
  101. return true;
  102. }
  103. i += 8 + size + (size & 1);
  104. }
  105. return false;
  106. }
  107. bool writeWav (const std::string& path, const Audio& a)
  108. {
  109. std::ofstream f (path, std::ios::binary);
  110. const std::uint32_t frames = (std::uint32_t) a.l.size(), data = frames * 8;
  111. const auto u32 = [&] (std::uint32_t v) { f.write ((const char*) &v, 4); };
  112. const auto u16 = [&] (std::uint16_t v) { f.write ((const char*) &v, 2); };
  113. f.write ("RIFF", 4); u32 (36 + data); f.write ("WAVEfmt ", 8); u32 (16); u16 (3); u16 (2); u32 ((std::uint32_t) a.rate);
  114. u32 ((std::uint32_t) a.rate * 8); u16 (8); u16 (32); f.write ("data", 4); u32 (data);
  115. for (std::uint32_t n = 0; n < frames; ++n)
  116. {
  117. f.write ((const char*) &a.l[n], 4);
  118. f.write ((const char*) &a.r[n], 4);
  119. }
  120. return (bool) f;
  121. }
  122. std::string lower (std::string s)
  123. {
  124. for (auto& c : s)
  125. c = (char) std::tolower ((unsigned char) c);
  126. return s;
  127. }
  128. bool numericText (const std::string& t, double& v)
  129. {
  130. const char* s = t.c_str();
  131. while (*s == ' ' || *s == '+')
  132. ++s;
  133. char* end = nullptr;
  134. v = std::strtod (s, &end);
  135. if (end == s)
  136. return false;
  137. // "1.2 k" / "1.2 kHz": thousands
  138. while (*end == ' ')
  139. ++end;
  140. if (*end == 'k' || *end == 'K')
  141. v *= 1000.0;
  142. return true;
  143. }
  144. float valueForText (EffectKind kind, int param, const std::string& want, const EffectParams& context)
  145. {
  146. double target = 0.0;
  147. const bool numeric = numericText (want, target);
  148. float best = -1.0f;
  149. double bestErr = 1e300;
  150. constexpr int steps = 20000;
  151. for (int k = 0; k <= steps; ++k)
  152. {
  153. const float v = (float) k / steps;
  154. const auto text = formatEffectParam (kind, param, v, 120.0, context);
  155. double got = 0.0;
  156. if (numeric)
  157. {
  158. if (numericText (text, got))
  159. {
  160. const double err = std::abs (got - target);
  161. if (err < bestErr)
  162. bestErr = err, best = v;
  163. }
  164. }
  165. else if (lower (text) == lower (want))
  166. return v;
  167. }
  168. if (best < 0.0f)
  169. std::fprintf (stderr, "warning: no value of parameter %d reads \"%s\"\n", param, want.c_str());
  170. return std::max (best, 0.0f);
  171. }
  172. } // namespace
  173. int main (int argc, char** argv)
  174. {
  175. if (argc < 2)
  176. {
  177. std::fprintf (stderr, "usage: fxrender <effect> [--rate hz] [--block n] [--ff translator file] [--set i=v] [--text i=value] [--list] in.wav out.wav ...\n");
  178. return 2;
  179. }
  180. const std::string want = argv[1];
  181. int kindIndex = -1;
  182. for (int k = 0; k <= (int) lastEffectKind; ++k)
  183. if (lower (effectInfo ((EffectKind) k).name) == lower (want) || std::to_string (k) == want)
  184. kindIndex = k;
  185. const bool sub = std::any_of (argv + 2, argv + argc, [] (const char* a) { return std::strcmp (a, "--sub") == 0; });
  186. if (kindIndex < 0 && sub)
  187. kindIndex = 0;
  188. if (kindIndex < 0)
  189. {
  190. std::fprintf (stderr, "unknown effect: %s\n", want.c_str());
  191. return 2;
  192. }
  193. auto kind = (EffectKind) kindIndex;
  194. auto slot = makeEffectSlot (kind);
  195. double rate = 0.0, settle = 0.5;
  196. bool songPos = false, settleSong = false;
  197. double songOffset = 0.0; // samples
  198. int block = 512;
  199. double tickPpq = 0.0;
  200. int tickMode = 0;
  201. bool list = false, slotMix = false;
  202. std::string dump;
  203. std::vector<std::string> files;
  204. for (int i = 2; i < argc; ++i)
  205. {
  206. const std::string a = argv[i];
  207. if (a == "--rate" && i + 1 < argc)
  208. rate = std::atof (argv[++i]);
  209. else if (a == "--block" && i + 1 < argc)
  210. block = std::max (1, std::atoi (argv[++i]));
  211. else if (a == "--songpos" && i + 1 < argc)
  212. songPos = true, songOffset = std::atof (argv[++i]); // round 188i: the song position (from 0 at the file's first sample) before each block, as a host gives it
  213. else if (a == "--ticks" && i + 2 < argc)
  214. tickPpq = std::atof (argv[++i]), tickMode = std::atoi (argv[++i]);
  215. else if (a == "--slotmix")
  216. slotMix = true;
  217. else if (a == "--settlesong")
  218. settleSong = true;
  219. else if (a == "--settle" && i + 1 < argc)
  220. settle = std::atof (argv[++i]);
  221. else if (a == "--list")
  222. list = true;
  223. else if (a == "--dump" && i + 1 < argc)
  224. dump = argv[++i];
  225. else if (a == "--ff" && i + 2 < argc)
  226. {
  227. const auto translate = fabfilter::translatorNamed (argv[++i]);
  228. std::ifstream f (argv[++i], std::ios::binary);
  229. const std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (f)), {});
  230. const auto state = fabfilter::parseState (bytes);
  231. const int n = translate != nullptr && state ? translate (*state, slot) : 0;
  232. std::printf ("translated %d parameters (state %s, %u values)\n", n, state ? "read" : "not read", state ? state->count : 0u);
  233. if (n == 0) // as a substitute slot that cannot read the state: the effect's defaults
  234. std::printf ("warning: state not translated, the effect's defaults are used\n");
  235. }
  236. else if (a == "--sub" && i + 2 < argc)
  237. {
  238. PluginIdentity id;
  239. id.format = ForeignPlugin::Format::vst3;
  240. id.name = argv[++i];
  241. std::ifstream f (argv[++i], std::ios::binary);
  242. id.state.assign (std::istreambuf_iterator<char> (f), {});
  243. const auto* entry = findPluginSubstitute (id, false);
  244. if (entry == nullptr)
  245. {
  246. std::fprintf (stderr, "no substitute for: %s\n", id.name.c_str());
  247. return 2;
  248. }
  249. int n = 0;
  250. slot = makeSubstituteSlot (*entry, &id, &n);
  251. kind = slot.kind;
  252. std::printf ("substitute %s, translated %d parameters (state %zu bytes)\n", effectInfo (kind).name, n, id.state.size());
  253. }
  254. else if ((a == "--set" || a == "--text") && i + 1 < argc)
  255. {
  256. const std::string s = argv[++i];
  257. const auto eq = s.find ('=');
  258. if (eq == std::string::npos)
  259. return 2;
  260. const int p = std::atoi (s.substr (0, eq).c_str());
  261. if (p < 0 || p >= maxEffectParams)
  262. return 2;
  263. slot.params[(std::size_t) p] = a == "--set" ? (float) std::atof (s.substr (eq + 1).c_str())
  264. : valueForText (kind, p, s.substr (eq + 1), slot.params);
  265. }
  266. else
  267. files.push_back (a);
  268. }
  269. const auto& info = effectInfo (kind);
  270. if (list)
  271. {
  272. for (std::size_t p = 0; p < info.params.size(); ++p)
  273. std::printf ("%zu\t%s\t%.6f\t%s\n", p, info.params[p].name, slot.params[p],
  274. formatEffectParam (kind, (int) p, slot.params[p], 120.0, slot.params).c_str());
  275. return 0;
  276. }
  277. if (! dump.empty())
  278. if (FILE* f = std::fopen (dump.c_str(), "w"))
  279. {
  280. for (std::size_t p = 0; p < info.params.size(); ++p)
  281. std::fprintf (f, "%zu %.9g\n", p, slot.params[p]);
  282. std::fclose (f);
  283. }
  284. for (std::size_t p = 0; p < info.params.size(); ++p)
  285. if (std::abs (slot.params[p] - info.params[p].defaultValue) > 1e-6f)
  286. std::printf ("param %zu %s = %.6f (%s)\n", p, info.params[p].name, slot.params[p],
  287. formatEffectParam (kind, (int) p, slot.params[p], 120.0, slot.params).c_str());
  288. if (slot.mix < 0.999f)
  289. std::printf ("slot mix %.4f%s\n", slot.mix, slotMix ? "" : " (not applied: --slotmix)");
  290. for (std::size_t f = 0; f + 1 < files.size(); f += 2)
  291. {
  292. Audio in;
  293. if (! readWav (files[f], in))
  294. {
  295. std::fprintf (stderr, "cannot read %s\n", files[f].c_str());
  296. return 1;
  297. }
  298. const double sr = rate > 0.0 ? rate : (double) in.rate;
  299. auto fx = makeEffect (slot);
  300. fx->prepare (sr);
  301. fx->reset();
  302. std::vector<float> l ((std::size_t) block), r ((std::size_t) block);
  303. const int settleN = (int) (settle * sr);
  304. for (int left = settleN; left > 0; left -= block)
  305. {
  306. const int n = std::min (block, left);
  307. std::fill (l.begin(), l.end(), 0.0f);
  308. std::fill (r.begin(), r.end(), 0.0f);
  309. // round 190nh: --settlesong: the play head runs through the settle too (as fxmeasure's does)
  310. if (songPos && settleSong)
  311. fx->setSongPosition (((double) (settleN - left) - settleN + songOffset) / sr * 2.0 * (double) ppq);
  312. fx->process (l.data(), r.data(), n, slot.params, 120.0);
  313. }
  314. Audio out;
  315. out.rate = (int) sr;
  316. out.l = in.l;
  317. out.r = in.r;
  318. const double tickLen = tickPpq > 0.0 ? sr * 0.5 / tickPpq : 0.0; // 120 BPM
  319. const auto tickAt = [&] (long long k) {
  320. const double t = (double) k * tickLen - songOffset;
  321. return (long long) (tickMode == 0 ? std::floor (t) : tickMode == 1 ? std::floor (t + 0.5) : std::ceil (t));
  322. };
  323. for (std::size_t at = 0, n = 0; at < out.l.size(); at += n)
  324. {
  325. n = std::min<std::size_t> ((std::size_t) block, out.l.size() - at);
  326. if (tickLen > 0.0)
  327. {
  328. long long k = (long long) std::floor (((double) at + songOffset) / tickLen);
  329. while (tickAt (k) <= (long long) at)
  330. ++k;
  331. n = std::min<std::size_t> (n, (std::size_t) (tickAt (k) - (long long) at));
  332. }
  333. if (songPos)
  334. fx->setSongPosition (((double) at + songOffset) / sr * 2.0 * (double) ppq); // 120 BPM: two beats a second
  335. if (slotMix && slot.mix < 0.999f)
  336. {
  337. std::vector<float> dl (out.l.begin() + (long) at, out.l.begin() + (long) (at + n)), dr (out.r.begin() + (long) at, out.r.begin() + (long) (at + n));
  338. fx->process (out.l.data() + at, out.r.data() + at, (int) n, slot.params, 120.0);
  339. for (std::size_t k = 0; k < n; ++k)
  340. {
  341. out.l[at + k] = dl[k] + (out.l[at + k] - dl[k]) * slot.mix;
  342. out.r[at + k] = dr[k] + (out.r[at + k] - dr[k]) * slot.mix;
  343. }
  344. }
  345. else
  346. fx->process (out.l.data() + at, out.r.data() + at, (int) n, slot.params, 120.0);
  347. }
  348. bool finite = true;
  349. for (std::size_t n = 0; n < out.l.size(); ++n)
  350. finite = finite && std::isfinite (out.l[n]) && std::isfinite (out.r[n]);
  351. writeWav (files[f + 1], out);
  352. std::printf ("processed %zu samples -> %s latency=%d%s\n", out.l.size(), files[f + 1].c_str(), fx->latencySamples(),
  353. finite ? "" : " NON-FINITE");
  354. }
  355. return 0;
  356. }