4
0

recbench.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. // recbench (round 190pz): LYNX's audio recording path without an audio device, on the real classes
  2. // (core/TakeRecording.h TakeStream + WavTakeWriter), the way AudioEngine runs them: an "audio thread" paced at real
  3. // time pushes every block of N takes into their streams (as the device callback does), a "recording thread" drains
  4. // them every 5 ms into crash-safe WAV files (AudioEngine::Drainer / Take::drain: 8192-frame pulls, the writer's
  5. // header + sync every `--sync` seconds).
  6. //
  7. // Reports: the audio thread's cost per block and take (instructions, Linux) and its page faults / context switches
  8. // while recording (a first-touch page or a lock shows there), the recording thread's busy time, its longest write call
  9. // (the sync), the most frames a stream held (how close the ring came to full: capacity 2^20 frames) and the frames
  10. // lost (turned to silence). `--stall MS`: the recording thread also sleeps MS every second (a slow or busy disk).
  11. //
  12. // usage: recbench --dir <folder> [--takes N] [--seconds S] [--rate R] [--block B] [--channels 1|2] [--format pcm24|float32|pcm16]
  13. // [--sync S] [--stall MS] [--capacity FRAMES]
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <chrono>
  17. #include <cmath>
  18. #include <cstdio>
  19. #include <cstdlib>
  20. #include <cstring>
  21. #include <filesystem>
  22. #include <memory>
  23. #include <string>
  24. #include <thread>
  25. #include <vector>
  26. #include <sys/resource.h>
  27. #include <time.h>
  28. #if defined(__linux__)
  29. #include <linux/perf_event.h>
  30. #include <sys/ioctl.h>
  31. #include <sys/syscall.h>
  32. #include <unistd.h>
  33. #endif
  34. #include "core/TakeRecording.h"
  35. namespace
  36. {
  37. using namespace lynx;
  38. using Clock = std::chrono::steady_clock;
  39. struct InstructionCounter
  40. {
  41. int fd = -1;
  42. InstructionCounter()
  43. {
  44. #if defined(__linux__)
  45. perf_event_attr a {};
  46. a.type = PERF_TYPE_HARDWARE;
  47. a.size = sizeof (a);
  48. a.config = PERF_COUNT_HW_INSTRUCTIONS;
  49. a.disabled = 1;
  50. a.exclude_kernel = 1;
  51. a.exclude_hv = 1;
  52. fd = (int) syscall (SYS_perf_event_open, &a, 0, -1, -1, 0);
  53. #endif
  54. }
  55. ~InstructionCounter()
  56. {
  57. if (fd >= 0)
  58. close (fd);
  59. }
  60. void start() { if (fd >= 0) { ioctl (fd, PERF_EVENT_IOC_RESET, 0); ioctl (fd, PERF_EVENT_IOC_ENABLE, 0); } }
  61. long long stop()
  62. {
  63. if (fd < 0)
  64. return -1;
  65. ioctl (fd, PERF_EVENT_IOC_DISABLE, 0);
  66. long long v = -1;
  67. if (::read (fd, &v, sizeof (v)) != (ssize_t) sizeof (v))
  68. v = -1;
  69. return v;
  70. }
  71. };
  72. struct ThreadUsage
  73. {
  74. long minor = 0, major = 0, voluntary = 0, involuntary = 0;
  75. static ThreadUsage now()
  76. {
  77. rusage u {};
  78. getrusage (RUSAGE_THREAD, &u);
  79. return { u.ru_minflt, u.ru_majflt, u.ru_nvcsw, u.ru_nivcsw };
  80. }
  81. };
  82. double ms (Clock::duration d) { return std::chrono::duration<double, std::milli> (d).count(); }
  83. } // namespace
  84. int main (int argc, char** argv)
  85. {
  86. std::string dir;
  87. int takes = 8, rate = 48000, block = 128, channels = 2, capacity = 1 << 20;
  88. double seconds = 20.0, syncSeconds = 1.0, stallMs = 0.0;
  89. auto format = takes::SampleFormat::pcm24;
  90. for (int i = 1; i < argc; ++i)
  91. {
  92. const std::string a = argv[i];
  93. auto next = [&] { return i + 1 < argc ? std::string (argv[++i]) : std::string ("0"); };
  94. if (a == "--dir") dir = next();
  95. else if (a == "--takes") takes = std::clamp (std::atoi (next().c_str()), 1, 64);
  96. else if (a == "--seconds") seconds = std::atof (next().c_str());
  97. else if (a == "--rate") rate = std::atoi (next().c_str());
  98. else if (a == "--block") block = std::max (16, std::atoi (next().c_str()));
  99. else if (a == "--channels") channels = std::clamp (std::atoi (next().c_str()), 1, 2);
  100. else if (a == "--sync") syncSeconds = std::atof (next().c_str());
  101. else if (a == "--stall") stallMs = std::atof (next().c_str());
  102. else if (a == "--capacity") capacity = std::atoi (next().c_str());
  103. else if (a == "--format")
  104. {
  105. const auto f = next();
  106. format = f == "float32" ? takes::SampleFormat::float32 : f == "pcm16" ? takes::SampleFormat::pcm16 : takes::SampleFormat::pcm24;
  107. }
  108. }
  109. if (dir.empty())
  110. {
  111. std::fprintf (stderr, "usage: recbench --dir <folder> [--takes N] [--seconds S] [--rate R] [--block B] ...\n");
  112. return 2;
  113. }
  114. std::filesystem::create_directories (dir);
  115. struct Take
  116. {
  117. std::unique_ptr<takes::TakeStream> stream;
  118. takes::WavTakeWriter writer;
  119. std::atomic<std::int64_t> pulled { 0 };
  120. std::int64_t maxHeld = 0;
  121. };
  122. std::vector<std::unique_ptr<Take>> list;
  123. const auto made0 = Clock::now();
  124. for (int k = 0; k < takes; ++k)
  125. {
  126. auto t = std::make_unique<Take>();
  127. t->stream = std::make_unique<takes::TakeStream> (channels, capacity);
  128. if (! t->writer.open (dir + "/take" + std::to_string (k) + ".wav", rate, channels, format, syncSeconds))
  129. {
  130. std::fprintf (stderr, "could not open %s\n", t->writer.error().c_str());
  131. return 1;
  132. }
  133. list.push_back (std::move (t));
  134. }
  135. const auto makeMs = ms (Clock::now() - made0);
  136. // the input: a tone with a little noise per take
  137. std::vector<std::vector<float>> input ((std::size_t) channels, std::vector<float> ((std::size_t) block));
  138. std::atomic<bool> done { false };
  139. // recording thread
  140. double busyMs = 0.0, longestWrite = 0.0;
  141. std::vector<double> writeMs;
  142. std::thread recorder ([&] {
  143. std::vector<float> scratch (2 * 8192);
  144. auto nextStall = Clock::now() + std::chrono::seconds (1);
  145. for (;;)
  146. {
  147. const auto finishing = done.load();
  148. const auto t0 = Clock::now();
  149. for (auto& t : list)
  150. for (;;)
  151. {
  152. float* out[] = { scratch.data(), scratch.data() + 8192 };
  153. const auto got = t->stream->pull (out, 8192);
  154. if (got <= 0)
  155. break;
  156. const float* in[] = { out[0], out[1] };
  157. const auto w0 = Clock::now();
  158. t->writer.write (in, got);
  159. const auto w = ms (Clock::now() - w0);
  160. longestWrite = std::max (longestWrite, w);
  161. if (w > 1.0)
  162. writeMs.push_back (w);
  163. t->pulled.fetch_add (got);
  164. }
  165. if (stallMs > 0.0 && Clock::now() >= nextStall)
  166. {
  167. std::this_thread::sleep_for (std::chrono::duration<double, std::milli> (stallMs));
  168. nextStall += std::chrono::seconds (1);
  169. }
  170. busyMs += ms (Clock::now() - t0);
  171. if (finishing)
  172. break;
  173. std::this_thread::sleep_for (std::chrono::milliseconds (5)); // (the Drainer's 5 ms time slice)
  174. }
  175. });
  176. // audio thread (this one): paced blocks
  177. const auto blocks = (int) (seconds * rate / block);
  178. const auto period = std::chrono::duration<double> ((double) block / rate);
  179. InstructionCounter counter;
  180. long long instr = 0, worstInstr = 0;
  181. double worstPushUs = 0.0;
  182. const auto u0 = ThreadUsage::now();
  183. auto due = Clock::now();
  184. std::uint32_t seed = 1;
  185. double phase = 0.0;
  186. for (int b = 0; b < blocks; ++b)
  187. {
  188. std::this_thread::sleep_until (due);
  189. due += std::chrono::duration_cast<Clock::duration> (period);
  190. for (int i = 0; i < block; ++i)
  191. {
  192. seed = seed * 1664525u + 1013904223u;
  193. phase += 220.0 / rate;
  194. const auto v = (float) (0.3 * std::sin (6.283185307179586 * phase)) + (float) ((int) (seed >> 9) - (1 << 22)) * 1e-9f;
  195. for (auto& c : input)
  196. c[(std::size_t) i] = v;
  197. }
  198. const float* data[] = { input[0].data(), input[(std::size_t) (channels - 1)].data() };
  199. const auto p0 = Clock::now();
  200. counter.start();
  201. for (auto& t : list)
  202. t->stream->push (data, block);
  203. const auto n = counter.stop();
  204. worstPushUs = std::max (worstPushUs, 1000.0 * ms (Clock::now() - p0));
  205. instr += n;
  206. worstInstr = std::max (worstInstr, n);
  207. for (auto& t : list)
  208. t->maxHeld = std::max (t->maxHeld, t->stream->pushedFrames() - t->pulled.load (std::memory_order_relaxed));
  209. }
  210. const auto u1 = ThreadUsage::now();
  211. for (auto& t : list)
  212. t->stream->finish();
  213. done.store (true);
  214. recorder.join();
  215. std::int64_t lost = 0, held = 0, frames = 0;
  216. for (auto& t : list)
  217. {
  218. lost += t->stream->lostFrames();
  219. held = std::max (held, t->maxHeld);
  220. frames += t->writer.frames();
  221. t->writer.close();
  222. }
  223. std::sort (writeMs.begin(), writeMs.end());
  224. const auto audioMs = 1000.0 * blocks * block / rate;
  225. std::printf ("RESULT takes=%d rate=%d block=%d ch=%d sync=%.1fs stall=%.0fms | make %.1f ms | audio thread: %.1f instr/block/take, worst block %lld instr, "
  226. "worst push %.1f us, minor faults %ld, major %ld, ctx vol %ld invol %ld | recorder: busy %.2f %% of real time, longest write %.1f ms, "
  227. "writes > 1 ms: %zu (p50 %.1f, p95 %.1f) | ring: most held %lld frames (%.1f %% of %d) | lost %lld frames | written %lld of %lld\n",
  228. takes, rate, block, channels, syncSeconds, stallMs, makeMs, (double) instr / blocks / takes, worstInstr, worstPushUs, u1.minor - u0.minor,
  229. u1.major - u0.major, u1.voluntary - u0.voluntary, u1.involuntary - u0.involuntary, 100.0 * busyMs / audioMs, longestWrite, writeMs.size(),
  230. writeMs.empty() ? 0.0 : writeMs[writeMs.size() / 2], writeMs.empty() ? 0.0 : writeMs[std::min (writeMs.size() - 1, (std::size_t) (0.95 * writeMs.size()))],
  231. (long long) held, 100.0 * (double) held / capacity, capacity, (long long) lost, (long long) frames, (long long) blocks * block * takes);
  232. return 0;
  233. }