InputDrift.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. // LYNX ASIO — the input side of a full-duplex stream (REA round 106).
  2. //
  3. // The capture device delivers packets on its own clock; the host's blocks are paced by the playback device. Two
  4. // clocks never run at exactly the same speed (two devices, or Windows' own rate conversion), so a plain FIFO between
  5. // them slowly fills up or runs dry: every few seconds or minutes the input would click when it is trimmed or padded.
  6. //
  7. // InputDrift is that FIFO plus a small adaptive resampler: a PI controller watches the average fill level and
  8. // reads the FIFO slightly faster or slower (at most ±0.5 %, normally a few hundred ppm — far below audibility) so
  9. // the level stays at its target. The fractional reader is a 16-tap Kaiser-windowed sinc (flat to ~20 kHz at
  10. // 48 kHz). Only when the stream is really interrupted (a capture stall, a host that stopped calling) does it
  11. // resynchronise, which is counted.
  12. //
  13. // Plain C++ without Windows headers, so tests/tests.cpp checks it on Linux. Written from textbook DSP (windowed-sinc
  14. // interpolation, PI control); nothing here comes from another driver.
  15. #pragma once
  16. #include <algorithm>
  17. #include <cmath>
  18. #include <cstdint>
  19. #include <vector>
  20. namespace lynxasio
  21. {
  22. class InputDrift
  23. {
  24. public:
  25. static constexpr int taps = 16; // interpolation filter length (frames)
  26. static constexpr int half = taps / 2; // frames needed on each side of the read position
  27. static constexpr int phases = 256; // filter table resolution between two frames
  28. static constexpr double maxCorrection = 0.005;
  29. // `target`: the fill level (frames) the controller keeps; `rate`: frames per second (time constants).
  30. void reset (int numChannels, int target, double rate)
  31. {
  32. channels = std::max (1, numChannels);
  33. targetFill = initialTarget = std::max (half + 1, target);
  34. targetRaises = 0;
  35. sampleRate = rate > 0.0 ? rate : 48000.0;
  36. capacity = 1;
  37. while (capacity < 4 * targetFill + 16384)
  38. capacity <<= 1;
  39. ring.assign ((size_t) capacity * (size_t) channels, 0.0f);
  40. writeIndex = readIndex = 0;
  41. frac = 0.0;
  42. lastPushTime = -1.0;
  43. lastPacket = 0;
  44. integral = 0.0;
  45. ratioNow = 1.0;
  46. underflows = overflows = 0;
  47. minRatio = maxRatio = 1.0;
  48. buildTable();
  49. // the history before the first frame is silence, and the FIFO starts at its target level
  50. writeIndex = half + targetFill;
  51. readIndex = half;
  52. smoothedFill = targetFill;
  53. }
  54. int numChannels() const { return channels; }
  55. int target() const { return targetFill; }
  56. int raises() const { return targetRaises; } // how often an underflow raised the target (the latency changed)
  57. double fill() const { return (double) (writeIndex - readIndex) - frac; }
  58. double ratio() const { return ratioNow; }
  59. double averageFill() const { return smoothedFill; }
  60. // Captured frames (interleaved), `now` = when they arrived (seconds, any steady clock; < 0 = unknown).
  61. // On overflow the oldest frames are dropped (counted once per event).
  62. void push (const float* interleaved, int frames, double now = -1.0)
  63. {
  64. if (frames <= 0)
  65. return;
  66. if (now >= 0.0)
  67. {
  68. lastPushTime = now;
  69. lastPacket = frames;
  70. }
  71. // keep `half` frames of history behind the read position for the filter
  72. if (writeIndex + frames - (readIndex - half) > capacity)
  73. {
  74. ++overflows;
  75. resyncTo (std::max (0, targetFill - frames));
  76. }
  77. for (int i = 0; i < frames; ++i)
  78. {
  79. float* dst = &ring[(size_t) ((writeIndex + i) & (capacity - 1)) * (size_t) channels];
  80. if (interleaved != nullptr)
  81. std::copy (interleaved + (size_t) i * (size_t) channels, interleaved + (size_t) (i + 1) * (size_t) channels, dst);
  82. else
  83. std::fill (dst, dst + channels, 0.0f);
  84. }
  85. writeIndex += frames;
  86. if (fill() > (double) (4 * targetFill + 4096)) // the host stopped reading: come back to the target
  87. {
  88. ++overflows;
  89. resyncTo (targetFill);
  90. }
  91. }
  92. void pushSilence (int frames) { push (nullptr, frames, -1.0); }
  93. // `target` is the level left in the FIFO right after a host block, averaged over time.
  94. // One host block: `frames` interleaved frames at the playback clock. Returns false when the FIFO ran dry
  95. // (the block is still complete: the stream is resynchronised with silence first).
  96. bool pull (float* out, int frames, double now = -1.0)
  97. {
  98. bool ok = true;
  99. const double needed = frames * ratioNow + half + 2;
  100. if (fill() < needed)
  101. {
  102. ++underflows;
  103. ok = false;
  104. // The packets came later than the target allows for: keep a larger level from now on (at most twice
  105. // the initial target), so a device with irregular timing clicks once instead of again and again.
  106. const int raised = std::min (2 * initialTarget, targetFill + (int) std::ceil (needed - fill()) + 32);
  107. if (raised > targetFill)
  108. {
  109. targetFill = raised;
  110. ++targetRaises;
  111. }
  112. // pad with silence so that the target level is left after this block; the level jump is not drift
  113. pushSilence ((int) std::ceil (needed - fill()) + targetFill);
  114. smoothedFill = targetFill;
  115. }
  116. for (int i = 0; i < frames; ++i)
  117. {
  118. const double p = frac * phases;
  119. const int ph = std::min (phases - 1, (int) p);
  120. const float mix = (float) (p - ph);
  121. const float* h0 = &table[(size_t) ph * taps];
  122. const float* h1 = &table[(size_t) (ph + 1) * taps];
  123. float* dst = out + (size_t) i * (size_t) channels;
  124. std::fill (dst, dst + channels, 0.0f);
  125. for (int k = 0; k < taps; ++k)
  126. {
  127. const float h = h0[k] + mix * (h1[k] - h0[k]);
  128. const float* x = &ring[(size_t) ((readIndex - half + 1 + k) & (capacity - 1)) * (size_t) channels];
  129. for (int c = 0; c < channels; ++c)
  130. dst[c] += h * x[c];
  131. }
  132. frac += ratioNow;
  133. const auto whole = (std::int64_t) frac;
  134. readIndex += whole;
  135. frac -= (double) whole;
  136. }
  137. updateRatio (frames, now); // measured on what is left after the block, for the next one
  138. return ok;
  139. }
  140. // Moves the read position so that the level is the target now (once, when the stream has settled: devices
  141. // often deliver a burst of frames, or nothing, during their first periods). Call it between two blocks.
  142. void recenter (double now)
  143. {
  144. double level = fill();
  145. if (now >= 0.0 && lastPushTime >= 0.0)
  146. level += std::clamp ((now - lastPushTime) * sampleRate, 0.0, 4.0 * lastPacket);
  147. const auto shift = (std::int64_t) std::llround (level - targetFill);
  148. if (shift > 0)
  149. readIndex += std::min<std::int64_t> (shift, writeIndex - readIndex - half - 1);
  150. else if (shift < 0)
  151. pushSilence ((int) -shift); // rare: the device started late
  152. smoothedFill = targetFill;
  153. integral = 0.0;
  154. ratioNow = 1.0;
  155. }
  156. // statistics
  157. std::int64_t underflows = 0, overflows = 0;
  158. double minRatio = 1.0, maxRatio = 1.0;
  159. private:
  160. void resyncTo (int level)
  161. {
  162. // drop the oldest frames (or step back) so that exactly `level` frames remain unread
  163. readIndex = writeIndex - level;
  164. frac = 0.0;
  165. smoothedFill = level;
  166. integral = 0.0;
  167. }
  168. void updateRatio (int frames, double now)
  169. {
  170. // The level seen by a block depends on when the last capture packet came: just after one it is a packet
  171. // higher than just before the next. The device has been recording since that packet, so those frames are
  172. // counted too ("virtual fill"); otherwise the slow phase walk between the two clocks would look like a
  173. // level change. Averaged over ~0.5 s, then PI control: 1000 ppm of correction per 500 frames of error; the
  174. // integral term absorbs a constant clock difference.
  175. double level = fill();
  176. if (now >= 0.0 && lastPushTime >= 0.0)
  177. level += std::clamp ((now - lastPushTime) * sampleRate, 0.0, 4.0 * lastPacket);
  178. const double a = std::min (1.0, frames / (0.5 * sampleRate));
  179. smoothedFill += a * (level - smoothedFill);
  180. const double err = smoothedFill - targetFill;
  181. integral = std::clamp (integral + 2.0e-12 * err * frames, -maxCorrection, maxCorrection);
  182. ratioNow = 1.0 + std::clamp (2.0e-6 * err + integral, -maxCorrection, maxCorrection);
  183. minRatio = std::min (minRatio, ratioNow);
  184. maxRatio = std::max (maxRatio, ratioNow);
  185. }
  186. static double besselI0 (double x)
  187. {
  188. double sum = 1.0, term = 1.0;
  189. for (int k = 1; k < 30; ++k)
  190. {
  191. term *= (x / (2.0 * k)) * (x / (2.0 * k));
  192. sum += term;
  193. }
  194. return sum;
  195. }
  196. void buildTable()
  197. {
  198. // h(t) for t = k - half + 1 - phase/phases (distance from the read position), cutoff 0.92 x Nyquist,
  199. // Kaiser window (beta 8); each phase normalised to unity gain at DC. Row `phases` = the next frame's row 0.
  200. constexpr double pi = 3.14159265358979323846, cutoff = 0.92, beta = 8.0;
  201. table.assign ((size_t) (phases + 1) * taps, 0.0f);
  202. for (int ph = 0; ph <= phases; ++ph)
  203. {
  204. const double f = (double) ph / phases;
  205. double sum = 0.0;
  206. std::vector<double> row (taps);
  207. for (int k = 0; k < taps; ++k)
  208. {
  209. const double t = (double) (k - half + 1) - f;
  210. const double x = pi * cutoff * t;
  211. const double sinc = std::abs (x) < 1e-9 ? 1.0 : std::sin (x) / x;
  212. const double w = t / half;
  213. const double win = std::abs (w) >= 1.0 ? 0.0 : besselI0 (beta * std::sqrt (1.0 - w * w)) / besselI0 (beta);
  214. row[(size_t) k] = cutoff * sinc * win;
  215. sum += row[(size_t) k];
  216. }
  217. for (int k = 0; k < taps; ++k)
  218. table[(size_t) ph * taps + (size_t) k] = (float) (row[(size_t) k] / sum);
  219. }
  220. }
  221. int channels = 1, targetFill = 256, initialTarget = 256, targetRaises = 0, capacity = 1;
  222. double sampleRate = 48000.0;
  223. std::vector<float> ring, table;
  224. std::int64_t writeIndex = 0, readIndex = 0; // absolute frame counters
  225. double frac = 0.0, smoothedFill = 0.0, integral = 0.0, ratioNow = 1.0;
  226. double lastPushTime = -1.0;
  227. int lastPacket = 0;
  228. };
  229. } // namespace lynxasio