fxrender.cpp 15 KB

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