DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
TubePreamp.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
167#include "../Core/AudioBuffer.h"
168#include "../Core/AudioSpec.h"
169#include "../Core/Biquad.h"
170#include "../Core/CabinetModel.h"
171#include "../Core/DenormalGuard.h"
172#include "../Core/DspMath.h"
173#include "../Core/FIRFilter.h"
174#include "../Core/Oversampling.h"
175#include "../Core/SmoothedValue.h"
176#include "../Core/StateBlob.h"
177#include "../Core/WDF.h"
178
179#include <algorithm>
180#include <array>
181#include <atomic>
182#include <cmath>
183#include <cstddef>
184#include <cstdint>
185#include <limits>
186#include <memory>
187#include <numbers>
188#include <span>
189#include <utility>
190#include <vector>
191
192namespace dspark {
193
195namespace detail {
196 struct TubePreampGridClamp
197 {
199 static double value(double v) noexcept
200 {
201 if (v <= 0.0) return v;
202 if (v >= 13.0) return 0.7; // 0.7*(1 - 2e^-37) rounds to 0.7
203 const double e = std::expm1(v * (-2.0 / 0.7));
204 return -0.7 * e / (2.0 + e);
205 }
206 };
207
222 struct TubePreampGridConduction
223 {
224 static constexpr double kGg = 6.177e-4, kXi = 1.314, kCg = 9.901;
225 static constexpr double kRs = 68e3;
226 static constexpr double kCc = 22e-9;
227 static constexpr double kRg = 1e6;
228
230 static double current(double v, double& slope) noexcept
231 {
232 const double z = kCg * v;
233 double sp = 0.0, sig = 0.0; // softplus(z), logistic(z)
234 if (z > 30.0) { sp = z; sig = 1.0; }
235 else if (z < -30.0) { sp = std::exp(z); sig = sp; }
236 else
237 {
238 const double e = std::exp(z);
239 sp = std::log1p(e);
240 sig = e / (1.0 + e);
241 }
242 const double base = sp / kCg;
243 const double pm1 = std::pow(base, kXi - 1.0);
244 slope = kGg * kXi * pm1 * sig;
245 return kGg * pm1 * base;
246 }
247
250 static double solve(double d, double rs = kRs) noexcept
251 {
252 if (!std::isfinite(d)) return 0.0;
253 double slope = 0.0;
254 double lo = d - rs * current(d, slope), hi = d;
255 double w = d > 0.0 ? std::min(hi, std::max(lo, std::pow(d / (rs * kGg), 1.0 / kXi)))
256 : d;
257 for (int it = 0; it < 100; ++it)
258 {
259 const double f = w + rs * current(w, slope) - d;
260 if (f > 0.0) hi = w;
261 else lo = w;
262 const double next = w - f / (1.0 + rs * slope);
263 const double step = next > lo && next < hi ? next : 0.5 * (lo + hi);
264 if (std::abs(step - w) <= 1e-15 * std::max(1.0, std::abs(w)) || hi - lo <= 1e-15)
265 {
266 w = step;
267 break;
268 }
269 w = step;
270 }
271 return w;
272 }
273 };
274
283 struct TubePreampGridTable
284 {
285 static constexpr double kLo = -1.5, kMid = 8.0, kHi = 72.0;
286 static constexpr int kFine = 64, kCoarse = 8;
287 static constexpr int kFineCells = static_cast<int>((kMid - kLo) * kFine);
288 static constexpr int kCells = kFineCells + static_cast<int>((kHi - kMid) * kCoarse);
290 struct Cell { double a3, a2, a1, a0; };
291 std::vector<Cell> cells;
292 double rs = TubePreampGridConduction::kRs;
293
294 explicit TubePreampGridTable(double sourceResistance = TubePreampGridConduction::kRs)
295 : cells(static_cast<size_t>(kCells)), rs(sourceResistance)
296 {
297 std::vector<double> w(static_cast<size_t>(kCells + 1)), dw(static_cast<size_t>(kCells + 1));
298 for (int i = 0; i <= kCells; ++i)
299 {
300 const double d = i <= kFineCells ? kLo + double(i) / kFine
301 : kMid + double(i - kFineCells) / kCoarse;
302 const double root = TubePreampGridConduction::solve(d, rs);
303 double slope = 0.0;
304 (void)TubePreampGridConduction::current(root, slope);
305 w[static_cast<size_t>(i)] = root;
306 dw[static_cast<size_t>(i)] = 1.0 / (1.0 + rs * slope);
307 }
308 // Each cell's Hermite cubic through the node values and slopes,
309 // in the monomial form eval() reads with one load.
310 for (int i = 0; i < kCells; ++i)
311 {
312 const double h = i < kFineCells ? 1.0 / kFine : 1.0 / kCoarse;
313 const double w0 = w[static_cast<size_t>(i)], w1 = w[static_cast<size_t>(i + 1)];
314 const double m0 = h * dw[static_cast<size_t>(i)], m1 = h * dw[static_cast<size_t>(i + 1)];
315 const double diff = w1 - w0;
316 cells[static_cast<size_t>(i)] = {m0 + m1 - 2.0 * diff, 3.0 * diff - 2.0 * m0 - m1, m0, w0};
317 }
318 }
319
321 [[nodiscard]] double eval(double d) const noexcept
322 {
323 if (d <= kLo) return d;
324 if (!(d < kHi)) return TubePreampGridConduction::solve(d, rs);
325 const double pos = d < kMid ? (d - kLo) * kFine : kFineCells + (d - kMid) * kCoarse;
326 const int i = std::min(static_cast<int>(pos), kCells - 1);
327 const double t = pos - i;
328 const Cell& c = cells[static_cast<size_t>(i)];
329 return ((c.a3 * t + c.a2) * t + c.a1) * t + c.a0;
330 }
331 };
332
333 struct TubePreampCurrentTable
334 {
335 static constexpr double kMu = 100.0, kEx = 1.4, kKg1 = 1060.0;
336 static constexpr double kKp = 600.0, kKvb = 300.0;
337 static constexpr double kRL = 100e3, kRk = 1.5e3, kCk = 22e-6;
338
340 static void koren(double vpk, double vgk, double& ip,
341 double& dIpdVpk, double& dIpdVgk) noexcept
342 {
343 vpk = std::max(vpk, 0.0);
344 const double s = std::sqrt(kKvb + vpk * vpk);
345 const double u = kKp * (1.0 / kMu + vgk / s);
346
347 double sp = 0.0, sig = 0.0; // softplus(u), logistic(u)
348 if (u > 30.0) { sp = u; sig = 1.0; }
349 else if (u < -30.0) { sp = std::exp(u); sig = sp; }
350 else
351 {
352 const double eu = std::exp(u);
353 sp = std::log1p(eu);
354 sig = eu / (1.0 + eu);
355 }
356
357 const double e1 = (vpk / kKp) * sp;
358 if (e1 <= 0.0)
359 {
360 ip = 0.0;
361 dIpdVpk = 0.0;
362 dIpdVgk = 0.0;
363 return;
364 }
365 const double e1ex1 = std::pow(e1, kEx - 1.0);
366 ip = 2.0 * e1ex1 * e1 / kKg1;
367 const double dIpdE1 = 2.0 * kEx * e1ex1 / kKg1;
368
369 const double dUdVpk = -kKp * vgk * vpk / (s * s * s);
370 const double dE1dVpk = sp / kKp + (vpk / kKp) * sig * dUdVpk;
371 const double dE1dVgk = vpk * sig / s;
372 dIpdVpk = dIpdE1 * dE1dVpk;
373 dIpdVgk = dIpdE1 * dE1dVgk;
374 }
375
379 static double gridForCurrent(double plate, double current) noexcept
380 {
381 const double e1 = std::pow(current * kKg1 * 0.5, 1.0 / kEx);
382 const double z = e1 * kKp / plate;
383 const double u = z > 50.0 ? z : std::log(std::expm1(z));
384 return std::sqrt(kKvb + plate * plate) * (u / kKp - 1.0 / kMu);
385 }
386
387 // With S = B+ - A and G = Vgrid - A, the trapezoidal cathode
388 // equation Vk = A + B*Ip leaves a TWO-dimensional implicit load line:
389 // Ip = Koren(S - (RL+B)*Ip, G - B*Ip). B is fixed by the rate given
390 // to the constructor: the 1x point circuit passes its sample rate,
391 // the continuous core passes infinity (B = 0) and freezes A per
392 // interval. Use R = G/S to align the cutoff knee across supply
393 // voltages. The 156672-byte table has <5e-10 A error in the
394 // independent load-line check. Bicubic Hermite interpolation keeps
395 // current and both first derivatives continuous at cell edges.
396 // Every channel and both calibration passes share this instance.
397 struct Node
398 {
399 double y, ds, dg, dsg;
400 };
401 static constexpr int kNS = 18, kNG = 272;
402 std::array<Node, kNS * kNG> nodes;
403 double kb;
404
405 explicit TubePreampCurrentTable(double rate)
406 : kb((0.5 / (rate * kCk)) / (1.0 + 0.5 / (rate * kCk * kRk)))
407 {
408 for (int si = 0; si < kNS; ++si)
409 for (int gi = 0; gi < kNG; ++gi)
410 {
411 const double s = si <= 6 ? 80.0 + 8.0 * si
412 : 128.0 + 16.0 * (si - 6);
413 // Tail cells must still resolve the exponential enough
414 // to keep the cubic nonnegative.
415 const double r = gi <= 16 ? -0.08 + gi * 0.0025
416 : (gi <= 31 ? -0.04 + (gi - 16) * 0.001
417 : -0.025 + (gi - 31) / 6400.0);
418 Node n = solve(s, s * r);
419 n.ds += r * n.dg; // dI/dS with R held fixed
420 n.dg *= s; // dI/dR with S held fixed
421 // Differentiate the implicit dI/dR, not sampled currents;
422 // 0.001 V is much smaller than the 8/16 V supply cells.
423 n.dsg = ((s + 0.001) * solve(s + 0.001, (s + 0.001) * r).dg
424 - (s - 0.001) * solve(s - 0.001, (s - 0.001) * r).dg) / 0.002;
425 nodes[static_cast<size_t>(si * kNG + gi)] = n;
426 }
427 }
428
429 [[nodiscard]] Node solve(double supply, double grid) const noexcept
430 {
431 // Positive current is bounded by the plate load. Safeguard Newton
432 // with that bracket: setup converges faster than pure bisection
433 // without accepting a root on an unphysical branch.
434 double low = 0.0, high = supply / (kRL + kb);
435 double y = 0.5 * high, p = 0.0, dp = 0.0, dg = 0.0;
436 for (int k = 0; k < 60; ++k)
437 {
438 koren(supply - (kRL + kb) * y, grid - kb * y, p, dp, dg);
439 const double f = y - p;
440 // An absolute 1e-15 A stop leaves arbitrary residuals in
441 // cutoff nodes whose true current is much smaller. Those
442 // inconsistent values/slopes can make their cubic negative.
443 if (std::abs(f) <= std::max(1e-30, 1e-13 * std::max(y, p))) break;
444 if (f > 0.0) high = y;
445 else low = y;
446 const double slope = 1.0 + (kRL + kb) * dp + kb * dg;
447 const double next = y - f / slope;
448 y = next >= low && next <= high ? next : 0.5 * (low + high);
449 }
450 koren(supply - (kRL + kb) * y, grid - kb * y, p, dp, dg);
451 const double den = 1.0 + (kRL + kb) * dp + kb * dg;
452 return {y, dp / den, dg / den, 0.0};
453 }
454
455 static double cubic(double a, double b, double da, double db, double t) noexcept
456 {
457 const double diff = b - a;
458 return (((da + db - 2.0 * diff) * t + (3.0 * diff - 2.0 * da - db)) * t + da) * t + a;
459 }
460
461 [[nodiscard]] bool covers(double s, double g) const noexcept
462 {
463 return s >= 80.0 && s < 304.0 && std::isfinite(g) && g < 1.0;
464 }
465
466 [[nodiscard]] double eval(double s, double g) const noexcept
467 {
468 // Below this cutoff the unloaded Koren current is < 1e-27 A.
469 if (g <= -0.08 * s) return 0.0;
470 const double step = s < 128.0 ? 8.0 : 16.0;
471 const double r = g / s;
472 const double rstep = r < -0.04 ? 0.0025 : (r < -0.025 ? 0.001 : 1.0 / 6400.0);
473 const double sp = s < 128.0 ? (s - 80.0) / 8.0 : 6.0 + (s - 128.0) / 16.0;
474 const double gp = r < -0.04 ? (r + 0.08) * 400.0
475 : (r < -0.025 ? 16.0 + (r + 0.04) * 1000.0
476 : 31.0 + (r + 0.025) * 6400.0);
477 // Adding the grid offset can round a value just below the upper
478 // edge onto that edge. Use the final CELL, with t = 1, there.
479 const int si = std::min(static_cast<int>(sp), kNS - 2);
480 const int gi = std::min(static_cast<int>(gp), kNG - 2);
481 const double st = sp - si, gt = gp - gi;
482 const Node& a = nodes[static_cast<size_t>(si * kNG + gi)];
483 const Node& b = nodes[static_cast<size_t>((si + 1) * kNG + gi)];
484 const Node& c = nodes[static_cast<size_t>(si * kNG + gi + 1)];
485 const Node& d = nodes[static_cast<size_t>((si + 1) * kNG + gi + 1)];
486 const double p0 = cubic(a.y, b.y, a.ds * step, b.ds * step, st);
487 const double p1 = cubic(c.y, d.y, c.ds * step, d.ds * step, st);
488 const double m0 = rstep * cubic(a.dg, b.dg, a.dsg * step, b.dsg * step, st);
489 const double m1 = rstep * cubic(c.dg, d.dg, c.dsg * step, d.dsg * step, st);
490 return std::max(0.0, cubic(p0, p1, m0, m1, gt));
491 }
492
496 struct Slice
497 {
498 const Node* row0 = nullptr;
499 const Node* row1 = nullptr;
500 double s = 0.0, invS = 0.0, cut = 0.0;
501 double h00 = 0.0, h01 = 0.0, h10 = 0.0, h11 = 0.0;
502 bool inside = false;
503
504 void set(const TubePreampCurrentTable& table, double supply) noexcept
505 {
506 s = supply;
507 inside = supply >= 80.0 && supply < 304.0;
508 if (!inside) return;
509 invS = 1.0 / supply;
510 cut = -0.08 * supply;
511 const double step = supply < 128.0 ? 8.0 : 16.0;
512 const double sp = supply < 128.0 ? (supply - 80.0) / 8.0
513 : 6.0 + (supply - 128.0) / 16.0;
514 const int si = std::min(static_cast<int>(sp), kNS - 2);
515 const double t = sp - si;
516 h00 = (2.0 * t - 3.0) * t * t + 1.0;
517 h01 = (3.0 - 2.0 * t) * t * t;
518 h10 = step * ((t - 2.0) * t + 1.0) * t;
519 h11 = step * (t - 1.0) * t * t;
520 row0 = table.nodes.data() + si * kNG;
521 row1 = row0 + kNG;
522 }
523
525 [[nodiscard]] double eval(double g) const noexcept
526 {
527 if (g <= cut) return 0.0;
528 const double r = g * invS;
529 double gp, rstep;
530 if (r < -0.04) { gp = (r + 0.08) * 400.0; rstep = 0.0025; }
531 else if (r < -0.025) { gp = 16.0 + (r + 0.04) * 1000.0; rstep = 0.001; }
532 else { gp = 31.0 + (r + 0.025) * 6400.0; rstep = 1.0 / 6400.0; }
533 const int gi = std::min(static_cast<int>(gp), kNG - 2);
534 const double gt = gp - gi;
535 const Node& a = row0[gi];
536 const Node& c = row0[gi + 1];
537 const Node& b = row1[gi];
538 const Node& d = row1[gi + 1];
539 const double p0 = h00 * a.y + h01 * b.y + h10 * a.ds + h11 * b.ds;
540 const double p1 = h00 * c.y + h01 * d.y + h10 * c.ds + h11 * d.ds;
541 const double m0 = rstep * (h00 * a.dg + h01 * b.dg + h10 * a.dsg + h11 * b.dsg);
542 const double m1 = rstep * (h00 * c.dg + h01 * d.dg + h10 * c.dsg + h11 * d.dsg);
543 const double diff = p1 - p0;
544 const double v = (((m0 + m1 - 2.0 * diff) * gt + (3.0 * diff - 2.0 * m0 - m1)) * gt
545 + m0) * gt + p0;
546 return v > 0.0 ? v : 0.0;
547 }
548 };
549 };
550
552 struct TubePreampCoreDesign
553 {
554 static constexpr int kKernelOrder = 6;
555 int taps = 0;
556 int degree = 0;
557 const double* farrow = nullptr;
559 std::array<std::array<double, kKernelOrder>, kKernelOrder> kernel {};
560 std::vector<double> compensation;
561 int latency = 0;
562 int osFactor = 2;
563
564 explicit TubePreampCoreDesign(int factor) : osFactor(factor)
565 {
566 // Least-squares Farrow fits over 0..22 kHz at 48 kHz (scaled with
567 // the base rate), interpolating the two interval samples. Max
568 // error vs the ideal band-limited interpolant: -82.8 dB (2x),
569 // -104.2 dB (4x), -108.2 dB (8x), -104.6 dB (16x). The droop
570 // compensation inverts sinc(f)^6 over the same band to better
571 // than 2e-6 dB.
572 static constexpr std::array<double, 100> kFarrow2 = {
573 4.2321905086886495e-10, 0.0059466381516058153, -0.002278523941500805,
574 -0.0054952548957599556, -0.014968825413515578, 0.054109227099701757,
575 -0.078269013079604377, 0.062385435811858708, -0.025290994449854602,
576 0.0038613094605228345, -2.2707239900454428e-09, -0.04509673531374573,
577 0.02130560198974633, 0.044927139987920424, 0.068139628956554815,
578 -0.29034355992063943, 0.41888697256651169, -0.33093026606533477,
579 0.13329150667830314, -0.020180282199047366, 6.3151437033992178e-09,
580 0.19516443759783259, -0.125629932201473, -0.18510777189666724,
581 -0.11518179249706405, 0.79144728674092368, -1.1628931982523558,
582 0.91250354516673049, -0.36515236023089487, 0.0548497671327925,
583 -1.1679462053512646e-08, -0.73810415625364523, 0.8470174584244009,
584 0.17008113400299396, 0.090159156301663379, -1.4018192300222059,
585 2.141392397438906, -1.6757774481811469, 0.66635226461915309,
586 -0.099301542452499336, 1.0000000156560307, -0.15092152990607394,
587 -1.4813400355254824, 0.32501007016593614, -0.10665904644708368,
588 1.7796410825385522, -2.8452200456412218, 2.2313784198552291,
589 -0.8823072013373332, 0.13041824116835923, -1.5700830890361179e-08,
590 1.0030991668852851, 0.84865934877928584, -0.74002126985840833,
591 0.25444017376234029, -1.7071024411426592, 2.8159173504397854,
592 -2.2212010942574856, 0.87438979546714801, -0.12818098509269454,
593 1.1781332260547313e-08, -0.37253030413198274, -0.12785657025701674,
594 0.56505142242672013, -0.33848444021117219, 1.2561039702068575,
595 -2.0800938843434165, 1.6517199081920575, -0.64812744525532984,
596 0.094217309828563259, -6.4097566291092411e-09, 0.13220572975363162,
597 0.022984358585025653, -0.23015119647358298, 0.23722601584356839,
598 -0.68523256280710365, 1.1138842977913868, -0.88863883259602172,
599 0.3478529827090574, -0.050130774674655959, 2.3207754129408065e-09,
600 -0.034616695799025515, -0.0030424597428906587, 0.06570936592805314,
601 -0.092489611102646821, 0.25062568572871546, -0.39729342975322812,
602 0.31732189085987816, -0.12390188239748591, 0.017687129761438363,
603 -4.3623536317367461e-10, 0.0049101708741372896, 0.00017308418349044246,
604 -0.010091070767974901, 0.017824294982185494, -0.04733411530281835,
605 0.073532096156291082, -0.058588400350969086, 0.022788475313836876,
606 -0.0032145338738844057
607 };
608 static constexpr std::array<double, 8> kComp2 = {
609 2.71867910879388, -1.2024111681479335, 0.46738582076148377,
610 -0.16331116573163179, 0.048832017855856398, -0.011604018931486495,
611 0.0019406397776269202, -0.00017174220997273029
612 };
613 static constexpr std::array<double, 64> kFarrow4 = {
614 -1.2900536553478881e-06, -0.0080151506262985533, -0.17777590204833338,
615 1.3139119710287313, -4.0413832196153869, 6.3642884759250222,
616 -4.992867908276553, 1.5418432994555842, 7.9871493323757734e-06,
617 0.088046779796333074, 1.0604467092541447, -8.1687752563172111,
618 25.099313210118467, -39.488286729375986, 30.975170253454831,
619 -9.5659246558470752, -2.2105953216776039e-05, -0.55815096062851943,
620 -2.3938696401524284, 22.40917634184877, -69.6019865941457,
621 109.51192256668676, -85.894556644533552, 26.527491731519852,
622 1.0000353884966167, -0.33265191629960283, 3.674166593014272,
623 -35.4328783727806, 111.52063276854375, -175.64384089126642,
624 137.76206099998669, -42.547532060929456, -3.5359293796327108e-05,
625 1.098889851519979, -4.2836042287146743, 35.135653508220415,
626 -111.44779322067839, 175.80749233768327, -137.90312082065205,
627 42.592525392586815, 2.205090483678061e-05, -0.37161767694349446,
628 3.0655130552579171, -21.923092860130158, 69.500034073335797,
629 -109.8183373403734, 86.15979318327652, -26.612319122360798,
630 -7.9535630817034395e-06, 0.095783904254697808, -1.1276037484567922,
631 7.9530205187897351, -25.075497255063709, 39.67283956818612,
632 -31.136230566192772, 9.6176971986688393, 1.2822935194890068e-06,
633 -0.012285737644740915, 0.18272380080694042, -1.2870126749889277,
634 4.0467156665242037, -6.4061717578660602, 5.0298415014987468,
635 -1.5538123482944795
636 };
637 static constexpr std::array<double, 7> kComp4 = {
638 0.77932253944179963, 0.48450011964418033, -0.63543552895607291,
639 0.36687547570613865, -0.13057476517676106, 0.027680644656114826,
640 -0.0027072253534879587
641 };
642 static constexpr std::array<double, 36> kFarrow8 = {
643 2.1428912092597181e-06, -0.068053152547346507, 0.82615315111595389,
644 -2.25344764450442, 2.3863455617383647, -0.89100287142393453,
645 -1.0400687109947751e-05, 0.076025067275552194, -3.5474940938342541,
646 10.692630341379365, -11.548180887960177, 4.3270436164777122,
647 1.0000204893461682, -1.474312011333621, 7.0561524197541718,
648 -20.727998495189027, 22.674059266177732, -8.5279485269151927,
649 -2.0475134054884214e-05, 2.1464836357794721, -7.6380358894712534,
650 20.54461472771839, -22.577478060052183, 8.5244628827979447,
651 1.0378974319923476e-05, -0.83433580274857921, 4.1702488442657986,
652 -10.417228839352022, 11.403009710027204, -4.3217178780150958,
653 -2.1353801282180795e-06, 0.15419278048117258, -0.8670223096885199,
654 2.1614225669978211, -2.3377483222244333, 0.88916021323615935
655 };
656 static constexpr std::array<double, 4> kComp8 = {
657 2.0670375203804419, -0.6482179311307088, 0.12681513715972098,
658 -0.012115968043045313
659 };
660 static constexpr std::array<double, 16> kFarrow16 = {
661 -4.7274945894591747e-08, -0.33475471468652312, 0.50168301501965318,
662 -0.16692822036410673, 1.0000001518786812, -0.49831699527905698,
663 -1.0024720850935107, 0.50078884218257014, -1.6291311300334343e-07,
664 1.0008871433692914, 0.4999030230846026, -0.50078992841108072,
665 5.8345140851491506e-08, -0.16782377216653666, 0.00089437399553421448,
666 0.16692931835075694
667 };
668 static constexpr std::array<double, 4> kComp16 = {
669 2.2958105734077243, -0.82005508291669238, 0.19585990127822545,
670 -0.023710110331518937
671 };
672 switch (factor)
673 {
674 case 2: taps = 10; farrow = kFarrow2.data(); setCompensation(kComp2, 0); break;
675 case 4: taps = 8; farrow = kFarrow4.data(); setCompensation(kComp4, 0); break;
676 case 8: taps = 6; farrow = kFarrow8.data(); setCompensation(kComp8, 0); break;
677 default: taps = 4; farrow = kFarrow16.data(); setCompensation(kComp16, 9); break;
678 }
679 degree = taps - 1;
680 // Interval n is processed when x[n + taps/2] arrives; its output
681 // moments complete z[n - 2]; the FIR centre adds its half length.
682 const int delay = taps / 2 + 2 + compensationHalf_ + padding_;
683 latency = delay / factor;
684 // Order-6 B-spline: B(u) = sum_j (-1)^j C(6,j) (u + 3 - j)_+^5 / 120.
685 // For output m = n + k and tau = 1/2 + d, u = k - 1/2 - d; every
686 // truncated power keeps one sign over the interval, so each piece
687 // is an exact polynomial in d.
688 constexpr double binom6[7] = {1, 6, 15, 20, 15, 6, 1};
689 constexpr double binom5[6] = {1, 5, 10, 10, 5, 1};
690 for (int ko = 0; ko < kKernelOrder; ++ko)
691 {
692 const int k = ko - 2;
693 for (int j = 0; j <= 6; ++j)
694 {
695 const double c = k + 2.5 - j;
696 if (c <= 0.0) continue;
697 const double sign = (j & 1) ? -1.0 : 1.0;
698 for (int p = 0; p <= 5; ++p)
699 {
700 const double term = sign * binom6[j] * binom5[p] * std::pow(c, 5 - p)
701 * ((p & 1) ? -1.0 : 1.0) / 120.0;
702 kernel[static_cast<size_t>(ko)][static_cast<size_t>(p)] += term;
703 }
704 }
705 }
706 }
707
708 private:
709 int padding_ = 0, compensationHalf_ = 0;
710
711 template <size_t N>
712 void setCompensation(const std::array<double, N>& half, int padding)
713 {
714 // half[0] is the centre tap; mirror, then delay by `padding`.
715 const int h = static_cast<int>(N) - 1;
716 padding_ = padding;
717 compensationHalf_ = h;
718 compensation.assign(static_cast<size_t>(2 * h + 1 + padding), 0.0);
719 for (int q = 0; q <= h; ++q)
720 {
721 compensation[static_cast<size_t>(padding + h + q)] = half[static_cast<size_t>(q)];
722 compensation[static_cast<size_t>(padding + h - q)] = half[static_cast<size_t>(q)];
723 }
724 }
725 };
726
730 inline void tubePreampPhi(double w, double* p) noexcept
731 {
732 const double aw = std::abs(w);
733 if (aw < 0.5)
734 {
735 static constexpr double inv[16] = {1.0, 1.0, 1.0 / 2, 1.0 / 6, 1.0 / 24, 1.0 / 120,
736 1.0 / 720, 1.0 / 5040, 1.0 / 40320, 1.0 / 362880, 1.0 / 3628800,
737 1.0 / 39916800, 1.0 / 479001600, 1.0 / 6227020800.0,
738 1.0 / 87178291200.0, 1.0 / 1307674368000.0};
739 const int n = aw < 1e-3 ? 3 : (aw < 0.02 ? 5 : (aw < 0.1 ? 7 : 10));
740 double v = inv[4 + n];
741 for (int j = n - 1; j >= 0; --j) v = v * w + inv[4 + j];
742 p[4] = v;
743 p[3] = w * v + inv[3];
744 p[2] = w * p[3] + inv[2];
745 p[1] = w * p[2] + 1.0;
746 p[0] = w * p[1] + 1.0;
747 }
748 else
749 {
750 p[0] = std::exp(w);
751 p[1] = (p[0] - 1.0) / w;
752 p[2] = (p[1] - 1.0) / w;
753 p[3] = (p[2] - 0.5) / w;
754 p[4] = (p[3] - 1.0 / 6.0) / w;
755 }
756 }
758 struct TubePreampToneModes
759 {
760 double lambda[3] {};
761 double unitPhi[3][5] {};
762 double beta[3] {};
763 double gamma[3] {};
764 double direct = 0.0;
765 double toModal[3][3] {};
766 double toPhysical[3][3] {};
767
768 void design(const wdf::ToneStackFMV<double>::AnalogStateSpace& ss,
769 double sampleRate) noexcept
770 {
771 // a = -C^-1 G with symmetric G: S = C^(1/2) a C^(-1/2) is symmetric.
772 double r[3], ri[3];
773 for (int i = 0; i < 3; ++i)
774 {
775 r[i] = std::sqrt(ss.capacitance[i]);
776 ri[i] = 1.0 / r[i];
777 }
778 double s[3][3], q[3][3] {};
779 for (int i = 0; i < 3; ++i)
780 for (int j = 0; j < 3; ++j)
781 s[i][j] = r[i] * ss.a[i][j] * ri[j];
782 for (int i = 0; i < 3; ++i)
783 for (int j = i + 1; j < 3; ++j)
784 s[i][j] = s[j][i] = 0.5 * (s[i][j] + s[j][i]);
785 for (int i = 0; i < 3; ++i) q[i][i] = 1.0;
786 // Cyclic Jacobi rotations; robust also for coincident eigenvalues.
787 for (int sweep = 0; sweep < 32; ++sweep)
788 {
789 double off = 0.0, norm = 0.0;
790 for (int i = 0; i < 3; ++i)
791 for (int j = 0; j < 3; ++j)
792 {
793 norm += s[i][j] * s[i][j];
794 if (i != j) off += s[i][j] * s[i][j];
795 }
796 if (off <= 1e-30 * norm) break;
797 for (int p = 0; p < 2; ++p)
798 for (int k = p + 1; k < 3; ++k)
799 {
800 if (s[p][k] == 0.0) continue;
801 const double theta = 0.5 * (s[k][k] - s[p][p]) / s[p][k];
802 const double t = (theta >= 0.0 ? 1.0 : -1.0)
803 / (std::abs(theta) + std::sqrt(theta * theta + 1.0));
804 const double c = 1.0 / std::sqrt(t * t + 1.0), sn = t * c;
805 for (int i = 0; i < 3; ++i)
806 {
807 const double sip = s[i][p], sik = s[i][k];
808 s[i][p] = c * sip - sn * sik;
809 s[i][k] = sn * sip + c * sik;
810 }
811 for (int i = 0; i < 3; ++i)
812 {
813 const double spi = s[p][i], ski = s[k][i];
814 s[p][i] = c * spi - sn * ski;
815 s[k][i] = sn * spi + c * ski;
816 }
817 for (int i = 0; i < 3; ++i)
818 {
819 const double qip = q[i][p], qik = q[i][k];
820 q[i][p] = c * qip - sn * qik;
821 q[i][k] = sn * qip + c * qik;
822 }
823 }
824 }
825 const double period = 1.0 / sampleRate;
826 for (int m = 0; m < 3; ++m)
827 {
828 lambda[m] = s[m][m] * period;
829 tubePreampPhi(lambda[m], unitPhi[m]);
830 double bm = 0.0, gm = 0.0;
831 for (int i = 0; i < 3; ++i)
832 {
833 toModal[m][i] = q[i][m] * r[i]; // Q^T C^(1/2)
834 toPhysical[i][m] = ri[i] * q[i][m]; // C^(-1/2) Q
835 bm += toModal[m][i] * ss.b[i];
836 gm += ss.c[i] * toPhysical[i][m];
837 }
838 beta[m] = bm * period;
839 gamma[m] = gm;
840 }
841 direct = ss.d;
842 }
843 };
844
845} // namespace detail
847
854template <FloatType T>
856{
857public:
858 // -- Lifecycle ---------------------------------------------------------------
859
864 void prepare(const AudioSpec& spec)
865 {
866 if (!spec.isValid()) return;
867 prepared_.store(false, std::memory_order_relaxed);
868 spec_ = spec;
869 sampleRate_ = spec.sampleRate;
870 mixMaxStep_ = static_cast<T>(1.0 / std::max(1.0, sampleRate_ * 0.02));
871 if (osAutomatic_)
872 osFactor_ = Oversampling<T>::factorForRate(spec.sampleRate, kAutomaticInternalRate);
873 // Internal processing rate = active oversampling factor x base rate
874 // (the factor is configurable; 1 = off, no resampling).
875 fs2_ = static_cast<double>(osFactor_) * sampleRate_;
876 numChannels_ = spec.numChannels;
877 maxBlock_ = std::max(spec.maxBlockSize, 1);
878 driveLogSmoother_.prepare(fs2_, 30.0);
879 for (auto& smoother : outputLogSmoothers_)
880 smoother.prepare(fs2_, 30.0);
882 stageBlend_.prepare(fs2_, 20.0);
883 for (auto& ramp : gainRamps_)
884 ramp.resize(static_cast<size_t>(maxBlock_) * static_cast<size_t>(osFactor_));
885 for (auto& scratch : compensationScratch_)
886 scratch.resize(static_cast<size_t>(maxBlock_) * static_cast<size_t>(osFactor_));
887 stageRamp_.resize(static_cast<size_t>(maxBlock_) * static_cast<size_t>(osFactor_));
888 sagRamp_.resize(static_cast<size_t>(maxBlock_) * static_cast<size_t>(osFactor_));
889 sagSmoother_.prepare(fs2_, 30.0);
890
891 if (osFactor_ > 1)
892 {
893 // From 4x the core leaves harmonics up to the internal Nyquist at
894 // close to their full level, so the preset's 80 dB is no longer
895 // enough to decimate them: every stage is made 100 dB deep.
896 oversampler_ = std::make_unique<Oversampling<T>>(
901 oversampler_->prepare(spec);
902 design_ = std::make_unique<detail::TubePreampCoreDesign>(osFactor_);
903 }
904 else
905 {
906 oversampler_.reset();
907 design_.reset();
908 }
909
910 // The continuous core freezes the cathode per interval (B = 0); the
911 // 1x point circuit keeps the trapezoidal cathode coupling.
912 loadTable_ = std::make_unique<LoadTable>(
913 design_ ? std::numeric_limits<double>::infinity() : fs2_);
914 if (gridModel_ == GridModel::Conduction)
915 {
916 // The 1x point circuit solves the coupling capacitor implicitly:
917 // its trapezoid adds a series resistance to the grid source.
918 const double rs = design_ ? Conduction::kRs : Conduction::kRs + couplingSeries(fs2_);
919 if (!gridTable_ || gridTable_->rs != rs)
920 gridTable_ = std::make_unique<detail::TubePreampGridTable>(rs);
921 }
922 else
923 gridTable_.reset();
924 for (auto& lane : channels_)
925 {
926 lane.clear();
927 lane.resize(static_cast<size_t>(numChannels_));
928 for (auto& ch : lane)
929 ch = std::make_unique<ChannelState>(fs2_, loadTable_.get(), design_.get(),
930 gridTable_.get());
931 }
932
933 latency_ = (oversampler_ ? oversampler_->getLatency() : 0) + (design_ ? design_->latency : 0);
934 // Behind minimum-phase filters the dry copy crosses the same filters
935 // (in phase at every frequency) and the ring adds only the core's delay.
936 dryThroughFilters_ = oversampler_ && osMode_ == OversamplingMode::MinimumPhase;
937 if (dryThroughFilters_) dryPath_.prepare(spec, *oversampler_);
938 dryScratch_.resize(numChannels_, maxBlock_);
939 dryDelay_ = latency_ - (dryThroughFilters_ ? oversampler_->getLatency() : 0);
940 drySize_ = 1;
941 while (drySize_ < latency_ + maxBlock_ + 1) drySize_ <<= 1;
942 dryRing_.assign(static_cast<size_t>(numChannels_),
943 std::vector<T>(static_cast<size_t>(drySize_), T(0)));
944 dryPos_ = 0;
945 cabinet_.prepare(sampleRate_, numChannels_);
946 cabScratch_.resize(numChannels_, maxBlock_);
947 cabStep_ = 1.0 / std::max(1.0, sampleRate_ * 0.02);
948
949 calibrateReference();
950
951 prepared_.store(true, std::memory_order_relaxed);
952 dirty_.store(true, std::memory_order_release);
953 reset();
954 }
955
957 void reset() noexcept
958 {
959 if (!prepared_.load(std::memory_order_relaxed)) return;
960 const double sagR = static_cast<double>(sag_.load(std::memory_order_relaxed)) * 40e3;
961 const int stages = stages_.load(std::memory_order_relaxed);
962 for (int st = 1; st <= 2; ++st)
963 for (auto& ch : channels_[static_cast<size_t>(st - 1)])
964 ch->reset(sagR, st);
965 numStagesActive_ = stages;
966 stageBlend_.reset(static_cast<double>(stages - 1));
967 stageWarmupRemaining_ = 0;
968 bothStagesActive_ = false;
969 for (auto& d : dryRing_)
970 std::fill(d.begin(), d.end(), T(0));
971 dryPos_ = 0;
972 dryPath_.reset();
973 if (oversampler_) oversampler_->reset();
974 // Seed the anti-zipper ramps at their targets: no fade-in on start.
975 gainsInitialized_ = false;
976 currentMix_ = mix_.load(std::memory_order_relaxed);
977 cabinet_.reset();
978 cabNow_ = cabinetOn_.load(std::memory_order_relaxed) ? 1.0 : 0.0;
979 }
980
989 void setCabinet(bool on) noexcept { cabinetOn_.store(on, std::memory_order_relaxed); }
990
992 [[nodiscard]] bool isCabinet() const noexcept { return cabinetOn_.load(std::memory_order_relaxed); }
993
995 [[nodiscard]] CabinetModel<T>& getCabinet() noexcept { return cabinet_; }
996
997 // -- Parameters (thread-safe) ---------------------------------------------------
998
1001 void setDrive(T db) noexcept
1002 {
1003 if (!std::isfinite(db)) return;
1004 driveDb_.store(std::clamp(db, T(-12), T(36)), std::memory_order_relaxed);
1005 dirty_.store(true, std::memory_order_release);
1006 }
1007
1009 void setTreble(T treble) noexcept
1010 {
1011 if (!std::isfinite(treble)) return;
1012 treble_.store(std::clamp(treble, T(0), T(1)), std::memory_order_relaxed);
1013 dirty_.store(true, std::memory_order_release);
1014 }
1015
1018 void setBass(T bass) noexcept
1019 {
1020 if (!std::isfinite(bass)) return;
1021 bass_.store(std::clamp(bass, T(0), T(1)), std::memory_order_relaxed);
1022 dirty_.store(true, std::memory_order_release);
1023 }
1024
1026 void setMiddle(T middle) noexcept
1027 {
1028 if (!std::isfinite(middle)) return;
1029 middle_.store(std::clamp(middle, T(0), T(1)), std::memory_order_relaxed);
1030 dirty_.store(true, std::memory_order_release);
1031 }
1032
1034 void setSag(T sag) noexcept
1035 {
1036 if (!std::isfinite(sag)) return;
1037 sag_.store(std::clamp(sag, T(0), T(1)), std::memory_order_relaxed);
1038 dirty_.store(true, std::memory_order_release);
1039 }
1040
1045 void setStages(int stages) noexcept
1046 {
1047 stages_.store(std::clamp(stages, 1, 2), std::memory_order_relaxed);
1048 dirty_.store(true, std::memory_order_release);
1049 }
1050
1064 void setOversampling(int factor)
1065 {
1066 if (factor < 1 || factor > 16 || (factor & (factor - 1)) != 0) return;
1067 if (factor == osFactor_ && !osAutomatic_) return;
1068 osAutomatic_ = false;
1069 osFactor_ = factor;
1070 // Rebuild the whole chain at the new internal rate if already prepared
1071 // (fs2_, oversampler, per-channel circuits and calibration all depend
1072 // on the factor). Same setup-thread cost as prepare().
1073 if (prepared_.load(std::memory_order_relaxed))
1074 prepare(spec_);
1075 }
1076
1091 {
1092 if (on == osAutomatic_) return;
1093 osAutomatic_ = on;
1094 if (on && prepared_.load(std::memory_order_relaxed))
1095 prepare(spec_);
1096 }
1097
1099 [[nodiscard]] bool isOversamplingAutomatic() const noexcept { return osAutomatic_; }
1100
1103 {
1104 LinearPhase,
1106 };
1107
1120 {
1121 mode = static_cast<OversamplingMode>(std::clamp(static_cast<int>(mode), 0, 1));
1122 if (mode == osMode_) return;
1123 osMode_ = mode;
1124 if (prepared_.load(std::memory_order_relaxed))
1125 prepare(spec_);
1126 }
1127
1129 [[nodiscard]] OversamplingMode getOversamplingMode() const noexcept { return osMode_; }
1130
1132 [[nodiscard]] int getOversamplingFactor() const noexcept { return osFactor_; }
1133
1154 enum class GridModel { Clamp, Conduction };
1155
1193 {
1194 const auto m = static_cast<GridModel>(std::clamp(static_cast<int>(model), 0, 1));
1195 if (m == gridModel_) return;
1196 gridModel_ = m;
1197 if (prepared_.load(std::memory_order_relaxed))
1198 prepare(spec_);
1199 }
1200
1202 [[nodiscard]] GridModel getGridModel() const noexcept { return gridModel_; }
1203
1205 void setOutput(T db) noexcept
1206 {
1207 if (!std::isfinite(db)) return;
1208 outputDb_.store(std::clamp(db, T(-24), T(12)), std::memory_order_relaxed);
1209 }
1210
1213 void setMix(T mix) noexcept
1214 {
1215 if (!std::isfinite(mix)) return;
1216 mix_.store(std::clamp(mix, T(0), T(1)), std::memory_order_relaxed);
1217 }
1218
1219 [[nodiscard]] T getDrive() const noexcept { return driveDb_.load(std::memory_order_relaxed); }
1220 [[nodiscard]] T getTreble() const noexcept { return treble_.load(std::memory_order_relaxed); }
1221 [[nodiscard]] T getBass() const noexcept { return bass_.load(std::memory_order_relaxed); }
1222 [[nodiscard]] T getMiddle() const noexcept { return middle_.load(std::memory_order_relaxed); }
1223 [[nodiscard]] T getSag() const noexcept { return sag_.load(std::memory_order_relaxed); }
1224 [[nodiscard]] int getStages() const noexcept { return stages_.load(std::memory_order_relaxed); }
1225 [[nodiscard]] T getOutput() const noexcept { return outputDb_.load(std::memory_order_relaxed); }
1226 [[nodiscard]] T getMix() const noexcept { return mix_.load(std::memory_order_relaxed); }
1227
1231 [[nodiscard]] int getLatency() const noexcept { return latency_; }
1232
1234 [[nodiscard]] int getLatencySamples() const noexcept { return getLatency(); }
1235
1238 [[nodiscard]] T getSupplyVoltage() const noexcept
1239 {
1240 return supplyNow_.load(std::memory_order_relaxed);
1241 }
1242
1244 [[nodiscard]] std::vector<uint8_t> getState() const
1245 {
1246 StateWriter w(stateId("TUBE"), 1);
1247 // Explicit float casts: the blob stores float, and with T = double the
1248 // unqualified write(key, double) would be ambiguous (float/int32/bool).
1249 w.write("drive", static_cast<float>(driveDb_.load(std::memory_order_relaxed)));
1250 w.write("treble", static_cast<float>(treble_.load(std::memory_order_relaxed)));
1251 w.write("bass", static_cast<float>(bass_.load(std::memory_order_relaxed)));
1252 w.write("middle", static_cast<float>(middle_.load(std::memory_order_relaxed)));
1253 w.write("sag", static_cast<float>(sag_.load(std::memory_order_relaxed)));
1254 w.write("stages", stages_.load(std::memory_order_relaxed));
1255 w.write("output", static_cast<float>(outputDb_.load(std::memory_order_relaxed)));
1256 w.write("mix", static_cast<float>(mix_.load(std::memory_order_relaxed)));
1257 w.write("oversampling", osFactor_);
1258 w.write("oversamplingAuto", osAutomatic_);
1259 w.write("oversamplingMode", static_cast<int32_t>(osMode_));
1260 w.write("gridModel", static_cast<int32_t>(gridModel_));
1261 w.write("cabinet", cabinetOn_.load(std::memory_order_relaxed));
1262 cabinet_.writeState(w, "cab.");
1263 return w.blob();
1264 }
1265
1267 bool setState(const uint8_t* data, size_t size)
1268 {
1269 StateReader r(data, size);
1270 if (!r.isValid() || r.processorId() != stateId("TUBE")) return false;
1271 setDrive(static_cast<T>(r.read("drive", 0.0f)));
1272 setTreble(static_cast<T>(r.read("treble", 0.5f)));
1273 setBass(static_cast<T>(r.read("bass", 0.5f)));
1274 setMiddle(static_cast<T>(r.read("middle", 0.5f)));
1275 setSag(static_cast<T>(r.read("sag", 0.3f)));
1276 setStages(r.read("stages", 1));
1277 setOutput(static_cast<T>(r.read("output", 0.0f)));
1278 setMix(static_cast<T>(r.read("mix", 1.0f)));
1279 setCabinet(r.read("cabinet", false));
1280 cabinet_.readState(r, "cab.");
1281 // The grid model takes effect with the (possibly changed) factor: one
1282 // rebuild, not two. Blobs without the key restore the Clamp model.
1283 const auto grid = static_cast<GridModel>(std::clamp(r.read("gridModel", 0), 0, 1));
1284 const bool regrid = grid != gridModel_;
1285 gridModel_ = grid;
1286 const int factorBefore = osFactor_;
1287 // Default 2 = the historical fixed factor, so blobs written before
1288 // it was configurable restore the 2x behaviour they were captured with.
1289 setOversampling(r.read("oversampling", 2));
1290 setAutomaticOversampling(r.read("oversamplingAuto", false));
1291 setOversamplingMode(static_cast<OversamplingMode>(r.read("oversamplingMode", 0)));
1292 if (regrid && osFactor_ == factorBefore && prepared_.load(std::memory_order_relaxed))
1293 prepare(spec_);
1294 return true;
1295 }
1296
1297 // -- Processing -------------------------------------------------------------------
1298
1300 void processBlock(AudioBufferView<T> buffer) noexcept
1301 {
1302 if (!prepared_.load(std::memory_order_relaxed)) return;
1303 DenormalGuard guard;
1304
1305 const int nCh = std::min(buffer.getNumChannels(), numChannels_);
1306 const int nS = buffer.getNumSamples();
1307 if (nCh == 0 || nS == 0) return;
1308
1309 // Front-door non-finite guard: a single NaN/Inf input sample would
1310 // poison the recursive circuit, tone-circuit, supply sag, output
1311 // DC-blocker and flatten-EQ state PERMANENTLY (only reset() clears
1312 // it, not clean input). Replace bad samples with silence before
1313 // they reach any state, so a transient upstream glitch cannot corrupt
1314 // the channel for the rest of the stream.
1315 for (int ch = 0; ch < nCh; ++ch)
1316 {
1317 T* d = buffer.getChannel(ch);
1318 for (int i = 0; i < nS; ++i)
1319 if (!std::isfinite(d[i])) d[i] = T(0);
1320 }
1321
1322 // Acquire pairs with the setters' release stores so the recompute
1323 // always sees the values published before the flag.
1324 if (dirty_.load(std::memory_order_relaxed)
1325 && dirty_.exchange(false, std::memory_order_acquire))
1326 recompute();
1327
1328 for (int off = 0; off < nS; off += maxBlock_)
1329 processChunk(buffer.getSubView(off, std::min(maxBlock_, nS - off)), nCh);
1330 }
1331
1332private:
1333 void processChunk(AudioBufferView<T> buffer, int nCh) noexcept
1334 {
1335 const int nS = buffer.getNumSamples();
1336 // Rate-limited mix ramp (moveTowards, exact landing; settled it
1337 // reduces to the constant, bit-identically).
1338 const T mixTarget = mix_.load(std::memory_order_relaxed);
1339 const T mixStart = currentMix_;
1340 const double trim = std::pow(10.0,
1341 static_cast<double>(outputDb_.load(std::memory_order_relaxed)) / 20.0);
1342 const std::array<double, 2> outGain { mScale_[0] * trim, mScale_[1] * trim };
1343
1344 // Dry snapshot (through the oversampler's filters when they are
1345 // minimum phase).
1346 if (dryThroughFilters_)
1347 {
1348 for (int ch = 0; ch < nCh; ++ch)
1349 std::copy_n(buffer.getChannel(ch), nS, dryScratch_.getChannel(ch));
1350 auto dryView = dryScratch_.toView().getSubView(0, nS);
1351 dryPath_.process(dryView);
1352 }
1353 for (int ch = 0; ch < nCh; ++ch)
1354 {
1355 const T* in = dryThroughFilters_ ? dryScratch_.getChannel(ch) : buffer.getChannel(ch);
1356 auto& dry = dryRing_[static_cast<size_t>(ch)];
1357 int dp = dryPos_;
1358 for (int i = 0; i < nS; ++i)
1359 {
1360 dry[static_cast<size_t>(dp)] = in[i];
1361 dp = (dp + 1) & (drySize_ - 1);
1362 }
1363 }
1364
1365 // Nonlinear circuit at the active oversampling factor (1x = process the
1366 // base-rate buffer in place, no resampling).
1367 {
1368 const bool osOn = (oversampler_ != nullptr);
1369 auto osView = osOn ? oversampler_->upsample(buffer) : buffer;
1370 const int osN = osView.getNumSamples();
1371
1372 // Smooth the compensation pair in logarithmic gain at the
1373 // internal sample clock. Interpolating between block endpoints
1374 // changes the trajectory when a host changes its block size.
1375 // Core's sample-exact one-pole retains the 30 ms time constant.
1376 const double driveLog = std::log(hScale_);
1377 if (!gainsInitialized_)
1378 {
1379 driveLogSmoother_.reset(driveLog);
1380 for (size_t st = 0; st < 2; ++st)
1381 outputLogSmoothers_[st].reset(std::log(outGain[st]));
1382 sagSmoother_.reset(sagR_);
1383 gainsInitialized_ = true;
1384 }
1385 driveLogSmoother_.setTargetValue(driveLog);
1386 const bool driveRamping = driveLogSmoother_.isSmoothing();
1387 if (driveRamping)
1388 {
1389 driveLogSmoother_.processBlock(
1390 std::span<double>(gainRamps_[0].data(), static_cast<size_t>(osN)));
1391 for (int i = 0; i < osN; ++i)
1392 {
1393 auto& value = gainRamps_[0][static_cast<size_t>(i)];
1394 value = value == driveLog ? hScale_ : std::exp(value);
1395 }
1396 }
1397 std::array<bool, 2> outputRamping {};
1398 for (size_t st = 0; st < 2; ++st)
1399 {
1400 const double outputLog = std::log(outGain[st]);
1401 auto& smoother = outputLogSmoothers_[st];
1402 smoother.setTargetValue(outputLog);
1403 outputRamping[st] = smoother.isSmoothing();
1404 if (!outputRamping[st]) continue;
1405 smoother.processBlock(
1406 std::span<double>(gainRamps_[st + 1].data(), static_cast<size_t>(osN)));
1407 for (int i = 0; i < osN; ++i)
1408 {
1409 auto& value = gainRamps_[st + 1][static_cast<size_t>(i)];
1410 value = value == outputLog ? outGain[st] : std::exp(value);
1411 }
1412 }
1413
1414 // Supply sag resistance, ramped like the gains: a step moved the
1415 // supply (and so the plate DC) at once and thumped (a 0.3 -> 1
1416 // sag change gave a 0.0975 step on a -20 dBFS tone).
1417 sagSmoother_.setTargetValue(sagR_);
1418 const bool sagRamping = sagSmoother_.isSmoothing();
1419 if (sagRamping)
1420 sagSmoother_.processBlock(
1421 std::span<double>(sagRamp_.data(), static_cast<size_t>(osN)));
1422
1423 // Advance the transition once per internal frame, shared by all
1424 // channels. The inactive circuit stops at the exact ramp endpoint,
1425 // even if the host's block extends beyond it.
1426 int transitionSamples = 0;
1427 while (bothStagesActive_ && transitionSamples < osN)
1428 {
1429 double w = stageBlend_.getCurrentValue();
1430 if (stageWarmupRemaining_ > 0) --stageWarmupRemaining_;
1431 else w = stageBlend_.getNextValue();
1432 stageRamp_[static_cast<size_t>(transitionSamples++)] = w * w * (3.0 - 2.0 * w);
1433 if (stageWarmupRemaining_ == 0 && !stageBlend_.isSmoothing())
1434 bothStagesActive_ = false;
1435 }
1436 const size_t target = static_cast<size_t>(numStagesActive_ - 1);
1437 for (int ch = 0; ch < nCh; ++ch)
1438 {
1439 T* d = osView.getChannel(ch);
1440 for (int i = 0; i < osN; ++i)
1441 {
1442 const double h = driveRamping ? gainRamps_[0][static_cast<size_t>(i)] : hScale_;
1443 const double x = h * static_cast<double>(d[i]);
1444 for (size_t st = 0; st < 2; ++st)
1445 {
1446 if (st != target && i >= transitionSamples) continue;
1447 compensationScratch_[st][static_cast<size_t>(i)] =
1448 channels_[st][static_cast<size_t>(ch)]->template processSample<false>(
1449 x, static_cast<int>(st) + 1,
1450 sagRamping ? sagRamp_[static_cast<size_t>(i)] : sagR_);
1451 }
1452 }
1453 if (osOn)
1454 {
1455 for (size_t st = 0; st < 2; ++st)
1456 {
1457 const int count = st == target ? osN : transitionSamples;
1458 if (count > 0)
1459 channels_[st][static_cast<size_t>(ch)]->compensateBlock(
1460 compensationScratch_[st].data(), count);
1461 }
1462 }
1463 for (int i = 0; i < osN; ++i)
1464 {
1465 const auto index = static_cast<size_t>(i);
1466 const double g = outputRamping[target] ? gainRamps_[target + 1][index] : outGain[target];
1467 double value = g * compensationScratch_[target][index];
1468 if (i < transitionSamples)
1469 {
1470 const size_t other = 1 - target;
1471 const double gOther = outputRamping[other] ? gainRamps_[other + 1][index] : outGain[other];
1472 const double alternate = gOther * compensationScratch_[other][index];
1473 const double w = target == 1 ? stageRamp_[index] : 1.0 - stageRamp_[index];
1474 value = alternate + w * (value - alternate);
1475 }
1476 d[i] = static_cast<T>(value);
1477 }
1478 }
1479 if (osOn) oversampler_->downsample(buffer);
1480 const double position = stageBlend_.getCurrentValue();
1481 const double w = position * position * (3.0 - 2.0 * position);
1482 const double current = (1.0 - w) * channels_[0][0]->supplyCurrent()
1483 + w * channels_[1][0]->supplyCurrent();
1484 supplyNow_.store(static_cast<T>(kBplus - sagSmoother_.getCurrentValue() * current),
1485 std::memory_order_relaxed);
1486 }
1487
1488 runCabinet(buffer, nCh, nS);
1489
1490 // Latency-compensated mix (ramped: a hard flip on the distorted wet
1491 // stream clicked at 1.6x the steady-state sample delta).
1492 for (int ch = 0; ch < nCh; ++ch)
1493 {
1494 T* d = buffer.getChannel(ch);
1495 const auto& dry = dryRing_[static_cast<size_t>(ch)];
1496 for (int i = 0; i < nS; ++i)
1497 {
1498 const int idx = (dryPos_ + i - dryDelay_) & (drySize_ - 1);
1499 const T drySample = dry[static_cast<size_t>(idx)];
1500 const T mixVal = moveTowards(mixStart, mixTarget, mixMaxStep_ * static_cast<T>(i + 1));
1501 d[i] = drySample + (d[i] - drySample) * mixVal;
1502 }
1503 }
1504 currentMix_ = moveTowards(mixStart, mixTarget, mixMaxStep_ * static_cast<T>(nS));
1505 dryPos_ = (dryPos_ + nS) & (drySize_ - 1);
1506 }
1507
1508 // -- Circuit constants (classic 12AX7 common-cathode stage) -------------------
1509 static constexpr double kBplus = 300.0;
1510 static constexpr double kRL = detail::TubePreampCurrentTable::kRL;
1511 static constexpr double kRk = detail::TubePreampCurrentTable::kRk;
1512 static constexpr double kCk = detail::TubePreampCurrentTable::kCk;
1513 static constexpr double kInterstage = 0.12;
1514
1515 using LoadTable = detail::TubePreampCurrentTable;
1516 using Clamp = detail::TubePreampGridClamp;
1517 using Conduction = detail::TubePreampGridConduction;
1518
1521 static double couplingSeries(double rate) noexcept
1522 {
1523 const double h = 0.5 / (rate * Conduction::kCc);
1524 return h / (1.0 + h / Conduction::kRg);
1525 }
1526
1527 static void koren(double vpk, double vgk, double& ip,
1528 double& dIpdVpk, double& dIpdVgk) noexcept
1529 {
1530 LoadTable::koren(vpk, vgk, ip, dIpdVpk, dIpdVgk);
1531 }
1532
1534 static double settleCurrent(double bplus, double grid = 0.0) noexcept
1535 {
1536 double i = 8e-4;
1537 for (int it = 0; it < 60; ++it)
1538 {
1539 const double vkS = i * kRk;
1540 const double vpk = bplus - i * kRL - vkS;
1541 double ipK = 0.0, dVpk = 0.0, dVgk = 0.0;
1542 koren(vpk, grid - vkS, ipK, dVpk, dVgk);
1543 const double f = i - ipK;
1544 const double fp = 1.0 - (dVpk * (-(kRL + kRk)) + dVgk * (-kRk));
1545 const double di = f / fp;
1546 i -= di;
1547 i = std::clamp(i, 0.0, bplus / (kRL + kRk));
1548 if (std::abs(di) < 1e-15) break;
1549 }
1550 return i;
1551 }
1552
1555 struct TriodeStage
1556 {
1557 const LoadTable* table = nullptr;
1558 const detail::TubePreampGridTable* grid = nullptr;
1559 double ig = 0.0;
1560 double vc = 0.0;
1561 double icPrev = 0.0;
1562 double fs2 = 96000.0;
1563 double ip = 8e-4;
1564 double vk = 1.2;
1565 double fPrev = 0.0;
1566 double vpDC = 200.0;
1567
1568 void settleDC(double bplus) noexcept
1569 {
1570 ip = settleCurrent(bplus);
1571 vk = ip * kRk;
1572 fPrev = 0.0;
1573 vpDC = bplus - ip * kRL;
1574 ig = 0.0;
1575 vc = 0.0;
1576 icPrev = 0.0;
1577 }
1578
1580 [[nodiscard]] double processSample(double vg, double bplusEff) noexcept
1581 {
1582 if (grid) return processConduction(vg, bplusEff);
1583 vg = Clamp::value(vg);
1584 // Trapezoidal cathode bypass: Ck dVk/dt = Ip - Vk/Rk, with fPrev
1585 // holding the previous NET CURRENT (Ip - Vk/Rk), so the update is
1586 // Vk_n = Vk_{n-1} + (T/2Ck)(I_n + I_{n-1}) = kA + kB * Ip_n.
1587 const double h2c = 0.5 / (fs2 * kCk);
1588 const double denom = 1.0 + h2c / kRk;
1589 const double kA = (vk + h2c * fPrev) / denom;
1590 const double kB = h2c / denom;
1591
1592 const double iMax = bplusEff / kRL + 1e-3;
1593 double i = std::clamp(ip, 0.0, iMax);
1594 // Outside the prepared supply/grid range, retain the analytic
1595 // circuit solve. The table includes a bounded deep-cutoff limit.
1596 if (table->covers(bplusEff - kA, vg - kA))
1597 i = table->eval(bplusEff - kA, vg - kA);
1598 else for (int it = 0; it < 8; ++it)
1599 {
1600 const double vkN = kA + kB * i;
1601 const double vpk = bplusEff - i * kRL - vkN;
1602 const double vgk = vg - vkN;
1603 double ipK = 0.0, dVpk = 0.0, dVgk = 0.0;
1604 koren(vpk, vgk, ipK, dVpk, dVgk);
1605
1606 const double f = i - ipK;
1607 const double fp = 1.0 - (dVpk * (-kRL - kB) + dVgk * (-kB));
1608 const double di = f / std::max(fp, 1e-6);
1609 i -= di;
1610 i = std::clamp(i, 0.0, iMax);
1611 if (std::abs(di) < 1e-12) break;
1612 }
1613
1614 const double vkN = kA + kB * i;
1615 fPrev = i - vkN / kRk; // net capacitor current for the trapezoid
1616 vk = vkN;
1617 ip = i;
1618 return (bplusEff - i * kRL) - vpDC; // AC component
1619 }
1620
1625 [[nodiscard]] double processConduction(double vs, double bplusEff) noexcept
1626 {
1627 const double h2c = 0.5 / (fs2 * kCk);
1628 const double denom = 1.0 + h2c / kRk;
1629 const double kA = (vk + h2c * fPrev) / denom;
1630 const double kB = h2c / denom;
1631 const double vkEst = kA + kB * (ip + ig);
1632 // Trapezoidal coupling capacitor: vc = cA + cB * Ig with the grid
1633 // leak current (vs - vc) / Rg; cB joins the grid source resistance
1634 // (the table is built for Rs + cB at this rate).
1635 const double hc = 0.5 / (fs2 * Conduction::kCc);
1636 const double cDen = 1.0 + hc / Conduction::kRg;
1637 const double cA = (vc + hc * (vs / Conduction::kRg + icPrev)) / cDen;
1638 const double drive = vs - cA - vkEst;
1639 const double w = grid->eval(drive);
1640 const double vg = vkEst + w;
1641 const double igN = (drive - w) / grid->rs;
1642 vc = cA + (hc / cDen) * igN;
1643 icPrev = (vs - vc) / Conduction::kRg + igN;
1644
1645 const double iMax = bplusEff / kRL + 1e-3;
1646 double i = std::clamp(ip, 0.0, iMax);
1647 // The table spans R = g / S up to 0.0125 (covers() keeps g < 1 V
1648 // for the clamp model, whose grid never gets that far).
1649 const double sC = bplusEff - kA, gC = vg - kA;
1650 if (sC >= 80.0 && sC < 304.0 && std::isfinite(gC) && gC < 0.0125 * sC)
1651 i = table->eval(sC, gC);
1652 else for (int it = 0; it < 8; ++it)
1653 {
1654 const double vkN = kA + kB * i;
1655 const double vpk = bplusEff - i * kRL - vkN;
1656 const double vgk = vg - vkN;
1657 double ipK = 0.0, dVpk = 0.0, dVgk = 0.0;
1658 koren(vpk, vgk, ipK, dVpk, dVgk);
1659 const double f = i - ipK;
1660 const double fp = 1.0 - (dVpk * (-kRL - kB) + dVgk * (-kB));
1661 const double di = f / std::max(fp, 1e-6);
1662 i -= di;
1663 i = std::clamp(i, 0.0, iMax);
1664 if (std::abs(di) < 1e-12) break;
1665 }
1666
1667 const double vkN = kA + kB * (i + igN);
1668 fPrev = i + igN - vkN / kRk;
1669 vk = vkN;
1670 ip = i;
1671 ig = igN;
1672 return (bplusEff - i * kRL) - vpDC;
1673 }
1674 };
1675
1681 struct ContinuousCore
1682 {
1686 static constexpr int kMaxLevels = 8;
1687 static constexpr int kMaxPieces = 48;
1688 static constexpr int kOrder = detail::TubePreampCoreDesign::kKernelOrder;
1689 static constexpr double kKneeRange = 1.0;
1690 static constexpr double kConductionKneeRange = 0.25;
1691 static constexpr double kSmallZ = 0.3, kStiffZ = 40.0;
1692 static constexpr double kLongPiece = 0.5;
1693 static constexpr double kShortPiece = 0.03;
1694 static constexpr double kMediumPiece = 0.1;
1698 static constexpr double kChargeFloor = -0.8;
1699
1700 const LoadTable* table = nullptr;
1701 const detail::TubePreampCoreDesign* design = nullptr;
1702 const detail::TubePreampGridTable* grid = nullptr;
1703 double period = 1.0 / 96000.0, cathodeDecay = 0.0, sagDecay = 0.0;
1704 double g1Prev = 0.0, g2Prev = 0.0;
1705 static constexpr double kConductionKnees[4] = {-0.6, -0.3, 0.1, 1.0};
1706 double gridIntegral1 = 0.0, gridIntegral2 = 0.0;
1708 double vc1 = 0.0, vc2 = 0.0, x2Prev = 0.0, x2Integral = 0.0;
1709 double vcSlope2 = 0.0;
1710 double vcRamp2 = 0.0;
1714 double charge1 = 0.0, charge2 = 0.0, chargeSlope1 = 0.0, chargeSlope2 = 0.0;
1715 double leakSlope2 = 0.0, leakEnd2 = 0.0, chargeRise = 0.0, lastIg1 = 0.0, lastIg2 = 0.0;
1716 double couplingDecay = 1.0;
1717 detail::TubePreampToneModes modes;
1718 std::array<double, 16> ring {};
1719 int ringPos = 0;
1720 double q[3] {};
1721 double vk1 = 0.0, vk2 = 0.0, ipLP = 0.0, i1Prev = 0.0, i2Prev = 0.0;
1722 double vp1 = 0.0, vp2 = 0.0;
1723 double out[kOrder] {};
1724 double cutSupply[2] = {-1.0, -1.0}, cutVgk[2] {};
1725 // Interval scratch
1726 typename LoadTable::Slice slice1, slice2;
1727 double supply = 0.0, a1 = 0.0, a2 = 0.0, s1 = 0.0, s2 = 0.0, ref1 = 0.0, ref2 = 0.0;
1728 double lev1[kMaxLevels] {}, lev2[kMaxLevels] {};
1729 int levels1 = 5, levels2 = 5;
1730 double integral1 = 0.0, integral2 = 0.0, moments[kOrder] {};
1731 double hi1 = 0.0, hi2 = 0.0;
1732 bool haveHi1 = false, haveHi2 = false;
1733 int stages = 2;
1734 // Gauss-Legendre rules on [0, 1]
1735 static constexpr double kG4x[4] = {0.069431844202973713, 0.33000947820757187,
1736 0.66999052179242813, 0.93056815579702629};
1737 static constexpr double kG4w[4] = {0.17392742256872692, 0.32607257743127308,
1738 0.32607257743127308, 0.17392742256872692};
1739 static constexpr double kG3x[3] = {0.11270166537925831, 0.5, 0.88729833462074169};
1740 static constexpr double kG3w[3] = {5.0 / 18.0, 4.0 / 9.0, 5.0 / 18.0};
1741 double lagrange4[4][4] {};
1742 double lagrange3[3][3] {};
1743 static constexpr double kG2x[2] = {0.21132486540518713, 0.78867513459481287};
1745 double nodeIntegral4[4][4] {}, nodeIntegral3[3][3] {}, nodeIntegral2[2][2] {};
1746 double endWeight4[4] {}, endWeight3[3] {}, endWeight2[2] {};
1747
1748 void init(double sampleRate, const LoadTable* tableIn,
1749 const detail::TubePreampCoreDesign* designIn) noexcept
1750 {
1751 table = tableIn;
1752 design = designIn;
1753 period = 1.0 / sampleRate;
1754 cathodeDecay = std::exp(-period / (kRk * kCk));
1755 sagDecay = std::exp(-period / 0.07);
1756 couplingDecay = std::exp(-period / (Conduction::kRg * Conduction::kCc));
1757 for (int k = 0; k < 4; ++k)
1758 {
1759 double poly[4] = {1.0, 0.0, 0.0, 0.0};
1760 double den = 1.0;
1761 int deg = 0;
1762 for (int o = 0; o < 4; ++o)
1763 {
1764 if (o == k) continue;
1765 double next[4] = {0.0, 0.0, 0.0, 0.0};
1766 for (int e = 0; e <= deg; ++e)
1767 {
1768 next[e + 1] += poly[e];
1769 next[e] -= kG4x[o] * poly[e];
1770 }
1771 ++deg;
1772 for (int e = 0; e < 4; ++e) poly[e] = next[e];
1773 den *= kG4x[k] - kG4x[o];
1774 }
1775 for (int e = 0; e < 4; ++e) lagrange4[k][e] = poly[e] / den;
1776 }
1777 for (int k = 0; k < 3; ++k)
1778 {
1779 const int o1 = (k + 1) % 3, o2 = (k + 2) % 3;
1780 const double den = (kG3x[k] - kG3x[o1]) * (kG3x[k] - kG3x[o2]);
1781 lagrange3[k][0] = kG3x[o1] * kG3x[o2] / den;
1782 lagrange3[k][1] = -(kG3x[o1] + kG3x[o2]) / den;
1783 lagrange3[k][2] = 1.0 / den;
1784 }
1785 chargeRise = (1.0 - couplingDecay) * Conduction::kRg;
1786 for (int j = 0; j < 4; ++j)
1787 for (int k = 0; k < 4; ++k)
1788 {
1789 double acc = 0.0, xp = kG4x[j];
1790 for (int e = 0; e < 4; ++e) { acc += lagrange4[k][e] * xp / (e + 1); xp *= kG4x[j]; }
1791 nodeIntegral4[j][k] = acc;
1792 }
1793 for (int j = 0; j < 3; ++j)
1794 for (int k = 0; k < 3; ++k)
1795 {
1796 double acc = 0.0, xp = kG3x[j];
1797 for (int e = 0; e < 3; ++e) { acc += lagrange3[k][e] * xp / (e + 1); xp *= kG3x[j]; }
1798 nodeIntegral3[j][k] = acc;
1799 }
1800 for (int k = 0; k < 4; ++k)
1801 endWeight4[k] = lagrange4[k][0] + lagrange4[k][1] + lagrange4[k][2] + lagrange4[k][3];
1802 for (int k = 0; k < 3; ++k) endWeight3[k] = lagrange3[k][0] + lagrange3[k][1] + lagrange3[k][2];
1803 const double g0 = kG2x[0], g1 = kG2x[1];
1804 for (int j = 0; j < 2; ++j)
1805 {
1806 const double x = kG2x[j];
1807 nodeIntegral2[j][0] = (0.5 * x * x - g1 * x) / (g0 - g1);
1808 nodeIntegral2[j][1] = (0.5 * x * x - g0 * x) / (g1 - g0);
1809 }
1810 endWeight2[0] = (1.0 - g1) / (g0 - g1);
1811 endWeight2[1] = (1.0 - g0) / (g1 - g0);
1812 }
1813
1832 template <int N>
1833 void chargeAtNodes(const double* src, double cathode, double charge, double len, double lastIg,
1834 const double (&weights)[N][N], const double* nodes, double* offset) const noexcept
1835 {
1836 // Below kChargeFloor at every node the grid current is negligible
1837 // (and smaller still at a larger charge): the nodes keep the charge.
1838 double top = src[0];
1839 for (int j = 1; j < N; ++j) top = std::max(top, src[j]);
1840 if (top - charge - cathode <= kChargeFloor)
1841 {
1842 for (int j = 0; j < N; ++j) offset[j] = charge;
1843 return;
1844 }
1845 const double k = chargeRise * len;
1846 for (int j = 0; j < N; ++j) offset[j] = charge + k * lastIg * nodes[j];
1847 double ig[N];
1848 for (int j = 0; j < N; ++j)
1849 {
1850 const double d = src[j] - offset[j] - cathode;
1851 ig[j] = (d - grid->eval(d)) * (1.0 / Conduction::kRs);
1852 }
1853 for (int j = 0; j < N; ++j)
1854 {
1855 double acc = 0.0;
1856 for (int m = 0; m < N; ++m) acc += weights[j][m] * ig[m];
1857 offset[j] = charge + k * acc;
1858 }
1859 }
1860
1862 void setTone(const wdf::ToneStackFMV<double>::AnalogStateSpace& ss) noexcept
1863 {
1864 double physical[3] = {0.0, 0.0, 0.0};
1865 for (int i = 0; i < 3; ++i)
1866 for (int m = 0; m < 3; ++m)
1867 physical[i] += modes.toPhysical[i][m] * q[m];
1868 modes.design(ss, 1.0 / period);
1869 for (int m = 0; m < 3; ++m)
1870 {
1871 q[m] = 0.0;
1872 for (int i = 0; i < 3; ++i) q[m] += modes.toModal[m][i] * physical[i];
1873 }
1874 }
1875
1876 static std::array<double, 3> dcBias(double sagR, int numStages, double grid = 0.0) noexcept
1877 {
1878 double bp = kBplus, i1 = 0.0, i2 = 0.0, iTotal = 0.0;
1879 for (int it = 0; it < 40; ++it)
1880 {
1881 i1 = settleCurrent(bp, grid);
1882 i2 = numStages > 1 && grid != 0.0 ? settleCurrent(bp) : i1;
1883 iTotal = i1 + (numStages > 1 ? i2 : 0.0);
1884 const double next = kBplus - sagR * iTotal;
1885 if (std::abs(next - bp) < 1e-12) { bp = next; break; }
1886 bp = next;
1887 }
1888 return {bp, i1, i2};
1889 }
1890
1891 void reset(double sagR, int numStages) noexcept
1892 {
1893 const auto bias = dcBias(sagR, numStages);
1894 const double bp = bias[0], i1 = bias[1];
1895 vk1 = vk2 = i1 * kRk;
1896 vp1 = vp2 = bp - i1 * kRL;
1897 ipLP = i1 * numStages;
1898 i1Prev = i2Prev = i1;
1899 g1Prev = g2Prev = 0.0;
1900 vc1 = vc2 = x2Prev = x2Integral = 0.0;
1901 vcRamp2 = vcSlope2 = 0.0;
1902 charge1 = charge2 = chargeSlope1 = chargeSlope2 = leakSlope2 = leakEnd2 = 0.0;
1903 lastIg1 = lastIg2 = 0.0;
1904 q[0] = q[1] = q[2] = 0.0;
1905 ring.fill(0.0);
1906 ringPos = 0;
1907 for (double& v : out) v = 0.0;
1908 cutSupply[0] = cutSupply[1] = -1.0;
1909 }
1910
1911 static double cutoffVgk(double s) noexcept
1912 {
1913 // Grid voltage relative to the cathode below which the plate
1914 // current is < 1e-10 A (plate effect < 10 uV) at vpk ~= s.
1915 return LoadTable::gridForCurrent(s, 1e-10);
1916 }
1917
1918 static double currentSlow(double s, double g) noexcept
1919 {
1920 // Frozen-cathode load line outside the table: Ip = Koren(s - RL Ip, g).
1921 double i = 0.5 * std::max(s, 0.0) / kRL, p = 0.0, dp = 0.0, dg = 0.0;
1922 for (int it = 0; it < 60; ++it)
1923 {
1924 koren(s - kRL * i, g, p, dp, dg);
1925 const double next = std::clamp(i - (i - p) / (1.0 + kRL * dp), 0.0,
1926 std::max(s, 0.0) / kRL);
1927 if (std::abs(next - i) < 1e-16) { i = next; break; }
1928 i = next;
1929 }
1930 return i;
1931 }
1932
1935 template <int N>
1936 void currents(const typename LoadTable::Slice& sl, double cathode,
1937 const double* x, double* result, double* gridCurrent) const noexcept
1938 {
1939 double g[N];
1940 if (grid)
1941 {
1942 for (int j = 0; j < N; ++j)
1943 {
1944 const double d = x[j] - cathode;
1945 g[j] = grid->eval(d);
1946 gridCurrent[j] = (d - g[j]) * (1.0 / detail::TubePreampGridConduction::kRs);
1947 }
1948 // The table spans R = g / S up to 0.0125.
1949 const double gMax = 0.0125 * sl.s;
1950 for (int j = 0; j < N; ++j)
1951 result[j] = (sl.inside && g[j] < gMax) ? sl.eval(g[j]) : currentSlow(sl.s, g[j]);
1952 return;
1953 }
1954 for (int j = 0; j < N; ++j) g[j] = Clamp::value(x[j]) - cathode;
1955 for (int j = 0; j < N; ++j)
1956 result[j] = (sl.inside && g[j] < 1.0) ? sl.eval(g[j]) : currentSlow(sl.s, g[j]);
1957 }
1958
1959 double current(const typename LoadTable::Slice& sl, double cathode, double x) const noexcept
1960 {
1961 double r, unused;
1962 currents<1>(sl, cathode, &x, &r, &unused);
1963 return r;
1964 }
1965
1966 static int classify(const double* lev, int levels, double v) noexcept
1967 {
1968 int k = 0;
1969 while (k < levels && v > lev[k]) ++k;
1970 return k;
1971 }
1972 static int classifyEdges(const double* lev, int levels, double v) noexcept
1973 {
1974 return v <= lev[0] ? 0 : (v > lev[levels - 1] ? levels : 1);
1975 }
1976
1977 void addMoments(double tau, double weight, double y) noexcept
1978 {
1979 const double d = tau - 0.5;
1980 double t = weight * y;
1981 for (int p = 0; p < kOrder; ++p) { moments[p] += t; t *= d; }
1982 }
1983 void addConstantMoments(double a, double b, double y) noexcept
1984 {
1985 const double pa = a - 0.5, pb = b - 0.5;
1986 double ea = pa, eb = pb;
1987 for (int p = 0; p < kOrder; ++p)
1988 {
1989 moments[p] += y * (eb - ea) / (p + 1);
1990 ea *= pa;
1991 eb *= pb;
1992 }
1993 }
1995 void addPolynomialMoments(double a, double h, const double* c, int degree) noexcept
1996 {
1997 static constexpr double inv[16] = {1.0, 1.0 / 2, 1.0 / 3, 1.0 / 4, 1.0 / 5, 1.0 / 6,
1998 1.0 / 7, 1.0 / 8, 1.0 / 9, 1.0 / 10, 1.0 / 11, 1.0 / 12, 1.0 / 13, 1.0 / 14,
1999 1.0 / 15, 1.0 / 16};
2000 static constexpr double binom[kOrder][kOrder] = {{1}, {1, 1}, {1, 2, 1},
2001 {1, 3, 3, 1}, {1, 4, 6, 4, 1}, {1, 5, 10, 10, 5, 1}};
2002 double sums[kOrder], hk = 1.0, dk[kOrder];
2003 dk[0] = 1.0;
2004 for (int k = 1; k < kOrder; ++k) dk[k] = dk[k - 1] * (a - 0.5);
2005 for (int k = 0; k < kOrder; ++k)
2006 {
2007 double acc = 0.0;
2008 for (int e = 0; e <= degree; ++e) acc += c[e] * inv[e + k];
2009 sums[k] = acc * hk;
2010 hk *= h;
2011 }
2012 for (int p = 0; p < kOrder; ++p)
2013 {
2014 double acc = 0.0;
2015 for (int k = 0; k <= p; ++k) acc += binom[p][k] * dk[p - k] * sums[k];
2016 moments[p] += h * acc;
2017 }
2018 }
2019
2023 {
2024 double c[6] {};
2025 int exactCount = 0;
2026 double q0[3] {}, z[3] {}, bt[3] {}, g[3] {};
2027 double u[4] {};
2028 int uTerms = 1;
2029
2030 double exactTerm(int k, double xi, double& derivative) const noexcept
2031 {
2032 double p[5];
2033 detail::tubePreampPhi(z[k] * xi, p);
2034 static constexpr double fact[4] = {1.0, 1.0, 2.0, 6.0};
2035 double forced = 0.0, xp = xi, ui = 0.0, xe = 1.0;
2036 for (int e = 0; e < uTerms; ++e)
2037 {
2038 forced += u[e] * fact[e] * xp * p[e + 1];
2039 xp *= xi;
2040 ui += u[e] * xe;
2041 xe *= xi;
2042 }
2043 const double qv = p[0] * q0[k] + bt[k] * forced;
2044 derivative = g[k] * (z[k] * qv + bt[k] * ui);
2045 return g[k] * qv;
2046 }
2047 double operator()(double xi) const noexcept
2048 {
2049 double v = ((((c[5] * xi + c[4]) * xi + c[3]) * xi + c[2]) * xi + c[1]) * xi + c[0];
2050 for (int k = 0; k < exactCount; ++k)
2051 {
2052 double dq;
2053 v += exactTerm(k, xi, dq);
2054 }
2055 return v;
2056 }
2057 double eval(double xi, double& derivative) const noexcept
2058 {
2059 double v = c[5], d = 0.0;
2060 for (int p = 4; p >= 0; --p)
2061 {
2062 d = d * xi + v;
2063 v = v * xi + c[p];
2064 }
2065 for (int k = 0; k < exactCount; ++k)
2066 {
2067 double dq;
2068 v += exactTerm(k, xi, dq);
2069 d += dq;
2070 }
2071 derivative = d;
2072 return v;
2073 }
2074 };
2075
2079 void propagate(double h, const double* u, int terms, Trajectory& tr) noexcept
2080 {
2081 static constexpr double fact[4] = {1.0, 1.0, 2.0, 6.0};
2082 tr.exactCount = 0;
2083 tr.uTerms = terms;
2084 for (int e = 0; e < 4; ++e) tr.u[e] = e < terms ? u[e] : 0.0;
2085 for (double& x : tr.c) x = 0.0;
2086 const double u0 = u[0], u0p = terms > 1 ? u[1] : 0.0;
2087 double u1 = 0.0, u1p = 0.0;
2088 for (int e = 0; e < terms; ++e)
2089 {
2090 u1 += u[e];
2091 u1p += e * u[e];
2092 }
2093 // Non-stiff modal sum: exact values and first/second derivatives
2094 // at both ends (from dq/dxi = z q + bt u), then a quintic Hermite.
2095 double h0 = 0.0, h0p = 0.0, h0pp = 0.0, h1 = 0.0, h1p = 0.0, h1pp = 0.0;
2096 for (int m = 0; m < 3; ++m)
2097 {
2098 const double z = modes.lambda[m] * h, bt = modes.beta[m] * h, g = modes.gamma[m];
2099 const double az = std::abs(z);
2100 if (az >= kStiffZ)
2101 {
2102 // Slow manifold of dq/dxi = z q + bt u:
2103 // q = -(bt/z) sum_k u^(k)(xi) / z^k (boundary layer < e^-40).
2104 const double iz = 1.0 / z;
2105 double der[4] = {0.0, 0.0, 0.0, 0.0};
2106 for (int e = 0; e < terms; ++e) der[e] = u[e];
2107 double izp = 1.0, endValue = 0.0;
2108 for (int k = 0; k < terms; ++k)
2109 {
2110 double sumAtEnd = 0.0;
2111 for (int e = 0; e < 4; ++e)
2112 {
2113 tr.c[e] += -g * bt * iz * izp * der[e];
2114 sumAtEnd += der[e];
2115 }
2116 endValue += izp * sumAtEnd;
2117 for (int e = 0; e < 3; ++e) der[e] = der[e + 1] * (e + 1);
2118 der[3] = 0.0;
2119 izp *= iz;
2120 }
2121 q[m] = -bt * iz * endValue;
2122 continue;
2123 }
2124 // A whole interval (h == 1) reads the values kept per mode.
2125 double pz[5];
2126 const double* p = pz;
2127 if (h == 1.0) p = modes.unitPhi[m];
2128 else detail::tubePreampPhi(z, pz);
2129 double forced = 0.0;
2130 for (int e = 0; e < terms; ++e) forced += u[e] * fact[e] * p[e + 1];
2131 const double qEnd = p[0] * q[m] + bt * forced;
2132 if (az > kSmallZ)
2133 {
2134 const int k = tr.exactCount++;
2135 tr.q0[k] = q[m];
2136 tr.z[k] = z;
2137 tr.bt[k] = bt;
2138 tr.g[k] = g;
2139 q[m] = qEnd;
2140 continue;
2141 }
2142 const double d0 = z * q[m] + bt * u0, d1 = z * qEnd + bt * u1;
2143 h0 += g * q[m];
2144 h0p += g * d0;
2145 h0pp += g * (z * d0 + bt * u0p);
2146 h1 += g * qEnd;
2147 h1p += g * d1;
2148 h1pp += g * (z * d1 + bt * u1p);
2149 q[m] = qEnd;
2150 }
2151 const double quad = 0.5 * h0pp;
2152 const double r0 = h1 - (h0 + h0p + quad), r1 = h1p - (h0p + 2.0 * quad), r2 = h1pp - 2.0 * quad;
2153 tr.c[0] += h0;
2154 tr.c[1] += h0p;
2155 tr.c[2] += quad;
2156 tr.c[3] += 10.0 * r0 - 4.0 * r1 + 0.5 * r2;
2157 tr.c[4] += -15.0 * r0 + 7.0 * r1 - r2;
2158 tr.c[5] += 6.0 * r0 - 3.0 * r1 + 0.5 * r2;
2159 for (int e = 0; e < terms; ++e) tr.c[e] += modes.direct * u[e];
2160 }
2161
2163 void stage2(double a, double h, const Trajectory& tr) noexcept
2164 {
2165 double cuts[16];
2166 int count = 0;
2167 cuts[count++] = 0.0;
2168 const int samples = h > 0.5 ? 4 : 2;
2169 double sv[5];
2170 double lo = std::numeric_limits<double>::max(), hi = -lo;
2171 for (int k = 0; k <= samples; ++k)
2172 {
2173 sv[k] = kInterstage * tr(double(k) / samples);
2174 lo = std::min(lo, sv[k]);
2175 hi = std::max(hi, sv[k]);
2176 }
2177 // Conduction model: the coupling capacitor's predicted change
2178 // across the interval (linear in time), removed from the source
2179 // that the grid sees; the capacitor update uses the source itself.
2180 const double ramp = grid ? vcSlope2 : 0.0;
2181 const auto src = [&](double t) { return kInterstage * tr(t) - ramp * (a + h * t); };
2182 if (grid) // Simpson average of the stage-2 source on this piece
2183 {
2184 x2Integral += h * (samples == 4 ? (sv[0] + 4.0 * sv[1] + 2.0 * sv[2] + 4.0 * sv[3] + sv[4]) / 12.0
2185 : (sv[0] + 4.0 * sv[1] + sv[2]) / 6.0);
2186 lo = std::numeric_limits<double>::max();
2187 hi = -lo;
2188 for (int k = 0; k <= samples; ++k)
2189 {
2190 sv[k] -= ramp * (a + h * double(k) / samples);
2191 lo = std::min(lo, sv[k]);
2192 hi = std::max(hi, sv[k]);
2193 }
2194 }
2195 const bool edges = hi - lo < (grid ? kConductionKneeRange : kKneeRange);
2196 const int levels = levels2;
2197 const auto cls = [&](double v) { return edges ? classifyEdges(lev2, levels, v) : classify(lev2, levels, v); };
2198 double pt = 0.0, pv = sv[0];
2199 int pc = cls(pv);
2200 const int first = pc;
2201 bool changed = false;
2202 for (int k = 1; k <= samples; ++k)
2203 {
2204 const double t = double(k) / samples, v = sv[k];
2205 const int cc = cls(v);
2206 if (cc != pc)
2207 {
2208 changed = true;
2209 const int low = std::min(cc, pc), high = std::max(cc, pc);
2210 for (int r = 0; r < high - low; ++r)
2211 {
2212 int li = cc > pc ? low + r : high - 1 - r;
2213 if (edges) li = li == 0 ? 0 : levels - 1;
2214 const double level = lev2[li];
2215 double tt = pt + (t - pt) * (pv - level) / (pv - v);
2216 for (int it = 0; it < 2; ++it)
2217 {
2218 double dv;
2219 const double f = kInterstage * tr.eval(tt, dv) - ramp * (a + h * tt) - level;
2220 dv = dv * kInterstage - ramp * h;
2221 if (dv == 0.0) break;
2222 const double next = tt - f / dv;
2223 if (!(next > pt && next < t)) break;
2224 tt = next;
2225 }
2226 if (tt > cuts[count - 1] + 1e-12 && count < 14) cuts[count++] = tt;
2227 }
2228 }
2229 pt = t;
2230 pv = v;
2231 pc = cc;
2232 }
2233 cuts[count++] = 1.0;
2234 for (int k = 0; k + 1 < count; ++k)
2235 {
2236 const double xa = cuts[k], xb = cuts[k + 1], len = xb - xa;
2237 if (len <= 0.0) continue;
2238 const int cm = changed ? cls(src(0.5 * (xa + xb))) : first;
2239 if (cm == 0 || (cm == levels && !grid))
2240 {
2241 double i2 = 0.0;
2242 if (cm == levels)
2243 {
2244 if (!haveHi2) { hi2 = current(slice2, a2, 1e3); haveHi2 = true; }
2245 i2 = hi2;
2246 }
2247 integral2 += h * len * i2;
2248 if (grid) lastIg2 = 0.0;
2249 addConstantMoments(a + h * xa, a + h * xb, supply - kRL * i2 - vp2);
2250 continue;
2251 }
2252 if (h * len > kLongPiece)
2253 {
2254 // Long smooth piece: a cubic interpolant keeps harmonics
2255 // near 0.8 cycles/sample from leaking past the kernel.
2256 double xs[4], is[4], gs[4], y[4], poly[4];
2257 for (int j = 0; j < 4; ++j) xs[j] = src(xa + len * kG4x[j]);
2258 if (grid) chargeNodes2<4>(xs, a, h, xa, len, nodeIntegral4, kG4x);
2259 currents<4>(slice2, ref2, xs, is, gs);
2260 for (int j = 0; j < 4; ++j)
2261 {
2262 integral2 += h * len * kG4w[j] * is[j];
2263 y[j] = supply - kRL * is[j] - vp2;
2264 }
2265 if (grid)
2266 {
2267 double sum = 0.0, end = 0.0;
2268 for (int j = 0; j < 4; ++j) { sum += kG4w[j] * gs[j]; end += endWeight4[j] * gs[j]; }
2269 gridIntegral2 += h * len * sum;
2270 charge2 += chargeRise * h * len * sum;
2271 lastIg2 = std::max(end, 0.0);
2272 }
2273 for (int e = 0; e < 4; ++e)
2274 poly[e] = lagrange4[0][e] * y[0] + lagrange4[1][e] * y[1]
2275 + lagrange4[2][e] * y[2] + lagrange4[3][e] * y[3];
2276 addPolynomialMoments(a + h * xa, h * len, poly, 3);
2277 continue;
2278 }
2279 if (h * len < kShortPiece)
2280 {
2281 // Short piece: two nodes and the exact moments of their
2282 // linear interpolant.
2283 constexpr double g0 = kG2x[0], g1 = kG2x[1];
2284 double xs[2] = {src(xa + len * g0), src(xa + len * g1)}, is[2], gs[2];
2285 if (grid) chargeNodes2<2>(xs, a, h, xa, len, nodeIntegral2, kG2x);
2286 currents<2>(slice2, ref2, xs, is, gs);
2287 integral2 += h * len * 0.5 * (is[0] + is[1]);
2288 if (grid)
2289 {
2290 gridIntegral2 += h * len * 0.5 * (gs[0] + gs[1]);
2291 charge2 += chargeRise * h * len * 0.5 * (gs[0] + gs[1]);
2292 lastIg2 = std::max(endWeight2[0] * gs[0] + endWeight2[1] * gs[1], 0.0);
2293 }
2294 const double y0 = supply - kRL * is[0] - vp2, y1 = supply - kRL * is[1] - vp2;
2295 double poly[2];
2296 poly[1] = (y1 - y0) / (g1 - g0);
2297 poly[0] = y0 - poly[1] * g0;
2298 addPolynomialMoments(a + h * xa, h * len, poly, 1);
2299 continue;
2300 }
2301 double xs[3], is[3], gs[3];
2302 for (int j = 0; j < 3; ++j) xs[j] = src(xa + len * kG3x[j]);
2303 if (grid) chargeNodes2<3>(xs, a, h, xa, len, nodeIntegral3, kG3x);
2304 currents<3>(slice2, ref2, xs, is, gs);
2305 if (grid)
2306 {
2307 double sum = 0.0, end = 0.0;
2308 for (int j = 0; j < 3; ++j) { sum += kG3w[j] * gs[j]; end += endWeight3[j] * gs[j]; }
2309 gridIntegral2 += h * len * sum;
2310 charge2 += chargeRise * h * len * sum;
2311 lastIg2 = std::max(end, 0.0);
2312 }
2313 // Exact moments of the plate interpolant through the three
2314 // nodes: Gauss weights alone are not exact for the quintic
2315 // kernel weights times a curved plate trajectory.
2316 double y[3], poly[3];
2317 for (int j = 0; j < 3; ++j)
2318 {
2319 integral2 += h * len * kG3w[j] * is[j];
2320 y[j] = supply - kRL * is[j] - vp2;
2321 }
2322 for (int e = 0; e < 3; ++e)
2323 poly[e] = lagrange3[0][e] * y[0] + lagrange3[1][e] * y[1] + lagrange3[2][e] * y[2];
2324 addPolynomialMoments(a + h * xa, h * len, poly, 2);
2325 }
2326 }
2327
2330 template <int N>
2331 void chargeNodes2(double* xs, double a, double h, double xa, double len,
2332 const double (&weights)[N][N], const double* nodes) const noexcept
2333 {
2334 double src[N], offset[N];
2335 for (int j = 0; j < N; ++j) src[j] = xs[j] + chargeSlope2 * (a + h * (xa + len * nodes[j]));
2336 chargeAtNodes<N>(src, ref2, charge2, h * len, lastIg2, weights, nodes, offset);
2337 for (int j = 0; j < N; ++j) xs[j] = src[j] - offset[j];
2338 }
2339
2340 void plate(double a, double h, const double* u, int terms) noexcept
2341 {
2342 Trajectory tr;
2343 propagate(h, u, terms, tr);
2344 if (stages > 1)
2345 stage2(a, h, tr);
2346 else if (tr.exactCount == 0)
2347 addPolynomialMoments(a, h, tr.c, 5);
2348 else
2349 {
2350 // Intermediate-stiffness mode present: interpolate the
2351 // tone-circuit output at the nodes, then take exact moments.
2352 const double y[3] = {tr(kG3x[0]), tr(kG3x[1]), tr(kG3x[2])};
2353 double poly[3];
2354 for (int e = 0; e < 3; ++e)
2355 poly[e] = lagrange3[0][e] * y[0] + lagrange3[1][e] * y[1] + lagrange3[2][e] * y[2];
2356 addPolynomialMoments(a, h, poly, 2);
2357 }
2358 }
2359
2360 double process(double x, int numStages, double sagR) noexcept
2361 {
2362 stages = numStages;
2363 const int taps = design->taps;
2364 ring[static_cast<size_t>(ringPos)] = x;
2365 ringPos = ringPos + 1 == taps ? 0 : ringPos + 1;
2366 interval(sagR);
2367 const double result = out[0];
2368 for (int k = 0; k + 1 < kOrder; ++k) out[k] = out[k + 1];
2369 out[kOrder - 1] = 0.0;
2370 return result;
2371 }
2372
2373 void interval(double sagR) noexcept
2374 {
2375 // Stage-1 grid polynomial on the interval [n, n+1].
2376 const int taps = design->taps;
2377 int deg = design->degree;
2378 double c[16] {};
2379 int idx = ringPos;
2380 for (int j = 0; j < taps; ++j)
2381 {
2382 const double v = ring[static_cast<size_t>(idx)];
2383 idx = idx + 1 == taps ? 0 : idx + 1;
2384 const double* row = design->farrow + j * (deg + 1);
2385 for (int p = 0; p <= deg; ++p) c[p] += row[p] * v;
2386 }
2387 const auto xAt = [&](double tau) {
2388 double v = c[deg];
2389 for (int p = deg - 1; p >= 0; --p) v = v * tau + c[p];
2390 return v;
2391 };
2392 // Slow states frozen at the predicted interval midpoint.
2393 const double iPrev = i1Prev + (stages > 1 ? i2Prev : 0.0);
2394 supply = kBplus - sagR * (ipLP + 0.5 * (1.0 - sagDecay) * (iPrev - ipLP));
2395 a1 = vk1 + 0.5 * (1.0 - cathodeDecay) * ((i1Prev + g1Prev) * kRk - vk1);
2396 a2 = vk2 + 0.5 * (1.0 - cathodeDecay) * ((i2Prev + g2Prev) * kRk - vk2);
2397 s1 = supply - a1;
2398 s2 = supply - a2;
2399 slice1.set(*table, s1);
2400 slice2.set(*table, s2);
2401 if (std::abs(s1 - cutSupply[0]) > 0.05) { cutSupply[0] = s1; cutVgk[0] = cutoffVgk(s1); }
2402 if (std::abs(s2 - cutSupply[1]) > 0.05) { cutSupply[1] = s2; cutVgk[1] = cutoffVgk(s2); }
2403 // Grid references: the cathode, plus the coupling capacitor voltage
2404 // (conduction model), advanced exactly below with the interval-
2405 // average source and grid current.
2406 ref1 = a1;
2407 ref2 = a2;
2408 double x1Avg = 0.0;
2409 if (grid)
2410 {
2411 // The coupling capacitor follows Cc dvc/dt = (x - vc) / Rg + Ig
2412 // inside the interval: vc(t) = vc + rise (X(t) - vc t) + Q(t)
2413 // to first order in rise = 1 - e^(-T / (Rg Cc)), with X the
2414 // integral of the source and Q the grid-current charge. Stage
2415 // 1: the leak is exact in the source polynomial (one degree
2416 // more), the charge is integrated piece by piece
2417 // (chargeAtNodes()); the predicted charge slope only places
2418 // the level crossings. Stage 2: the leak ramps from where the
2419 // previous reference ended to its predicted end (its source is
2420 // known only piece by piece), the charge as in stage 1. A held
2421 // or ramped capacitor stepped or bent at every boundary under
2422 // grid current, which the output kernel cannot remove.
2423 for (int p = 0; p <= deg; ++p) x1Avg += c[p] / (p + 1);
2424 const double rise = 1.0 - couplingDecay;
2425 chargeSlope1 = chargeRise * g1Prev;
2426 ref1 += vc1;
2427 for (int p = deg + 1; p >= 1; --p) c[p] -= rise * c[p - 1] / p;
2428 c[1] += rise * vc1 - chargeSlope1;
2429 ++deg;
2430 leakEnd2 = vc2 + rise * (x2Prev - vc2);
2431 leakSlope2 = leakEnd2 - vcRamp2;
2432 chargeSlope2 = chargeRise * g2Prev;
2433 vcSlope2 = leakSlope2 + chargeSlope2;
2434 ref2 += vcRamp2;
2435 charge1 = charge2 = 0.0;
2436 }
2437 lev1[0] = ref1 + cutVgk[0]; lev1[1] = ref1 - 3.0; lev1[2] = ref1 - 1.0; lev1[3] = 1.0; lev1[4] = 6.0;
2438 lev2[0] = ref2 + cutVgk[1]; lev2[1] = ref2 - 3.0; lev2[2] = ref2 - 1.0; lev2[3] = 1.0; lev2[4] = 6.0;
2439 if (grid)
2440 {
2441 // Conduction knee relative to the cathode, where the grid
2442 // slope falls from 1 to 0.2 (source -0.6 .. +0.3 V against
2443 // the cathode); no saturated top region, the grid keeps
2444 // rising slowly with the source. Stage 1 is also split
2445 // halfway between cutoff and A-3, where the plate current
2446 // grows about six decades: with the stage biased colder by
2447 // the charged capacitor its pulses start there, and one cubic
2448 // across it aliased (-81.4 against -90.3 dBc, two stages,
2449 // +24 dB, 16 kHz).
2450 levels1 = 8;
2451 levels2 = 7;
2452 for (int k = 7; k >= 2; --k) lev1[k] = lev1[k - 1];
2453 lev1[1] = 0.5 * (lev1[0] + lev1[2]);
2454 for (int k = 0; k < 4; ++k)
2455 {
2456 lev1[4 + k] = ref1 + kConductionKnees[k];
2457 lev2[3 + k] = ref2 + kConductionKnees[k];
2458 }
2459 }
2460 for (int j = 1; j < levels1; ++j) lev1[j] = std::max(lev1[j], lev1[j - 1] + 1e-6);
2461 for (int j = 1; j < levels2; ++j) lev2[j] = std::max(lev2[j], lev2[j - 1] + 1e-6);
2462 // Split the interval where the grid crosses the stage-1 levels;
2463 // interior knees only when the interval spans at least 1 V.
2464 double qv[5];
2465 double lo = std::numeric_limits<double>::max(), hi = -lo;
2466 for (int k = 0; k <= 4; ++k)
2467 {
2468 qv[k] = xAt(0.25 * k);
2469 lo = std::min(lo, qv[k]);
2470 hi = std::max(hi, qv[k]);
2471 }
2472 const bool edges = hi - lo < (grid ? kConductionKneeRange : kKneeRange);
2473 const int levels = levels1;
2474 const auto cls = [&](double v) { return edges ? classifyEdges(lev1, levels, v) : classify(lev1, levels, v); };
2475 double cuts[kMaxPieces];
2476 int count = 0;
2477 cuts[count++] = 0.0;
2478 double pt = 0.0, pv = qv[0];
2479 int pc = cls(pv);
2480 const int first = pc;
2481 bool changed = false;
2482 for (int k = 1; k <= 4; ++k)
2483 {
2484 const double t = 0.25 * k, v = qv[k];
2485 const int cc = cls(v);
2486 if (cc != pc)
2487 {
2488 changed = true;
2489 const int low = std::min(cc, pc), high = std::max(cc, pc);
2490 for (int r = 0; r < high - low; ++r)
2491 {
2492 int li = cc > pc ? low + r : high - 1 - r;
2493 if (edges) li = li == 0 ? 0 : levels - 1;
2494 const double level = lev1[li];
2495 double tt = pt + (t - pt) * (pv - level) / (pv - v);
2496 for (int it = 0; it < 2; ++it)
2497 {
2498 double f = c[deg], df = 0.0;
2499 for (int p = deg - 1; p >= 0; --p) { df = df * tt + f; f = f * tt + c[p]; }
2500 f -= level;
2501 if (df == 0.0) break;
2502 const double next = tt - f / df;
2503 if (!(next > pt && next < t)) break;
2504 tt = next;
2505 }
2506 if (tt > cuts[count - 1] + 1e-12 && count < kMaxPieces - 2) cuts[count++] = tt;
2507 }
2508 }
2509 pt = t;
2510 pv = v;
2511 pc = cc;
2512 }
2513 cuts[count++] = 1.0;
2514 integral1 = integral2 = 0.0;
2515 gridIntegral1 = gridIntegral2 = 0.0;
2516 x2Integral = 0.0;
2517 for (double& m : moments) m = 0.0;
2518 haveHi1 = haveHi2 = false;
2519 for (int k = 0; k + 1 < count; ++k)
2520 {
2521 const double a = cuts[k], b = cuts[k + 1], h = b - a;
2522 if (h <= 0.0) continue;
2523 const int cm = changed ? cls(xAt(0.5 * (a + b))) : first;
2524 if (cm == 0 || (cm == levels && !grid))
2525 {
2526 // Stage 1 saturated: constant plate voltage on the piece.
2527 double i1 = 0.0;
2528 if (cm == levels)
2529 {
2530 if (!haveHi1) { hi1 = current(slice1, a1, 1e3); haveHi1 = true; }
2531 i1 = hi1;
2532 }
2533 integral1 += h * i1;
2534 if (grid) lastIg1 = 0.0;
2535 const double u[1] = {supply - kRL * i1 - vp1};
2536 plate(a, h, u, 1);
2537 continue;
2538 }
2539 if (grid && h < kShortPiece)
2540 {
2541 // Short piece (conduction model): two nodes and the exact
2542 // moments of the plate's linear interpolant, as in stage 2.
2543 constexpr double g0 = kG2x[0], g1 = kG2x[1];
2544 const double ta = a + h * g0, tb = a + h * g1;
2545 double va = c[deg], vb = c[deg];
2546 for (int p = deg - 1; p >= 0; --p) { va = va * ta + c[p]; vb = vb * tb + c[p]; }
2547 double src[2] = {va + chargeSlope1 * ta, vb + chargeSlope1 * tb}, offset[2];
2548 chargeAtNodes<2>(src, ref1, charge1, h, lastIg1, nodeIntegral2, kG2x, offset);
2549 double x2[2] = {src[0] - offset[0], src[1] - offset[1]}, i2[2], q2[2];
2550 currents<2>(slice1, ref1, x2, i2, q2);
2551 integral1 += h * 0.5 * (i2[0] + i2[1]);
2552 gridIntegral1 += h * 0.5 * (q2[0] + q2[1]);
2553 charge1 += chargeRise * h * 0.5 * (q2[0] + q2[1]);
2554 lastIg1 = std::max(endWeight2[0] * q2[0] + endWeight2[1] * q2[1], 0.0);
2555 const double y0 = supply - kRL * i2[0] - vp1, y1 = supply - kRL * i2[1] - vp1;
2556 double u2[2];
2557 u2[1] = (y1 - y0) / (g1 - g0);
2558 u2[0] = y0 - u2[1] * g0;
2559 plate(a, h, u2, 2);
2560 continue;
2561 }
2562 if (grid && h < kMediumPiece)
2563 {
2564 // Medium piece (conduction model): three nodes and the
2565 // exact moments of their quadratic interpolant.
2566 double x3[3], src[3], offset[3], i3[3], q3[3];
2567 for (int j = 0; j < 3; ++j)
2568 {
2569 const double tj = a + h * kG3x[j];
2570 double v = c[deg];
2571 for (int p = deg - 1; p >= 0; --p) v = v * tj + c[p];
2572 src[j] = v + chargeSlope1 * tj;
2573 }
2574 chargeAtNodes<3>(src, ref1, charge1, h, lastIg1, nodeIntegral3, kG3x, offset);
2575 for (int j = 0; j < 3; ++j) x3[j] = src[j] - offset[j];
2576 currents<3>(slice1, ref1, x3, i3, q3);
2577 double y3[3], sum = 0.0, end = 0.0;
2578 for (int j = 0; j < 3; ++j)
2579 {
2580 integral1 += h * kG3w[j] * i3[j];
2581 y3[j] = supply - kRL * i3[j] - vp1;
2582 sum += kG3w[j] * q3[j];
2583 end += endWeight3[j] * q3[j];
2584 }
2585 gridIntegral1 += h * sum;
2586 charge1 += chargeRise * h * sum;
2587 lastIg1 = std::max(end, 0.0);
2588 double u3[3];
2589 for (int e = 0; e < 3; ++e)
2590 u3[e] = lagrange3[0][e] * y3[0] + lagrange3[1][e] * y3[1] + lagrange3[2][e] * y3[2];
2591 plate(a, h, u3, 3);
2592 continue;
2593 }
2594 double xs[4], is[4];
2595 {
2596 double t0 = a + h * kG4x[0], t1 = a + h * kG4x[1];
2597 double t2 = a + h * kG4x[2], t3 = a + h * kG4x[3];
2598 double v0 = c[deg], v1 = c[deg], v2 = c[deg], v3 = c[deg];
2599 for (int p = deg - 1; p >= 0; --p)
2600 {
2601 v0 = v0 * t0 + c[p];
2602 v1 = v1 * t1 + c[p];
2603 v2 = v2 * t2 + c[p];
2604 v3 = v3 * t3 + c[p];
2605 }
2606 xs[0] = v0; xs[1] = v1; xs[2] = v2; xs[3] = v3;
2607 }
2608 if (grid)
2609 {
2610 double src[4], offset[4];
2611 for (int j = 0; j < 4; ++j) src[j] = xs[j] + chargeSlope1 * (a + h * kG4x[j]);
2612 chargeAtNodes<4>(src, ref1, charge1, h, lastIg1, nodeIntegral4, kG4x, offset);
2613 for (int j = 0; j < 4; ++j) xs[j] = src[j] - offset[j];
2614 }
2615 double gs[4];
2616 currents<4>(slice1, ref1, xs, is, gs);
2617 double y[4];
2618 for (int j = 0; j < 4; ++j)
2619 {
2620 y[j] = supply - kRL * is[j] - vp1;
2621 integral1 += h * kG4w[j] * is[j];
2622 }
2623 if (grid)
2624 {
2625 double sum = 0.0, end = 0.0;
2626 for (int j = 0; j < 4; ++j) { sum += kG4w[j] * gs[j]; end += endWeight4[j] * gs[j]; }
2627 gridIntegral1 += h * sum;
2628 charge1 += chargeRise * h * sum;
2629 lastIg1 = std::max(end, 0.0);
2630 }
2631 double u[4];
2632 for (int e = 0; e < 4; ++e)
2633 u[e] = lagrange4[0][e] * y[0] + lagrange4[1][e] * y[1]
2634 + lagrange4[2][e] * y[2] + lagrange4[3][e] * y[3];
2635 plate(a, h, u, 4);
2636 }
2637 // Exact exponential updates with the interval-average currents.
2638 // The cathode carries plate and grid current; the supply only
2639 // the plate current.
2640 vk1 = vk1 * cathodeDecay + (1.0 - cathodeDecay) * kRk * (integral1 + gridIntegral1);
2641 if (stages > 1)
2642 {
2643 vk2 = vk2 * cathodeDecay + (1.0 - cathodeDecay) * kRk * (integral2 + gridIntegral2);
2644 i2Prev = integral2;
2645 g2Prev = gridIntegral2;
2646 }
2647 if (grid)
2648 {
2649 // Coupling capacitors: Cc dvc/dt = (x - vc) / Rg + Ig, exact for
2650 // the interval-average source x and grid current Ig.
2651 vc1 = vc1 * couplingDecay + (1.0 - couplingDecay) * (x1Avg + Conduction::kRg * gridIntegral1);
2652 if (stages > 1)
2653 {
2654 vc2 = vc2 * couplingDecay + (1.0 - couplingDecay) * (x2Integral + Conduction::kRg * gridIntegral2);
2655 x2Prev = x2Integral;
2656 vcRamp2 = leakEnd2 + charge2; // the reference where this interval ended
2657 }
2658 }
2659 ipLP = ipLP * sagDecay + (1.0 - sagDecay) * (integral1 + (stages > 1 ? integral2 : 0.0));
2660 i1Prev = integral1;
2661 g1Prev = gridIntegral1;
2662 for (int k = 0; k < kOrder; ++k)
2663 {
2664 const auto& piece = design->kernel[static_cast<size_t>(k)];
2665 double acc = 0.0;
2666 for (int p = 0; p < kOrder; ++p) acc += piece[static_cast<size_t>(p)] * moments[p];
2667 out[k] += acc;
2668 }
2669 }
2670 };
2671
2673 struct ChannelState
2674 {
2675 explicit ChannelState(double fs2In, const LoadTable* table,
2676 const detail::TubePreampCoreDesign* designIn,
2677 const detail::TubePreampGridTable* gridIn)
2678 : design(designIn), fmv(38e3, 1e6) // fixed source impedance
2679 {
2680 stage1.table = table;
2681 stage2.table = table;
2682 stage1.grid = gridIn;
2683 stage2.grid = gridIn;
2684 core.grid = gridIn;
2685 stage1.fs2 = fs2In;
2686 stage2.fs2 = fs2In;
2687 fs2 = fs2In;
2688 fmv.prepare(fs2In);
2689 if (design)
2690 {
2691 core.init(fs2In, table, design);
2692 core.setTone(fmv.analogStateSpace());
2693 compensation.prepare(static_cast<int>(design->compensation.size()), 1);
2694 compensation.setCoefficients(design->compensation);
2695 }
2696 }
2697
2704 void reset(double sagR, int numStages) noexcept
2705 {
2706 // Fixed point over the ACTIVE stage count: processing only
2707 // draws current from the stages in use, so seeding ipLP with both
2708 // stages' current at 1-stage settings left a ~70 ms sag transient.
2709 double bp = kBplus;
2710 double iTotal = 0.0;
2711 for (int it = 0; it < 8; ++it)
2712 {
2713 stage1.settleDC(bp);
2714 stage2.settleDC(bp);
2715 iTotal = stage1.ip + (numStages > 1 ? stage2.ip : 0.0);
2716 const double bpNew = kBplus - sagR * iTotal;
2717 if (std::abs(bpNew - bp) < 1e-9) break;
2718 bp = bpNew;
2719 }
2720 ipLP = iTotal;
2721 outHpX = outHpY = 0.0;
2722 fmv.reset();
2723 for (auto& set : flatten)
2724 for (auto& f : set)
2725 f.reset();
2726 if (design)
2727 {
2728 core.reset(sagR, numStages);
2729 compensation.reset();
2730 }
2731 }
2732
2739 void resumeFrom(const ChannelState& source, int numStages, double sagR) noexcept
2740 {
2741 // The bypass capacitor already measures mean plate current.
2742 // Invert Koren at that operating point, then solve the requested
2743 // load with the same effective grid bias. Using zero input as the
2744 // reference would still produce a pulse with DC-biased audio.
2745 const double current1 = (design ? source.core.vk1 : source.stage1.vk) / kRk;
2746 const double current2 = numStages == 1
2747 ? (design ? source.core.vk2 : source.stage2.vk) / kRk : 0.0;
2748 const double supply = kBplus - sagR * (current1 + current2);
2749 const double plate = std::max(1.0, supply - (kRL + kRk) * current1);
2750 const double grid = kRk * current1
2751 + LoadTable::gridForCurrent(plate, std::max(current1, 1e-18));
2752 const auto after = ContinuousCore::dcBias(sagR, numStages, grid);
2753 const double di = after[1] - current1;
2754 const double dTotal = after[1] + (numStages == 2 ? after[2] : 0.0) - current1 - current2;
2755 const double dPlate = after[0] - supply - kRL * di;
2756 const double reference = after[0] - kRL * after[1];
2757 const double previousReference = design ? source.core.vp1 : source.stage1.vpDC;
2758 const double inputOffset = previousReference + dPlate - reference;
2759 stage1 = source.stage1;
2760 stage1.vk += kRk * di;
2761 stage1.ip += di;
2762 stage1.vpDC = reference;
2763 stage2.ip = after[2];
2764 stage2.vk = kRk * after[2];
2765 stage2.vpDC = after[0] - kRL * after[2];
2766 stage2.fPrev = 0.0;
2767 stage2.ig = stage2.vc = stage2.icPrev = 0.0;
2768 ipLP = source.ipLP + dTotal;
2769 if (!design) fmv.copyStateFrom(source.fmv, inputOffset);
2770 core = source.core;
2771 core.vk1 += kRk * di;
2772 core.i1Prev += di;
2773 core.vp1 = reference;
2774 core.vc2 = core.x2Prev = core.g2Prev = core.vcRamp2 = 0.0;
2775 if (design)
2776 for (int mode = 0; mode < 3; ++mode)
2777 for (int capacitor = 0; capacitor < 3; ++capacitor)
2778 core.q[mode] += core.modes.toModal[mode][capacitor] * inputOffset;
2779 // A common DC shift of the three coupling-capacitor voltages
2780 // exactly cancels the changed stage-1 voltage reference. Rebase
2781 // that reference at each fork so repeated switches cannot drift
2782 // it (and the compensating capacitor state) without bound.
2783 core.ipLP += dTotal;
2784 core.vk2 = stage2.vk;
2785 core.vp2 = stage2.vpDC;
2786 core.i2Prev = stage2.ip;
2787 for (double& value : core.out) value = 0.0;
2788 outHpX = outHpY = 0.0;
2789 for (auto& filter : flatten[static_cast<size_t>(numStages - 1)])
2790 filter.reset();
2791 if (design) compensation.reset();
2792 }
2793
2795 void setFlattenCoeffs(int stageCount,
2796 const std::array<BiquadCoeffs, 3>& c) noexcept
2797 {
2798 auto& set = flatten[static_cast<size_t>(stageCount - 1)];
2799 for (int k = 0; k < 3; ++k)
2800 set[static_cast<size_t>(k)].setCoeffs(c[static_cast<size_t>(k)]);
2801 }
2802
2803 void setToneControls(double t, double b, double m) noexcept
2804 {
2805 fmv.setControls(t, b, m); // rebuilds the R-type scattering
2806 if (design) core.setTone(fmv.analogStateSpace());
2807 }
2808
2810 [[nodiscard]] double supplyCurrent() const noexcept { return design ? core.ipLP : ipLP; }
2811
2812 template <bool Compensate = true>
2813 [[nodiscard]] double processSample(double vgIn, int numStages, double sagR) noexcept
2814 {
2815 double v;
2816 if (design)
2817 v = core.process(vgIn, numStages, sagR);
2818 else
2819 {
2820 // Supply sag: B+ droops with smoothed total plate current.
2821 const double sagAlpha = 1.0 - std::exp(-1.0 / (0.07 * fs2));
2822 const double iTotal = stage1.ip + (numStages > 1 ? stage2.ip : 0.0);
2823 ipLP += sagAlpha * (iTotal - ipLP);
2824 const double bplusEff = kBplus - sagR * ipLP;
2825 // Stage 1 -> FMV tone stack -> (stage 2).
2826 v = stage1.processSample(vgIn, bplusEff);
2827 v = fmv.processSample(v);
2828 if (numStages > 1)
2829 v = stage2.processSample(v * kInterstage, bplusEff);
2830 }
2831
2832 // Output coupling high-pass (~8 Hz, removes residual sag drift).
2833 const double a = 1.0 - 2.0 * std::numbers::pi * 8.0 / fs2;
2834 const double y = a * (outHpY + v - outHpX);
2835 outHpX = v;
2836 outHpY = y;
2837 // Restore absolute polarity for single-stage use.
2838 double out = (numStages > 1) ? y : -y;
2839
2840 // Reference-flattening EQ: undoes the FMV stack's fixed envelope
2841 // at the neutral tone setting (designed in calibrateReference
2842 // from the measured response), so neutral knobs sound neutral
2843 // and the tone controls act RELATIVE to flat. This linear stage
2844 // adds no harmonics.
2845 auto& fl = flatten[numStages > 1 ? 1 : 0];
2846 out = fl[0].processSample(out, 0);
2847 out = fl[1].processSample(out, 0);
2848 out = fl[2].processSample(out, 0);
2849 if constexpr (!Compensate) return out;
2850 if (!design) return out;
2851 return compensation.processSample(out, 0);
2852 }
2853
2854 void compensateBlock(double* data, int count) noexcept
2855 {
2856 // Core block processing hoists coefficient publication/atomics
2857 // out of the inner loop. The calibration uses the same FIR.
2858 compensation.processBlock(AudioBufferView<double>(&data, 1, count));
2859 }
2860
2861 double fs2 = 96000.0;
2862 TriodeStage stage1, stage2;
2863 double ipLP = 1.6e-3;
2864 double outHpX = 0.0, outHpY = 0.0;
2865 std::array<std::array<Biquad<double, 1>, 3>, 2> flatten;
2866 const detail::TubePreampCoreDesign* design;
2867 ContinuousCore core;
2868 FIRFilter<double> compensation;
2869
2870 wdf::ToneStackFMV<double> fmv;
2871 };
2872
2874 void recompute() noexcept
2875 {
2876 const double drive = std::pow(10.0, static_cast<double>(
2877 driveDb_.load(std::memory_order_relaxed)) / 20.0);
2878 const double t = static_cast<double>(treble_.load(std::memory_order_relaxed));
2879 const double b = static_cast<double>(bass_.load(std::memory_order_relaxed));
2880 const double m = static_cast<double>(middle_.load(std::memory_order_relaxed));
2881 const double sag = static_cast<double>(sag_.load(std::memory_order_relaxed));
2882 const int requestedStages = stages_.load(std::memory_order_relaxed);
2883
2884 hScale_ = drive; // 0 dBFS -> 1 V grid at drive 0
2885 // Note on physics: a class-A preamp draws near-constant average
2886 // current, so supply sag shifts the operating point rather than
2887 // pumping like a push-pull power amp. The audible touch response of
2888 // this model comes from the cathode-bypass bias shift (modelled in
2889 // TriodeStage); the sag control changes voicing, not loudness.
2890 sagR_ = sag * 40e3;
2891 for (auto& lane : channels_)
2892 for (auto& ch : lane)
2893 ch->setToneControls(t, b, m);
2894
2895 if (!gainsInitialized_)
2896 {
2897 // A pre-stream edit selects the initial circuit, without a fade
2898 // or a supply transient from the other topology's DC point.
2899 for (auto& ch : channels_[static_cast<size_t>(requestedStages - 1)])
2900 ch->reset(sagR_, requestedStages);
2901 stageBlend_.reset(static_cast<double>(requestedStages - 1));
2902 bothStagesActive_ = false;
2903 stageWarmupRemaining_ = 0;
2904 }
2905 else if (requestedStages != numStagesActive_)
2906 {
2907 if (!bothStagesActive_)
2908 {
2909 auto& incoming = channels_[static_cast<size_t>(requestedStages - 1)];
2910 const auto& outgoing = channels_[static_cast<size_t>(numStagesActive_ - 1)];
2911 for (size_t ch = 0; ch < incoming.size(); ++ch)
2912 incoming[ch]->resumeFrom(*outgoing[ch], requestedStages, sagR_);
2913 stageWarmupRemaining_ = std::max(1, static_cast<int>(std::ceil(0.005 * fs2_)));
2914 bothStagesActive_ = true;
2915 }
2916 stageBlend_.setTargetValue(static_cast<double>(requestedStages - 1));
2917 if (!stageBlend_.isSmoothing())
2918 {
2919 bothStagesActive_ = false;
2920 stageWarmupRemaining_ = 0;
2921 }
2922 }
2923 numStagesActive_ = requestedStages;
2924
2925 // Loudness: divide out the circuit's program gain at the REFERENCE
2926 // tone setting (measured once in prepare on a settled channel) and
2927 // MOST of the drive factor. The link is partial (drive^0.75, i.e. a
2928 // residual +0.25 dB/dB slope): an exact 1/drive link leaves the knob
2929 // audibly dead below 0 dB (the circuit is still clean there) and
2930 // turns it into a pure attenuator above (compression eats level
2931 // faster than the link returns it). With the residual slope, -12 dB
2932 // drive sits ~3 dB lower and clean, high drive holds level while the
2933 // density grows. The tone knobs stay fully audible: their deviation
2934 // from the 0.5/0.5/0.5 reference is part of the tone, not the level.
2935 // Cheap by construction (no scratch processing on the audio thread).
2936 //
2937 // The divisor is the circuit's MEASURED program gain at this drive
2938 // (prepare-time LUT, log-interpolated) - same contract as
2939 // TapeMachine/TransformerModel, whose per-drive scratch calibration
2940 // is what kept their knobs healthy. The previous analytic
2941 // 1/drive^0.75 broke at high drive: once the triode pins at its
2942 // ceiling, output stops growing with drive while the divisor keeps
2943 // rising, so the level FELL hard instead of holding.
2944 const double driveDbNow = static_cast<double>(driveDb_.load(std::memory_order_relaxed));
2945 for (int st = 1; st <= 2; ++st)
2946 mScale_[static_cast<size_t>(st - 1)] = std::pow(drive, 0.25)
2947 / std::max(programGainAt(driveDbNow, st), 1e-9);
2948 }
2949
2951 [[nodiscard]] double programGainAt(double driveDb, int stages) const noexcept
2952 {
2953 const auto& lut = gProgLut_[static_cast<size_t>(stages - 1)];
2954 // Ordered min/max instead of clamp: a NaN input resolves to 0 here
2955 // (defence in depth; the setter already rejects non-finite values, and
2956 // an unguarded NaN would UB-cast into a wild LUT index).
2957 const double pos = std::min(std::max(0.0, (driveDb - kDriveLutMinDb) / kDriveLutStepDb),
2958 static_cast<double>(kDriveLutN - 1));
2959 const int idx = std::min(static_cast<int>(pos), kDriveLutN - 2);
2960 const double frac = pos - static_cast<double>(idx);
2961 const double a = std::max(lut[static_cast<size_t>(idx)], 1e-9);
2962 const double b = std::max(lut[static_cast<size_t>(idx) + 1], 1e-9);
2963 return a * std::pow(b / a, frac); // gains are smooth in dB
2964 }
2965
2981 void calibrateReference() noexcept
2982 {
2983 constexpr double kRefTones[] = { 100.0, 200.0, 400.0, 800.0, 1600.0, 3200.0, 6400.0 };
2984 constexpr double kSagRef = 0.3 * 40e3;
2985 const int settle = static_cast<int>(0.060 * fs2_);
2986 const int meas = static_cast<int>(0.050 * fs2_);
2987 constexpr double kAmpPerTone = 0.095 / 2.6457513;
2988
2989 for (int st = 1; st <= 2; ++st)
2990 {
2991 ChannelState cal(fs2_, loadTable_.get(), design_.get(), gridTable_.get());
2992 cal.setToneControls(0.5, 0.5, 0.5);
2993 cal.reset(kSagRef, st);
2994
2995 // Per-tone Goertzel over the measured tail.
2996 std::array<double, 7> gs1 {}, gs2 {}, gc {};
2997 for (int k = 0; k < 7; ++k)
2998 gc[static_cast<size_t>(k)] =
2999 2.0 * std::cos(2.0 * std::numbers::pi * kRefTones[k] / fs2_);
3000 for (int i = 0; i < settle + meas; ++i)
3001 {
3002 double x = 0.0;
3003 for (int k = 0; k < 7; ++k)
3004 x += std::sin(2.0 * std::numbers::pi * kRefTones[k] * i / fs2_ + k * 1.7);
3005 x *= kAmpPerTone;
3006 const double y = cal.processSample(x, st, kSagRef);
3007 if (i >= settle)
3008 for (int k = 0; k < 7; ++k)
3009 {
3010 auto& s1 = gs1[static_cast<size_t>(k)];
3011 auto& s2 = gs2[static_cast<size_t>(k)];
3012 const double s0 = y + gc[static_cast<size_t>(k)] * s1 - s2;
3013 s2 = s1; s1 = s0;
3014 }
3015 }
3016 std::array<double, 7> gainDb {};
3017 for (int k = 0; k < 7; ++k)
3018 {
3019 const double c = gc[static_cast<size_t>(k)] * 0.5;
3020 const double s1 = gs1[static_cast<size_t>(k)], s2 = gs2[static_cast<size_t>(k)];
3021 const double mag = std::sqrt(std::max(s1 * s1 + s2 * s2 - 2.0 * c * s1 * s2, 0.0))
3022 * 2.0 / meas;
3023 gainDb[static_cast<size_t>(k)] =
3024 20.0 * std::log10(std::max(mag / kAmpPerTone, 1e-9));
3025 }
3026
3027 // Flattening EQ from the band means, relative to the overall mean.
3028 double mean = 0.0;
3029 for (double g : gainDb) mean += g / 7.0;
3030 const double lo = 0.5 * (gainDb[0] + gainDb[1]) - mean;
3031 const double mid = (gainDb[2] + gainDb[3] + gainDb[4]) / 3.0 - mean;
3032 const double hi = 0.5 * (gainDb[5] + gainDb[6]) - mean;
3033
3034 std::array<BiquadCoeffs, 3> fc = {
3035 BiquadCoeffs::makeLowShelf(fs2_, 180.0, -lo),
3036 BiquadCoeffs::makePeak(fs2_, 800.0, 0.55, -mid),
3037 BiquadCoeffs::makeHighShelf(fs2_, 4500.0, -hi)
3038 };
3039 for (auto& lane : channels_)
3040 for (auto& ch : lane)
3041 ch->setFlattenCoeffs(st, fc);
3042
3043 // Phase 2: program gain vs DRIVE, on a chained scratch channel
3044 // with the flattener installed (the chain as it really sounds).
3045 // Each grid point gets a re-settle (bias/sag adapt to the new
3046 // level) before its measurement window. recompute() interpolates
3047 // this LUT, so the loudness link tracks the circuit's actual
3048 // compression - the fix for the level falling at high drive.
3049 ChannelState sweep(fs2_, loadTable_.get(), design_.get(), gridTable_.get());
3050 sweep.setToneControls(0.5, 0.5, 0.5);
3051 sweep.setFlattenCoeffs(st, fc);
3052 sweep.reset(kSagRef, st);
3053 const int settle2 = static_cast<int>(0.030 * fs2_);
3054 const int meas2 = static_cast<int>(0.030 * fs2_);
3055 int t = 0; // continuous tone phase across the whole sweep
3056 for (int kd = 0; kd < kDriveLutN; ++kd)
3057 {
3058 const double d = std::pow(10.0,
3059 (kDriveLutMinDb + kd * kDriveLutStepDb) / 20.0);
3060 double inSq = 0.0, outSq = 0.0;
3061 for (int i = 0; i < settle2 + meas2; ++i, ++t)
3062 {
3063 double x = 0.0;
3064 for (int k = 0; k < 7; ++k)
3065 x += std::sin(2.0 * std::numbers::pi * kRefTones[k] * t / fs2_ + k * 1.7);
3066 x *= kAmpPerTone;
3067 const double y = sweep.processSample(d * x, st, kSagRef);
3068 if (i >= settle2)
3069 {
3070 inSq += x * x;
3071 outSq += y * y;
3072 }
3073 }
3074 gProgLut_[static_cast<size_t>(st - 1)][static_cast<size_t>(kd)] =
3075 (outSq > 0.0 && inSq > 0.0) ? std::sqrt(outSq / inSq) : 1.0;
3076 }
3077 }
3078 }
3079
3080 // -- Members --------------------------------------------------------------------
3081 AudioSpec spec_ {};
3082 double sampleRate_ = 48000.0;
3083 double fs2_ = 96000.0;
3084 int numChannels_ = 0;
3085 int maxBlock_ = 0;
3086 std::atomic<bool> prepared_ { false };
3087 int latency_ = 0;
3088 int drySize_ = 1;
3089 int osFactor_ = 2;
3090 bool osAutomatic_ = false;
3092 OversamplingDryPath<T> dryPath_;
3093 AudioBuffer<T> dryScratch_;
3094 bool dryThroughFilters_ = false;
3095 int dryDelay_ = 0;
3096 static constexpr double kAutomaticInternalRate = 88200.0;
3097
3098 std::unique_ptr<LoadTable> loadTable_;
3099 std::unique_ptr<detail::TubePreampGridTable> gridTable_;
3100 GridModel gridModel_ = GridModel::Clamp;
3101 std::unique_ptr<detail::TubePreampCoreDesign> design_;
3102 std::unique_ptr<Oversampling<T>> oversampler_;
3103 std::array<std::vector<std::unique_ptr<ChannelState>>, 2> channels_;
3104
3105 std::vector<std::vector<T>> dryRing_;
3106 int dryPos_ = 0;
3107
3108 static constexpr int kDriveLutN = 13;
3109 static constexpr double kDriveLutMinDb = -12.0;
3110 static constexpr double kDriveLutStepDb = 4.0;
3111
3112 double hScale_ = 1.0;
3113 std::array<double, 2> mScale_ { 1.0, 1.0 };
3114 double sagR_ = 0.0;
3115 int numStagesActive_ = 1;
3117 std::array<std::array<double, kDriveLutN>, 2> gProgLut_ {
3118 { { 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 },
3119 { 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 } } };
3120 SmoothedValue<double> driveLogSmoother_;
3121 std::array<SmoothedValue<double>, 2> outputLogSmoothers_;
3122 std::array<std::vector<double>, 3> gainRamps_;
3123 std::array<std::vector<double>, 2> compensationScratch_;
3124 SmoothedValue<double> stageBlend_;
3125 std::vector<double> stageRamp_;
3126 SmoothedValue<double> sagSmoother_;
3127 std::vector<double> sagRamp_;
3128 int stageWarmupRemaining_ = 0;
3129 bool bothStagesActive_ = false;
3130 bool gainsInitialized_ = false;
3132 void runCabinet(AudioBufferView<T> buffer, int nCh, int nS) noexcept
3133 {
3134 const double target = cabinetOn_.load(std::memory_order_relaxed) ? 1.0 : 0.0;
3135 if (cabNow_ == 0.0 && target == 0.0) return;
3136 if (cabNow_ == 1.0 && target == 1.0)
3137 {
3138 cabinet_.processBlock(buffer.getSubView(0, nS));
3139 return;
3140 }
3141 if (cabNow_ == 0.0) cabinet_.reset(); // its memory is of another time
3142 const int n = std::min(nS, cabScratch_.getNumSamples());
3143 const int channels = std::min(nCh, cabScratch_.getNumChannels());
3144 for (int ch = 0; ch < channels; ++ch)
3145 std::copy_n(buffer.getChannel(ch), n, cabScratch_.getChannel(ch));
3146 cabinet_.processBlock(cabScratch_.toView().getSubView(0, n));
3147 double now = cabNow_;
3148 for (int i = 0; i < n; ++i)
3149 {
3150 now += std::clamp(target - now, -cabStep_, cabStep_);
3151 for (int ch = 0; ch < channels; ++ch)
3152 {
3153 T& x = buffer.getChannel(ch)[i];
3154 x = static_cast<T>(static_cast<double>(x) + now * (static_cast<double>(cabScratch_.getChannel(ch)[i]) - static_cast<double>(x)));
3155 }
3156 }
3157 cabNow_ = (n < nS) ? target : now;
3158 }
3159
3160 CabinetModel<T> cabinet_;
3161 std::atomic<bool> cabinetOn_ { false };
3162 AudioBuffer<T> cabScratch_;
3163 double cabNow_ = 0.0;
3164 double cabStep_ = 1.0 / 960.0;
3165
3166 T currentMix_ = T(1);
3167 T mixMaxStep_ = T(1.0 / 960.0);
3168
3169 std::atomic<T> driveDb_ { T(0) };
3170 std::atomic<T> treble_ { T(0.5) };
3171 std::atomic<T> bass_ { T(0.5) };
3172 std::atomic<T> middle_ { T(0.5) };
3173 std::atomic<T> sag_ { T(0.3) };
3174 std::atomic<int> stages_ { 1 };
3175 std::atomic<T> outputDb_ { T(0) };
3176 std::atomic<T> mix_ { T(1) };
3177 std::atomic<T> supplyNow_ { T(300) };
3178 std::atomic<bool> dirty_ { true };
3179};
3180
3181} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
A loudspeaker cabinet: colour filters, sparse reflections and two diffusers, with no latency.
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
Power-of-two oversampling processor with polyphase anti-aliasing.
static constexpr int factorForRate(double sampleRate, double minimumInternalRate=176400.0, int maxFactor=1<< kMaxStages) noexcept
The smallest factor that brings a host rate up to an internal rate.
Zero-allocation parameter smoother for real-time audio.
void setSmoothingType(SmoothingType type) noexcept
Sets the smoothing algorithm.
void reset(T value=T(0)) noexcept
Hard-resets both current and target states to a specific value.
T getNextValue() noexcept
Calculates and returns the next smoothed value.
T getCurrentValue() const noexcept
Returns the current internal value without advancing the state.
bool isSmoothing() const noexcept
Evaluates if the smoother is actively transitioning.
void setTargetValue(T newTarget) noexcept
Updates the target value. Safe to call continuously (e.g., from host automation).
void processBlock(std::span< T > buffer) noexcept
Computes a block of smoothed values into an output buffer.
void prepare(double sampleRate, double rampTimeMs=20.0) noexcept
Precalculates internal coefficients based on sample rate and timing.
Tolerant reader: missing keys yield defaults, unknown keys are skipped.
Definition StateBlob.h:171
float read(const char *key, float defaultValue) const
Reads a float, or defaultValue when the key is absent.
Definition StateBlob.h:214
bool isValid() const noexcept
Definition StateBlob.h:209
uint32_t processorId() const noexcept
Definition StateBlob.h:210
Serializes key/value parameters into a versioned blob.
Definition StateBlob.h:53
std::vector< uint8_t > blob() const
Finalizes and returns the blob.
Definition StateBlob.h:112
void write(const char *key, float value)
Writes a float parameter.
Definition StateBlob.h:71
One/two 12AX7 stages with sag and a WDF tone circuit.
Definition TubePreamp.h:856
void setAutomaticOversampling(bool on)
Lets the host rate choose the factor (SETUP THREAD ONLY, as setOversampling()).
T getBass() const noexcept
void setStages(int stages) noexcept
Number of triode stages (1 = clean/edge, 2 = high gain). RT-safe; the prepared latency does not chang...
T getSupplyVoltage() const noexcept
Effective B+ supply voltage of channel 0 (sag meter readout). During a stage transition,...
bool setState(const uint8_t *data, size_t size)
Restores parameters from a blob (tolerant; rejects foreign ids).
int getLatencySamples() const noexcept
Compatibility alias of getLatency(), in prepared-rate samples.
T getDrive() const noexcept
T getOutput() const noexcept
void processBlock(AudioBufferView< T > buffer) noexcept
Processes a block in-place. Pass-through until prepare() succeeds.
void setBass(T bass) noexcept
Bass control of the FMV stack [0, 1] (log-taper, like the original). Non-finite values are ignored.
void setMiddle(T middle) noexcept
Middle control of the FMV stack [0, 1]. Non-finite values are ignored.
void setGridModel(GridModel model)
Selects the grid model. SETUP THREAD ONLY, like setOversampling(): it rebuilds the circuits and re-ru...
CabinetModel< T > & getCabinet() noexcept
The cabinet model: its setters are safe from any thread.
Definition TubePreamp.h:995
int getLatency() const noexcept
Latency in prepared-rate samples added by the oversampler and the continuous core (0 at 1x = off); re...
T getTreble() const noexcept
void reset() noexcept
Re-settles every stage at its DC operating point. RT-safe.
Definition TubePreamp.h:957
T getMiddle() const noexcept
int getStages() const noexcept
void setTreble(T treble) noexcept
Treble control of the FMV stack [0, 1]. Non-finite values are ignored.
bool isCabinet() const noexcept
Whether the cabinet stage is on.
Definition TubePreamp.h:992
void setDrive(T db) noexcept
Input drive in dB [-12, +36]; level-compensated. Non-finite values are ignored.
T getSag() const noexcept
bool isOversamplingAutomatic() const noexcept
Whether the factor follows the host rate (setAutomaticOversampling()).
OversamplingMode
How the oversampler filters (see setOversamplingMode()).
@ LinearPhase
Linear-phase half-bands: the latency of the factor, the dry path a delay (default).
@ MinimumPhase
Elliptic allpass half-bands: a few samples of latency, the dry path through the same filters.
void setSag(T sag) noexcept
Supply sag depth [0, 1] (0 = stiff supply). Non-finite values are ignored.
T getMix() const noexcept
GridModel
How the stages model grid conduction (see setGridModel()).
void setOversampling(int factor)
Configures internal oversampling of the nonlinear circuit (visible, tunable and switchable off)....
GridModel getGridModel() const noexcept
The selected grid model.
void setMix(T mix) noexcept
Dry/wet mix [0, 1]; dry is latency-compensated and the mix is ramped over at least 20 ms....
void setOversamplingMode(OversamplingMode mode)
Chooses the oversampler's filters (SETUP THREAD ONLY, as setOversampling(): an active instance is pre...
void setOutput(T db) noexcept
Static output trim in dB [-24, +12]. Non-finite values are ignored.
std::vector< uint8_t > getState() const
Serializes the parameter state (setup/UI threads; allocates).
void prepare(const AudioSpec &spec)
Allocates both stage configurations per channel and runs the reference calibration....
Definition TubePreamp.h:864
OversamplingMode getOversamplingMode() const noexcept
The oversampler's filters (setOversamplingMode()).
int getOversamplingFactor() const noexcept
Active oversampling factor (1 = off, 2 = default).
void setCabinet(bool on) noexcept
Runs the wet signal through a loudspeaker cabinet (off by default).
Definition TubePreamp.h:989
constexpr int delay
Delay of the projected output behind the newest input, in samples.
constexpr int interval(const std::array< int, 7 > &deg, int degIdx, int skip) noexcept
Calculate semitone interval skipping 'skip' degrees in the scale.
Main namespace for the DSPark framework.
T moveTowards(T from, T to, T maxDelta) noexcept
Moves a value toward a target by at most a given distance.
Definition DspMath.h:137
constexpr uint32_t stateId(const char(&tag)[5]) noexcept
Builds a FOURCC processor id, e.g. dspark::stateId("COMP").
Definition StateBlob.h:672
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37
constexpr bool isValid() const noexcept
Checks if the specification contains valid, processable parameters.
Definition AudioSpec.h:71
int numChannels
Number of audio channels (e.g., 1 = mono, 2 = stereo).
Definition AudioSpec.h:58
int maxBlockSize
Maximum number of samples per processing block.
Definition AudioSpec.h:53
double sampleRate
Sample rate in Hz.
Definition AudioSpec.h:45
static BiquadCoeffs makePeak(double sampleRate, double freq, double Q, double gainDb) noexcept
Peak (parametric EQ) filter.
Definition Biquad.h:201
static BiquadCoeffs makeLowShelf(double sampleRate, double freq, double gainDb, double slope=1.0) noexcept
Low-shelf filter.
Definition Biquad.h:417
static BiquadCoeffs makeHighShelf(double sampleRate, double freq, double gainDb, double slope=1.0) noexcept
High-shelf filter.
Definition Biquad.h:447
double exactTerm(int k, double xi, double &derivative) const noexcept
double eval(double xi, double &derivative) const noexcept
double operator()(double xi) const noexcept