DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
TapeMachine.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
142#include "../Core/AudioBuffer.h"
143#include "../Core/AudioSpec.h"
144#include "../Core/Biquad.h"
145#include "../Core/DenormalGuard.h"
146#include "../Core/DryWetMixer.h"
147#include "../Core/DspMath.h"
148#include "../Core/FilterDesign.h"
149#include "../Core/Hysteresis.h"
150#include "../Core/NormalizedLadder.h"
151#include "../Core/Oversampling.h"
152#include "../Core/SimdOps.h"
153#include "../Core/StateBlob.h"
154#include "../Core/TapeTransport.h"
155
156#include <algorithm>
157#include <array>
158#include <atomic>
159#include <cmath>
160#include <cstddef>
161#include <cstdint>
162#include <memory>
163#include <numbers>
164#include <vector>
165
166namespace dspark {
167
174template <FloatType T>
176{
177public:
179 enum class Standard { NAB, CCIR };
180
182 enum class Speed { IPS_7_5, IPS_15, IPS_30, IPS_3_75 };
183
197 enum class Transport { Modulated, Speed };
198
200 enum class Mains { Hz50, Hz60 };
201
212
223 enum class TrackFormat { Half, Full, Quarter };
224
233
242 enum class HeadModel { Bump, Contour };
243
258 enum class Electronics { Ideal, Circuit };
259
260 // -- Lifecycle ---------------------------------------------------------------
261
271 void prepare(const AudioSpec& spec)
272 {
273 if (!spec.isValid()) return;
274 if (prepared_.load(std::memory_order_relaxed) && spec.sampleRate == spec_.sampleRate
275 && spec.numChannels == spec_.numChannels && spec.maxBlockSize != spec_.maxBlockSize)
276 {
277 spec_.maxBlockSize = spec.maxBlockSize;
278 return;
279 }
280 prepared_.store(false, std::memory_order_relaxed);
281 spec_ = spec;
282 sampleRate_ = spec.sampleRate;
283 mixMaxStep_ = static_cast<T>(1.0 / std::max(1.0, sampleRate_ * 0.02));
284 numChannels_ = spec.numChannels;
285 maxBlock_ = std::max(spec.maxBlockSize, 1);
286 if (osAutomatic_)
287 osRequested_ = Oversampling<T>::factorForRate(spec.sampleRate, kAutomaticInternalRate);
288 osFactor_ = osRequested_;
289 steps_ = stepsInUse(spec.sampleRate);
290
291 // The hysteresis core runs at the active oversampling factor (4x
292 // default) so the quarter-internal-rate AC bias carrier and its
293 // sidebands stay clear of the audio band. factor = 1 = OFF: no
294 // resampling and zero added latency; the carrier is then in-band.
295 // With four levels it takes two steps a sample from 44.1 to under 352.8 kHz.
296 const double osRate = sampleRate_ * static_cast<double>(osFactor_);
297 const double coreRate = osRate * static_cast<double>(steps_);
298 const double tolerance = fourLevel_ ? kFourLevelTolerance : kExactTolerance;
299 stepped_.assign(static_cast<size_t>(numChannels_), {});
300 calib_.setTolerance(tolerance);
301 calib2_.setTolerance(tolerance);
302 // With four levels the solver starts from the carrier's own period;
303 // two levels keep the exact solver of before, to compare.
304 const int period = fourLevel_ ? kCarrierPeriod : 0;
305 calib_.setPredictorPeriod(period);
306 calib2_.setPredictorPeriod(period);
307 if (osFactor_ > 1)
308 {
309 oversampler_ = std::make_unique<Oversampling<T>>(
313 oversampler_->prepare(spec);
314 }
315 else
316 {
317 oversampler_.reset();
318 }
319
320 // Push-pull pair per channel: +carrier and -carrier instances, output
321 // averaged. Odd-in-bias terms (the carrier, its 3rd harmonic fold and
322 // the loop's remanence DC) cancel exactly, as in the centre-tapped
323 // record-head circuits of real machines.
324 hysteresis_.assign(static_cast<size_t>(numChannels_), {});
325 hysteresisN_.assign(static_cast<size_t>(numChannels_), {});
326 for (auto& h : hysteresis_)
327 {
328 h.prepare(coreRate);
329 h.setTolerance(tolerance);
330 h.setPredictorPeriod(period);
331 h.setParameters(3.5e5, 2.2e4, 1.6e-3, 2.7e4, 0.17);
332 }
333 for (auto& h : hysteresisN_)
334 {
335 h.prepare(coreRate);
336 h.setTolerance(tolerance);
337 h.setPredictorPeriod(period);
338 h.setParameters(3.5e5, 2.2e4, 1.6e-3, 2.7e4, 0.17);
339 }
340
341 recordHF_.assign(static_cast<size_t>(numChannels_), {});
342 recordLF_.assign(static_cast<size_t>(numChannels_), {});
343 playHF_.assign(static_cast<size_t>(numChannels_), {});
344 playLF_.assign(static_cast<size_t>(numChannels_), {});
345 headBump_.assign(static_cast<size_t>(numChannels_), {});
346 overBiasLp_.assign(static_cast<size_t>(numChannels_), 0.0);
347 inputAc_.assign(static_cast<size_t>(numChannels_), {});
348 inputAcPole_ = std::exp(-2.0 * std::numbers::pi * kInputCouplingHz / sampleRate_);
349 recTrim_.assign(static_cast<size_t>(numChannels_), {});
350 playTrim_.assign(static_cast<size_t>(numChannels_), {});
351 ironLp_.assign(static_cast<size_t>(numChannels_), 0.0);
352 ironA_ = 1.0 - std::exp(-2.0 * std::numbers::pi * kIronCornerHz / sampleRate_);
353 resting_ = false;
354 wakeHold_ = 0;
355 const size_t channels = static_cast<size_t>(numChannels_);
356 hissHF_.assign(channels, {});
357 hissLF_.assign(channels, {});
358 xtHp_.assign(channels, {});
359 trPre_.assign(channels, {});
360 trPost_.assign(channels, {});
361 trMean_.assign(channels, 0.0);
362 asymMean_.assign(channels, 0.0);
363 recordHeld_.assign(channels, 0.0);
364 recordFall_ = std::exp(-1.0 / (kRecordPeakSeconds * sampleRate_ * static_cast<double>(std::max(1, osFactor_))));
365 wet_.assign(channels, 0.0);
366 headContour_.assign(channels, {});
367 recNet_.assign(channels, {});
368 playNet_.assign(channels, {});
369 {
370 // Channel bleed: a first-order high-pass at 10 kHz (its corner kept
371 // in place), scaled to unity at 1 kHz. Transformer branch: a
372 // one-pole low-pass at 60 Hz before the curve (flux follows
373 // voltage over frequency) and its inverse, capped at 4 kHz, after.
374 const double wc = 2.0 * sampleRate_ * std::tan(std::numbers::pi * std::min(10000.0, 0.45 * sampleRate_) / sampleRate_);
375 const ShelfSection hp = firstOrder(1.0, 0.0, 1.0, wc, sampleRate_);
376 for (auto& s : xtHp_) s = hp;
377 xtNorm_ = 1.0 / std::max(1e-9, shelfMagnitude(hp, 2.0 * std::numbers::pi * 1000.0 / sampleRate_));
378 const double w1 = 2.0 * std::numbers::pi * kTransformerCornerHz;
379 const double w2 = 2.0 * std::numbers::pi * std::min(4000.0, 0.45 * sampleRate_);
380 const ShelfSection pre = firstOrder(0.0, w1, 1.0, w1, sampleRate_);
381 const ShelfSection post = firstOrder(1.0 / w1, 1.0, 1.0 / w2, 1.0, sampleRate_);
382 for (auto& s : trPre_) s = pre;
383 for (auto& s : trPost_) s = post;
384 }
385
386 // AC-coupled playback amplifier: fixed 2nd-order 24 Hz high-pass
387 // (real machines roll off there; also blocks remanence DC).
388 outHp_.assign(static_cast<size_t>(numChannels_), {});
389 {
390 const auto hc = BiquadCoeffs::makeHighPass(sampleRate_, kOutputCouplingHz, 0.707);
391 for (auto& h : outHp_)
392 h = PeakSection { hc.b0, hc.b1, hc.b2, hc.a1, hc.a2, 0.0, 0.0 };
393 }
394
395 // Loss FIR: 63 taps at 48 kHz, scaled with the rate so the design
396 // grid keeps the same frequency spacing (a fixed 63 taps at 192 kHz
397 // smeared the reproduce-gap cut: -3.67 dB at 18 kHz instead of -1.57).
398 firLen_ = std::max(kFirLenAt48k,
399 64 * static_cast<int>(std::lround(sampleRate_ / 48000.0)) - 1);
400 firCenter_ = (firLen_ - 1) / 2;
401 firHalf_ = 1;
402 while (firHalf_ < firLen_ + 1) firHalf_ <<= 1;
403 firState_.assign(static_cast<size_t>(numChannels_),
404 std::vector<T>(static_cast<size_t>(2 * firHalf_), T(0)));
405 firPos_ = 0;
406 firTaps_.assign(static_cast<size_t>(firLen_), T(0));
407 {
408 const int grid = firLen_ + 1;
409 cosTable_.resize(static_cast<size_t>(grid));
410 for (int m = 0; m < grid; ++m)
411 cosTable_[static_cast<size_t>(m)] =
412 std::cos(2.0 * std::numbers::pi * m / static_cast<double>(grid));
413 designMags_.assign(static_cast<size_t>(grid / 2 + 1), 0.0);
414 designTaps_.assign(static_cast<size_t>(firLen_), 0.0);
415 }
416 overBiasX1_.assign(static_cast<size_t>(numChannels_), 0.0);
417
418 // Transport delay scales with the rate so the wow excursion (sized in
419 // samples at 48k, scaled by fs/48k) always fits under the centre. What
420 // the two steps of the core delay is taken off it: the latency stays
421 // that of one step.
422 delayCenter_ = std::max(96, static_cast<int>(96.0 * sampleRate_ / 48000.0)) - (steps_ > 1 ? kStepDelay / osFactor_ : 0);
423 int dsz = 1;
424 // Room for the speed transport too: its delay is the head distance
425 // over the speed, from a quarter to four times the centre.
426 while (dsz < 5 * delayCenter_ + 16) dsz <<= 1;
427 delayMask_ = dsz - 1;
428 delayRing_.assign(static_cast<size_t>(numChannels_),
429 std::vector<T>(static_cast<size_t>(dsz), T(0)));
430 delayPos_ = 0;
431
432 // Per-sample modulation smoothing constants (precomputed once).
433 const double dt = 1.0 / sampleRate_;
434 // The transport's noises run at the control rate (nextTransportMod()).
435 const double dControl = static_cast<double>(kTransportControl) * dt;
436 driftA_ = std::exp(-2.0 * std::numbers::pi * 0.10 * dControl);
437 scrapeA1_ = std::exp(-2.0 * std::numbers::pi * 90.0 * dControl);
438 scrapeA2_ = std::exp(-2.0 * std::numbers::pi * 40.0 * dControl);
439 // The speed transport: the head distance is the delay centre at the
440 // nominal speed.
441 tapeTransport_.prepare(sampleRate_, static_cast<double>(delayCenter_), speedIps_ > 0.0 ? speedIps_ : 15.0);
442 tapeTransport_.setLimits(3.0, static_cast<double>(delayMask_ - 4));
443 asymMeanA_ = std::exp(-2.0 * std::numbers::pi * 10.0 * dt / static_cast<double>(osFactor_));
444 trMeanA_ = std::exp(-2.0 * std::numbers::pi * 5.0 * dt);
445
446 latency_ = (oversampler_ ? oversampler_->getLatency() : 0) + firCenter_ + delayCenter_
447 + (steps_ > 1 ? kStepDelay / osFactor_ : 0); // the steps' delay, taken off the transport's
448 // Behind minimum-phase filters the dry copy crosses the same filters
449 // (in phase at every frequency) and the ring adds the rest of the delay.
450 dryThroughFilters_ = oversampler_ && osMode_ == OversamplingMode::MinimumPhase;
451 if (dryThroughFilters_) dryPath_.prepare(spec, *oversampler_);
452 dryScratch_.resize(numChannels_, maxBlock_);
453 dryDelay_ = latency_ - (dryThroughFilters_ ? oversampler_->getLatency() : 0);
454 drySize_ = 1;
455 while (drySize_ < latency_ + maxBlock_ + 1) drySize_ <<= 1;
456 dryRing_.assign(static_cast<size_t>(numChannels_),
457 std::vector<T>(static_cast<size_t>(drySize_), T(0)));
458 dryPos_ = 0;
459 for (auto* lead : { &dryInputLead_, &dryOutputLead_, &dryIronLead_ }) lead->prepare(sampleRate_, numChannels_);
460 dryInputLead_.setCorner(kInputCouplingHz);
461 dryOutputLead_.setCorner(detail::DryPhase::kButterworthShare * kOutputCouplingHz);
462
463 // The first calibration runs here, on the setup thread; later
464 // parameter changes calibrate incrementally inside processBlock().
465 dirty_.store(false, std::memory_order_relaxed);
466 formApplied_ = -1;
467 circuitActive_ = false;
468 speedTransportActive_ = false;
469 speedIps_ = 0.0;
470 recomputeLinear();
471 calActive_ = false;
472 calRestart_ = false;
473 startCalibration();
474 stepCalibration(calN_);
475 hSm_ = hScale_;
476 mSm_ = mScale_;
477 bSm_ = biasAmp_;
478 prepared_.store(true, std::memory_order_relaxed);
479 reset();
480 }
481
483 void reset() noexcept
484 {
485 if (!prepared_.load(std::memory_order_relaxed)) return;
486 clearMachine();
487 for (auto& d : dryRing_) std::fill(d.begin(), d.end(), T(0));
488 dryPath_.reset();
489 resting_ = false;
490 wakeHold_ = 0;
491 tapeTransport_.reset();
492 lastMod_ = 0.0;
493 aimRamps(true);
494 firPos_ = 0;
495 delayPos_ = 0;
496 dryPos_ = 0;
497 currentMix_ = mix_.load(std::memory_order_relaxed); // no fade-in on start
498 aimDryPhase(currentMix_);
499 for (auto* lead : { &dryInputLead_, &dryOutputLead_, &dryIronLead_ })
500 {
501 lead->reset();
502 lead->land();
503 }
504 biasPhase_ = 0;
505 modPhaseWow_ = 0.0;
506 modPhaseFlut_ = 0.0;
507 modPhaseFlut2_ = 0.0;
508 driftState_ = 0.0;
509 scrapeLp1_ = scrapeLp2_ = 0.0;
510 modFrom_ = modTo_ = 0.0;
511 modAt_ = 0;
512 humCos_ = 1.0;
513 humSin_ = 0.0;
514 humStepFor_ = -1.0;
515 rng_ = 0x1357feedu;
516 rngNoise_ = 0x2468beefu;
517 hSm_ = hScale_; // no fade-in on start; a running calibration continues
518 mSm_ = mScale_;
519 bSm_ = biasAmp_;
520 std::fill(recordHeld_.begin(), recordHeld_.end(), 0.0);
521 alignHpX_.fill(0.0);
522 alignHpY_.fill(0.0);
523 for (auto& p : recordPeak_) p.store(T(0), std::memory_order_relaxed);
524 if (oversampler_) oversampler_->reset();
525 }
526
527 // -- Parameters (thread-safe) ---------------------------------------------------
528
535 void setDrive(T driveDb) noexcept
536 {
537 if (!std::isfinite(driveDb)) return;
538 driveDb_.store(std::clamp(driveDb, T(-12), T(24)), std::memory_order_relaxed);
539 dirty_.store(true, std::memory_order_release);
540 }
541
551 void setBias(T bias) noexcept
552 {
553 if (!std::isfinite(bias)) return;
554 bias_.store(std::clamp(bias, T(0), T(1)), std::memory_order_relaxed);
555 dirty_.store(true, std::memory_order_release);
556 }
557
571 void setOversampling(int factor)
572 {
573 if (factor < 1 || factor > 16 || (factor & (factor - 1)) != 0) return;
574 if (factor == osRequested_ && !osAutomatic_) return;
575 osAutomatic_ = false;
576 osRequested_ = factor;
577 osFactor_ = factor;
578 if (prepared_.load(std::memory_order_relaxed))
579 prepare(spec_);
580 }
581
597 {
598 if (on == osAutomatic_) return;
599 osAutomatic_ = on;
600 if (on && prepared_.load(std::memory_order_relaxed))
601 prepare(spec_);
602 }
603
605 [[nodiscard]] bool isOversamplingAutomatic() const noexcept { return osAutomatic_; }
606
608 enum class BiasShape
609 {
610 TwoLevel,
611 FourLevel
612 };
613
630 {
631 const bool four = shape == BiasShape::FourLevel;
632 if (four == fourLevel_) return;
633 fourLevel_ = four;
634 if (prepared_.load(std::memory_order_relaxed))
635 prepare(spec_);
636 }
637
639 [[nodiscard]] BiasShape getBiasShape() const noexcept { return fourLevel_ ? BiasShape::FourLevel : BiasShape::TwoLevel; }
640
643 {
646 };
647
660 {
661 mode = static_cast<OversamplingMode>(std::clamp(static_cast<int>(mode), 0, 1));
662 if (mode == osMode_) return;
663 osMode_ = mode;
664 if (prepared_.load(std::memory_order_relaxed))
665 prepare(spec_);
666 }
667
669 [[nodiscard]] OversamplingMode getOversamplingMode() const noexcept { return osMode_; }
670
672 [[nodiscard]] int getOversamplingFactor() const noexcept { return osFactor_; }
673
676 void setSpeed(Speed s) noexcept
677 {
678 const int v = std::clamp(static_cast<int>(s),
679 static_cast<int>(Speed::IPS_7_5),
680 static_cast<int>(Speed::IPS_3_75));
681 speed_.store(v, std::memory_order_relaxed);
682 dirty_.store(true, std::memory_order_release);
683 }
684
687 void setStandard(Standard s) noexcept
688 {
689 const int v = std::clamp(static_cast<int>(s),
690 static_cast<int>(Standard::NAB),
691 static_cast<int>(Standard::CCIR));
692 standard_.store(v, std::memory_order_relaxed);
693 dirty_.store(true, std::memory_order_release);
694 }
695
698 void setLossEffects(T amount) noexcept
699 {
700 if (!std::isfinite(amount)) return;
701 loss_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
702 dirty_.store(true, std::memory_order_release);
703 }
704
707 void setHeadBump(T amount) noexcept
708 {
709 if (!std::isfinite(amount)) return;
710 headBumpAmt_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
711 dirty_.store(true, std::memory_order_release);
712 }
713
716 void setWowFlutter(T amount) noexcept
717 {
718 if (!std::isfinite(amount)) return;
719 wowFlutter_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
720 }
721
730 void setNoise(T dbfs) noexcept
731 {
732 if (!std::isfinite(dbfs)) return;
733 noiseDb_.store(std::clamp(dbfs, T(-200), T(-20)), std::memory_order_relaxed);
734 }
735
738 void setMix(T mix) noexcept
739 {
740 if (!std::isfinite(mix)) return;
741 mix_.store(std::clamp(mix, T(0), T(1)), std::memory_order_relaxed);
742 }
743
745 void setTransport(Transport t) noexcept
746 {
747 transport_.store(std::clamp(static_cast<int>(t), 0, 1), std::memory_order_relaxed);
748 }
749
757 void setHum(T dbfs, Mains mains = Mains::Hz50) noexcept
758 {
759 if (!std::isfinite(dbfs)) return;
760 humDb_.store(std::clamp(dbfs, T(-200), T(-20)), std::memory_order_relaxed);
761 mains_.store(std::clamp(static_cast<int>(mains), 0, 1), std::memory_order_relaxed);
762 }
763
772 void setChannelBleed(T dB) noexcept
773 {
774 if (std::isfinite(dB)) channelBleedDb_.store(std::clamp(dB, T(-200), T(-20)), std::memory_order_relaxed);
775 }
776
784 void setEvenHarmonics(T amount) noexcept
785 {
786 if (std::isfinite(amount)) evenHarmonics_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
787 }
788
802 void setOutputIron(T amount) noexcept
803 {
804 if (std::isfinite(amount)) outputIron_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
805 }
806
808 void setHeadModel(HeadModel m) noexcept
809 {
810 headModel_.store(std::clamp(static_cast<int>(m), 0, 1), std::memory_order_relaxed);
811 dirty_.store(true, std::memory_order_release);
812 }
813
816 {
817 electronics_.store(std::clamp(static_cast<int>(e), 0, 1), std::memory_order_relaxed);
818 dirty_.store(true, std::memory_order_release);
819 }
820
829 void setAlignment(T hfDb, T lfDb) noexcept
830 {
831 if (!std::isfinite(hfDb) || !std::isfinite(lfDb)) return;
832 alignHf_.store(std::clamp(hfDb, T(-6), T(6)), std::memory_order_relaxed);
833 alignLf_.store(std::clamp(lfDb, T(-6), T(6)), std::memory_order_relaxed);
834 dirty_.store(true, std::memory_order_release);
835 }
836
849 void setRecordEmphasis(T dB) noexcept
850 {
851 if (!std::isfinite(dB)) return;
852 recordEmphasis_.store(std::clamp(dB, T(-6), T(6)), std::memory_order_relaxed);
853 dirty_.store(true, std::memory_order_release);
854 }
856 [[nodiscard]] T getRecordEmphasis() const noexcept { return recordEmphasis_.load(std::memory_order_relaxed); }
857
866 [[nodiscard]] T getRecordPeak(int channel) const noexcept
867 {
868 if (channel < 0 || channel >= kMaxRecordPeaks) return T(0);
869 return recordPeak_[static_cast<size_t>(channel)].load(std::memory_order_relaxed);
870 }
880 void setAlignmentTolerance(T amount) noexcept
881 {
882 if (std::isfinite(amount)) alignTolerance_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
883 }
885 [[nodiscard]] T getAlignmentTolerance() const noexcept { return alignTolerance_.load(std::memory_order_relaxed); }
886
888 [[nodiscard]] T getRecordPeakDb(int channel) const noexcept { return gainToDecibels(getRecordPeak(channel)); }
889
892 {
893 formulation_.store(std::clamp(static_cast<int>(f), 0, 2), std::memory_order_relaxed);
894 dirty_.store(true, std::memory_order_release);
895 }
896
899 {
900 trackFormat_.store(std::clamp(static_cast<int>(f), 0, 2), std::memory_order_relaxed);
901 dirty_.store(true, std::memory_order_release);
902 }
903
915 void setCalibrationLevel(T dB) noexcept
916 {
917 if (!std::isfinite(dB)) return;
918 calLevel_.store(std::clamp(dB, T(0), T(9)), std::memory_order_relaxed);
919 dirty_.store(true, std::memory_order_release);
920 }
921
923 void setMonitor(Monitor m) noexcept
924 {
925 monitor_.store(std::clamp(static_cast<int>(m), 0, 2), std::memory_order_relaxed);
926 dirty_.store(true, std::memory_order_release);
927 }
928
929 [[nodiscard]] Transport getTransport() const noexcept { return static_cast<Transport>(transport_.load(std::memory_order_relaxed)); }
930 [[nodiscard]] T getHum() const noexcept { return humDb_.load(std::memory_order_relaxed); }
931 [[nodiscard]] Mains getMains() const noexcept { return static_cast<Mains>(mains_.load(std::memory_order_relaxed)); }
932 [[nodiscard]] T getChannelBleed() const noexcept { return channelBleedDb_.load(std::memory_order_relaxed); }
933 [[nodiscard]] T getEvenHarmonics() const noexcept { return evenHarmonics_.load(std::memory_order_relaxed); }
934 [[nodiscard]] T getOutputIron() const noexcept { return outputIron_.load(std::memory_order_relaxed); }
935 [[nodiscard]] HeadModel getHeadModel() const noexcept { return static_cast<HeadModel>(headModel_.load(std::memory_order_relaxed)); }
936 [[nodiscard]] Electronics getElectronics() const noexcept { return static_cast<Electronics>(electronics_.load(std::memory_order_relaxed)); }
937 [[nodiscard]] T getAlignmentHf() const noexcept { return alignHf_.load(std::memory_order_relaxed); }
938 [[nodiscard]] T getAlignmentLf() const noexcept { return alignLf_.load(std::memory_order_relaxed); }
939 [[nodiscard]] Formulation getFormulation() const noexcept { return static_cast<Formulation>(formulation_.load(std::memory_order_relaxed)); }
940 [[nodiscard]] TrackFormat getTrackFormat() const noexcept { return static_cast<TrackFormat>(trackFormat_.load(std::memory_order_relaxed)); }
941 [[nodiscard]] T getCalibrationLevel() const noexcept { return calLevel_.load(std::memory_order_relaxed); }
942 [[nodiscard]] Monitor getMonitor() const noexcept { return static_cast<Monitor>(monitor_.load(std::memory_order_relaxed)); }
943
944 [[nodiscard]] T getDrive() const noexcept { return driveDb_.load(std::memory_order_relaxed); }
945 [[nodiscard]] T getBias() const noexcept { return bias_.load(std::memory_order_relaxed); }
946 [[nodiscard]] Speed getSpeed() const noexcept
947 {
948 return static_cast<Speed>(speed_.load(std::memory_order_relaxed));
949 }
950 [[nodiscard]] Standard getStandard() const noexcept
951 {
952 return static_cast<Standard>(standard_.load(std::memory_order_relaxed));
953 }
954 [[nodiscard]] T getLossEffects() const noexcept { return loss_.load(std::memory_order_relaxed); }
955 [[nodiscard]] T getHeadBump() const noexcept { return headBumpAmt_.load(std::memory_order_relaxed); }
956 [[nodiscard]] T getWowFlutter() const noexcept { return wowFlutter_.load(std::memory_order_relaxed); }
957 [[nodiscard]] T getNoise() const noexcept { return noiseDb_.load(std::memory_order_relaxed); }
958 [[nodiscard]] T getMix() const noexcept { return mix_.load(std::memory_order_relaxed); }
959
962 [[nodiscard]] int getLatency() const noexcept { return latency_; }
963
965 [[nodiscard]] int getLatencySamples() const noexcept { return getLatency(); }
966
968 [[nodiscard]] std::vector<uint8_t> getState() const
969 {
970 StateWriter w(stateId("TAPE"), 1);
971 // Explicit float casts: the blob stores float, and with T = double the
972 // unqualified write(key, double) would be ambiguous (float/int32/bool).
973 w.write("drive", static_cast<float>(driveDb_.load(std::memory_order_relaxed)));
974 w.write("bias", static_cast<float>(bias_.load(std::memory_order_relaxed)));
975 w.write("speed", speed_.load(std::memory_order_relaxed));
976 w.write("standard", standard_.load(std::memory_order_relaxed));
977 w.write("loss", static_cast<float>(loss_.load(std::memory_order_relaxed)));
978 w.write("headBump", static_cast<float>(headBumpAmt_.load(std::memory_order_relaxed)));
979 w.write("wowFlutter", static_cast<float>(wowFlutter_.load(std::memory_order_relaxed)));
980 w.write("noise", static_cast<float>(noiseDb_.load(std::memory_order_relaxed)));
981 w.write("mix", static_cast<float>(mix_.load(std::memory_order_relaxed)));
982 w.write("oversampling", osRequested_);
983 w.write("biasShape", fourLevel_ ? 1 : 0);
984 w.write("oversamplingAuto", osAutomatic_);
985 w.write("oversamplingMode", static_cast<int32_t>(osMode_));
986 w.write("transport", transport_.load(std::memory_order_relaxed));
987 w.write("humDb", static_cast<float>(humDb_.load(std::memory_order_relaxed)));
988 w.write("mains", mains_.load(std::memory_order_relaxed));
989 w.write("channelBleed", static_cast<float>(channelBleedDb_.load(std::memory_order_relaxed)));
990 w.write("evenHarmonics", static_cast<float>(evenHarmonics_.load(std::memory_order_relaxed)));
991 w.write("outputIron", static_cast<float>(outputIron_.load(std::memory_order_relaxed)));
992 w.write("headModel", headModel_.load(std::memory_order_relaxed));
993 w.write("electronics", electronics_.load(std::memory_order_relaxed));
994 w.write("alignHf", static_cast<float>(alignHf_.load(std::memory_order_relaxed)));
995 w.write("alignLf", static_cast<float>(alignLf_.load(std::memory_order_relaxed)));
996 w.write("recordEmphasis", static_cast<float>(recordEmphasis_.load(std::memory_order_relaxed)));
997 w.write("alignTolerance", static_cast<float>(getAlignmentTolerance()));
998 w.write("formulation", formulation_.load(std::memory_order_relaxed));
999 w.write("trackFormat", trackFormat_.load(std::memory_order_relaxed));
1000 w.write("calibrationLevel", static_cast<float>(calLevel_.load(std::memory_order_relaxed)));
1001 w.write("monitor", monitor_.load(std::memory_order_relaxed));
1002 return w.blob();
1003 }
1004
1006 bool setState(const uint8_t* data, size_t size)
1007 {
1008 StateReader r(data, size);
1009 if (!r.isValid() || r.processorId() != stateId("TAPE")) return false;
1010 setDrive(static_cast<T>(r.read("drive", 0.0f)));
1011 setBias(static_cast<T>(r.read("bias", 0.5f)));
1012 setSpeed(static_cast<Speed>(r.read("speed", 1)));
1013 setStandard(static_cast<Standard>(r.read("standard", 0)));
1014 setLossEffects(static_cast<T>(r.read("loss", 0.5f)));
1015 setHeadBump(static_cast<T>(r.read("headBump", 0.5f)));
1016 setWowFlutter(static_cast<T>(r.read("wowFlutter", 0.15f)));
1017 setNoise(static_cast<T>(r.read("noise", -200.0f)));
1018 setMix(static_cast<T>(r.read("mix", 1.0f)));
1019 setTransport(static_cast<Transport>(r.read("transport", 0)));
1020 setHum(static_cast<T>(r.read("humDb", -200.0f)), static_cast<Mains>(r.read("mains", 0)));
1021 setChannelBleed(static_cast<T>(r.read("channelBleed", -200.0f)));
1022 setEvenHarmonics(static_cast<T>(r.read("evenHarmonics", 0.0f)));
1023 setOutputIron(static_cast<T>(r.read("outputIron", 0.0f)));
1024 setHeadModel(static_cast<HeadModel>(r.read("headModel", 0)));
1025 setElectronics(static_cast<Electronics>(r.read("electronics", 0)));
1026 setAlignment(static_cast<T>(r.read("alignHf", 0.0f)), static_cast<T>(r.read("alignLf", 0.0f)));
1027 setRecordEmphasis(static_cast<T>(r.read("recordEmphasis", 0.0f)));
1028 setAlignmentTolerance(static_cast<T>(r.read("alignTolerance", 0.0f)));
1029 setFormulation(static_cast<Formulation>(r.read("formulation", 0)));
1030 setTrackFormat(static_cast<TrackFormat>(r.read("trackFormat", 0)));
1031 setCalibrationLevel(static_cast<T>(r.read("calibrationLevel", 0.0f)));
1032 setMonitor(static_cast<Monitor>(r.read("monitor", 0)));
1033 // Default 4 = the historical fixed factor (older blobs restore 4x).
1034 setOversampling(r.read("oversampling", 4));
1035 setAutomaticOversampling(r.read("oversamplingAuto", false));
1036 setBiasShape(r.read("biasShape", 1) == 0 ? BiasShape::TwoLevel : BiasShape::FourLevel);
1037 setOversamplingMode(static_cast<OversamplingMode>(r.read("oversamplingMode", 0)));
1038 return true;
1039 }
1040
1041 // -- Processing -------------------------------------------------------------------
1042
1044 void processBlock(AudioBufferView<T> buffer) noexcept
1045 {
1046 if (!prepared_.load(std::memory_order_relaxed)) return;
1047 DenormalGuard guard;
1048
1049 const int nCh = std::min(buffer.getNumChannels(), numChannels_);
1050 const int nS = buffer.getNumSamples();
1051 if (nCh == 0 || nS == 0) return;
1052
1053 // Front-door non-finite guard: a single NaN/Inf input sample would
1054 // poison the recursive record/playback EQ, push-pull JA hysteresis,
1055 // loss-FIR ring, transport delay and over-bias/DC state PERMANENTLY -
1056 // the JA core mutes to exact silence forever (only reset() clears it,
1057 // not clean input). Replace bad samples with silence before they reach
1058 // any state, so a transient upstream glitch cannot mute the channel for
1059 // the rest of the stream.
1060 for (int ch = 0; ch < nCh; ++ch)
1061 {
1062 T* d = buffer.getChannel(ch);
1063 for (int i = 0; i < nS; ++i)
1064 if (!std::isfinite(d[i])) d[i] = T(0);
1065 }
1066
1067 // Acquire pairs with the setters' release stores so the recompute
1068 // always sees the values published before the flag. Linear stages
1069 // change at once; the drive makeup calibrates over the next blocks.
1070 if (dirty_.load(std::memory_order_relaxed)
1071 && dirty_.exchange(false, std::memory_order_acquire))
1072 {
1073 recomputeLinear();
1074 if (calActive_) calRestart_ = true;
1075 else startCalibration();
1076 }
1077
1078 for (int off = 0; off < nS; off += maxBlock_)
1079 processChunk(buffer.getSubView(off, std::min(maxBlock_, nS - off)), nCh);
1080 }
1081
1082private:
1083 void processChunk(AudioBufferView<T> buffer, int nCh) noexcept
1084 {
1085 const int nS = buffer.getNumSamples();
1086 const T mixTarget = mix_.load(std::memory_order_relaxed);
1087 const T mixStart = currentMix_;
1088 const double wfDepth = static_cast<double>(wowFlutter_.load(std::memory_order_relaxed));
1089 const bool speedTransport = transport_.load(std::memory_order_relaxed) == 1;
1090 if (speedTransport != speedTransportActive_)
1091 {
1092 // Into the speed model from where the modulated delay stands; back
1093 // to the modulated model at its own position.
1094 if (speedTransport)
1095 {
1096 tapeTransport_.setSpeedNow(speedIps_);
1097 tapeTransport_.syncDelay(static_cast<double>(delayCenter_) + lastMod_);
1098 }
1099 speedTransportActive_ = speedTransport;
1100 }
1101 const bool circuit = circuitActive_;
1102 aimRamps(false);
1103 if (hissOn() && hissNormDirty_) computeHissNorm();
1104 const bool hissActive = hiss_.active();
1105 const bool humActive = hum_.active();
1106 const bool xtActive = xt_.active();
1107 const bool trActive = tr_.active();
1108 const bool monitorMoving = monitorRamp_.now != 1.0 || monitorRamp_.target != 1.0;
1109 aimDryPhase(mixTarget);
1110 const double humStep = (mains_.load(std::memory_order_relaxed) == 1 ? 60.0 : 50.0) / sampleRate_;
1111 if (humStep != humStepFor_)
1112 {
1113 humStepFor_ = humStep;
1114 humRotCos_ = std::cos(2.0 * std::numbers::pi * humStep);
1115 humRotSin_ = std::sin(2.0 * std::numbers::pi * humStep);
1116 }
1117 {
1118 const double r = 1.0 / std::sqrt(humCos_ * humCos_ + humSin_ * humSin_);
1119 humCos_ *= r;
1120 humSin_ *= r;
1121 }
1122
1123 // 1. Dry snapshot for the latency-compensated mix (through the
1124 // oversampler's filters when they are minimum phase).
1125 if (dryThroughFilters_)
1126 {
1127 for (int ch = 0; ch < nCh; ++ch)
1128 std::copy_n(buffer.getChannel(ch), nS, dryScratch_.getChannel(ch));
1129 auto dryView = dryScratch_.toView().getSubView(0, nS);
1130 dryPath_.process(dryView);
1131 }
1132 for (int ch = 0; ch < nCh; ++ch)
1133 {
1134 const T* in = dryThroughFilters_ ? dryScratch_.getChannel(ch) : buffer.getChannel(ch);
1135 auto& dry = dryRing_[static_cast<size_t>(ch)];
1136 int dp = dryPos_;
1137 for (int i = 0; i < nS; ++i)
1138 {
1139 dry[static_cast<size_t>(dp)] = in[i];
1140 dp = (dp + 1) & (drySize_ - 1);
1141 }
1142 }
1143
1144 // At rest: with the mix settled on the dry side, or the source being
1145 // monitored, nothing of the machine is heard, so it does not run. The
1146 // dry ring keeps its place and a pending calibration goes on.
1147 if ((mixTarget == T(0) && mixStart == T(0)) || (monitorRamp_.now == 0.0 && monitorRamp_.target == 0.0))
1148 {
1149 for (int i = 0; i < nS; ++i)
1150 {
1151 const double inTurn = dryInputLead_.advance(), outTurn = dryOutputLead_.advance(), ironTurn = dryIronLead_.advance();
1152 const int at = (dryPos_ + i - dryDelay_) & (drySize_ - 1);
1153 for (int ch = 0; ch < nCh; ++ch)
1154 buffer.getChannel(ch)[i] = turnDry(ch, dryRing_[static_cast<size_t>(ch)][static_cast<size_t>(at)], inTurn, outTurn, ironTurn);
1155 }
1156 dryPos_ = (dryPos_ + nS) & (drySize_ - 1);
1157 if (calActive_) stepCalibration(nS * osFactor_ * steps_);
1158 resting_ = true;
1159 return;
1160 }
1161 if (resting_)
1162 {
1163 // Back from rest: the machine's memory is of another time. It
1164 // starts from rest and runs unheard until its own latency has
1165 // passed; then the mix (or the monitor) fades it in.
1166 clearMachine();
1167 hSm_ = hScale_;
1168 mSm_ = mScale_;
1169 bSm_ = biasAmp_;
1170 wakeHold_ = latency_ + 1;
1171 resting_ = false;
1172 }
1173 const int warm = std::min(wakeHold_, nS);
1174 wakeHold_ -= warm;
1175
1176 // 1b. The line input is AC coupled, as a machine's is: DC and the
1177 // slowest drift never reach the tape, where they would lean the loop
1178 // to one side (even harmonics that no later stage removes). Two
1179 // one-pole high-passes in series: critically damped, no overshoot; in
1180 // double, the difference taken first so that a constant cancels
1181 // exactly. Then the record side of the emphasis trim.
1182 {
1183 const double p = inputAcPole_, g = 0.5 * (1.0 + p);
1184 for (int ch = 0; ch < nCh; ++ch)
1185 {
1186 T* d = buffer.getChannel(ch);
1187 auto& s = inputAc_[static_cast<size_t>(ch)];
1188 auto& trim = recTrim_[static_cast<size_t>(ch)];
1189 for (int i = 0; i < nS; ++i)
1190 {
1191 const double x = static_cast<double>(d[i]);
1192 const double y1 = g * (x - s[0]) + p * s[1];
1193 s[0] = x;
1194 s[1] = y1;
1195 const double y2 = g * (y1 - s[2]) + p * s[3];
1196 s[2] = y1;
1197 s[3] = y2;
1198 d[i] = static_cast<T>(trim.process(y2));
1199 }
1200 }
1201 }
1202
1203 // 2. Record EQ (emphasis) at base rate (the circuit runs its record
1204 // network at the internal rate instead).
1205 if (!circuit)
1206 {
1207 for (int ch = 0; ch < nCh; ++ch)
1208 {
1209 T* d = buffer.getChannel(ch);
1210 auto& hf = recordHF_[static_cast<size_t>(ch)];
1211 auto& lf = recordLF_[static_cast<size_t>(ch)];
1212 for (int i = 0; i < nS; ++i)
1213 d[i] = static_cast<T>(hf.process(lf.process(static_cast<double>(d[i]))));
1214 }
1215 }
1216
1217 // 3. Push-pull AC-bias hysteresis at 4x. One shared carrier phase for
1218 // all channels (a machine has a single bias oscillator); each channel
1219 // runs a +carrier and a -carrier JA instance and averages them, which
1220 // cancels every odd-in-bias term exactly (carrier, its folded 3rd
1221 // harmonic, remanence DC) like a centre-tapped record head.
1222 {
1223 const bool osOn = (oversampler_ != nullptr);
1224 auto osView = osOn ? oversampler_->upsample(buffer) : buffer;
1225 const int osN = osView.getNumSamples();
1226 const int phaseStart = biasPhase_;
1227 // Geometric ramps of the calibrated set (drive, makeup, bias):
1228 // the pair spans orders of magnitude, so power-law interpolation
1229 // keeps it on its calibration curve (as in TransformerModel).
1230 double hRat = 1.0, mRat = 1.0, bRat = 1.0;
1231 double hEnd = hSm_, mEnd = mSm_, bEnd = bSm_;
1232 if (osN > 0 && (hSm_ != hScale_ || mSm_ != mScale_ || bSm_ != biasAmp_))
1233 {
1234 const double kSm = 1.0 - std::exp(-static_cast<double>(osN)
1235 / (kGainRampSeconds * sampleRate_ * static_cast<double>(osFactor_)));
1236 const auto glide = [kSm](double from, double to) noexcept
1237 {
1238 const double e = from * std::pow(to / from, kSm);
1239 return std::abs(std::log(e / to)) < 1e-9 ? to : e;
1240 };
1241 hEnd = glide(hSm_, hScale_);
1242 mEnd = glide(mSm_, mScale_);
1243 bEnd = glide(bSm_, biasAmp_);
1244 const double inv = 1.0 / static_cast<double>(osN);
1245 hRat = std::pow(hEnd / hSm_, inv);
1246 mRat = std::pow(mEnd / mSm_, inv);
1247 bRat = std::pow(bEnd / bSm_, inv);
1248 }
1249 const bool ramping = hRat != 1.0 || mRat != 1.0 || bRat != 1.0;
1250 const bool alignOn = updateAlignment(nCh);
1251 const bool asymActive = asym_.active();
1252 LinearRamp asymAfter = asym_;
1253 for (int ch = 0; ch < nCh; ++ch)
1254 {
1255 T* d = osView.getChannel(ch);
1256 auto& hp = hysteresis_[static_cast<size_t>(ch)];
1257 auto& hn = hysteresisN_[static_cast<size_t>(ch)];
1258 auto& stepped = stepped_[static_cast<size_t>(ch)];
1259 auto& rec = recNet_[static_cast<size_t>(ch)];
1260 auto& play = playNet_[static_cast<size_t>(ch)];
1261 double& mean = asymMean_[static_cast<size_t>(ch)];
1262 LinearRamp asym = asym_;
1263 double inScale = hSm_, mS = mSm_, B = bSm_;
1264 int phase = phaseStart;
1265 double held = recordHeld_[static_cast<size_t>(ch)];
1266 const double biasTrim = alignOn && ch < kMaxAligned ? alignBias_[static_cast<size_t>(ch)] : 1.0;
1267 for (int i = 0; i < osN; ++i)
1268 {
1269 if (ramping)
1270 {
1271 inScale *= hRat;
1272 mS *= mRat;
1273 B *= bRat;
1274 }
1275 double xs = static_cast<double>(d[i]);
1276 if (circuit) xs = rec[1].processSample(rec[0].processSample(xs, 0), 0);
1277 if (asymActive)
1278 {
1279 // Even term less its running mean: no DC reaches the tape.
1280 const double square = xs * xs;
1281 mean = asymMeanA_ * mean + (1.0 - asymMeanA_) * square;
1282 xs += asym.next() * kAsymmetryShare * (square - mean);
1283 }
1284 const double x = inScale * xs;
1285 held = std::max(std::abs(x), held * recordFall_);
1286 double pair;
1287 if (steps_ > 1)
1288 {
1289 pair = twoSteps(stepped, hp, hn, x, alignOn ? B * biasTrim : B, phase);
1290 phase = (phase + 2) & 7;
1291 }
1292 else
1293 {
1294 const double c = carrier(alignOn ? B * biasTrim : B, biasNominal_, phase);
1295 phase = (phase + 1) & 7;
1296 const double mp = static_cast<double>(hp.processSample(static_cast<T>(x + c)));
1297 const double mn = static_cast<double>(hn.processSample(static_cast<T>(x - c)));
1298 pair = mp + mn;
1299 }
1300 double out = (mS * 0.5) * pair;
1301 if (circuit) out = play[1].processSample(play[0].processSample(out, 0), 0);
1302 d[i] = static_cast<T>(out);
1303 }
1304 asymAfter = asym;
1305 if (!std::isfinite(held)) held = 0.0;
1306 recordHeld_[static_cast<size_t>(ch)] = held;
1307 if (ch < kMaxRecordPeaks)
1308 recordPeak_[static_cast<size_t>(ch)].store(static_cast<T>(held / kRecordFullScale), std::memory_order_relaxed);
1309 }
1310 if (nCh > 0) asym_ = asymAfter;
1311 if (circuit)
1312 for (int ch = 0; ch < nCh; ++ch)
1313 for (int s = 0; s < 2; ++s)
1314 {
1315 recNet_[static_cast<size_t>(ch)][static_cast<size_t>(s)].advanceRamp(osN);
1316 playNet_[static_cast<size_t>(ch)][static_cast<size_t>(s)].advanceRamp(osN);
1317 }
1318 hSm_ = hEnd;
1319 mSm_ = mEnd;
1320 bSm_ = bEnd;
1321 biasPhase_ = (phaseStart + osN * steps_) & 7;
1322 // Advance a pending makeup calibration by as many steps of the
1323 // core as this block has: bounded work per callback.
1324 if (calActive_) stepCalibration(osN * steps_);
1325 if (osOn) oversampler_->downsample(buffer);
1326 }
1327
1328 // The over-bias low-pass starts from the signal it receives, not from
1329 // rest: switching it on with a zero state stepped the output.
1330 const bool overBiasStart = overBiasOn_ && !overBiasActive_;
1331 overBiasActive_ = overBiasOn_;
1332
1333 // 4-6. Per frame: hiss onto the tape, loss FIR and head, transport,
1334 // playback EQ, over-bias, output coupling and transformer per channel;
1335 // then the channel bleed, hum, monitor and mix across the channels.
1336 for (int i = 0; i < nS; ++i)
1337 {
1338 // One shared transport per frame (all channels move together,
1339 // like tape past a single capstan).
1340 double readPos;
1341 if (speedTransport)
1342 {
1343 readPos = tapeTransport_.next(wfDepth);
1344 }
1345 else
1346 {
1347 lastMod_ = nextTransportMod(wfDepth);
1348 readPos = static_cast<double>(delayCenter_) + lastMod_;
1349 }
1350 const auto readInt = static_cast<int>(std::floor(readPos));
1351 const T frac = static_cast<T>(readPos - readInt);
1352 const double hissAmp = hissActive ? hiss_.next() * hissNorm_ * kUniformToUnitRms : 0.0;
1353 const double trShare = trActive ? tr_.next() : 0.0;
1354
1355 for (int ch = 0; ch < nCh; ++ch)
1356 {
1357 T* d = buffer.getChannel(ch);
1358 T in = d[i];
1359
1360 // Hiss is magnetic noise on the tape: it is read through the
1361 // head losses and the reproduce de-emphasis (own RNG stream:
1362 // enabling it must not change the transport's realisation).
1363 if (hissActive)
1364 {
1365 rngNoise_ = rngNoise_ * 1664525u + 1013904223u;
1366 double n1 = (static_cast<double>(rngNoise_ >> 8) / 8388608.0 - 1.0) * hissAmp;
1367 if (circuit)
1368 n1 = hissLF_[static_cast<size_t>(ch)].process(hissHF_[static_cast<size_t>(ch)].process(n1));
1369 in += static_cast<T>(n1);
1370 }
1371
1372 // Loss FIR (linear phase) on a per-channel mirrored ring.
1373 auto& fir = firState_[static_cast<size_t>(ch)];
1374 fir[static_cast<size_t>(firPos_)] = in;
1375 fir[static_cast<size_t>(firPos_ + firHalf_)] = in; // mirrored
1376 const T* win = &fir[static_cast<size_t>(firPos_ + firHalf_ - (firLen_ - 1))];
1377 T y = simd::dotProduct(firTaps_.data(), win, firLen_);
1378
1379 // Head bump resonance, or the contour chain.
1380 if (contourActive_)
1381 for (auto& s : headContour_[static_cast<size_t>(ch)]) y = s.process(y);
1382 else
1383 y = headBump_[static_cast<size_t>(ch)].process(y);
1384
1385 // Transport fractional delay: interpolate at t - readInt -
1386 // frac, between p1 = x(t-readInt) and p2 = x(t-readInt-1).
1387 auto& dl = delayRing_[static_cast<size_t>(ch)];
1388 dl[static_cast<size_t>(delayPos_)] = y;
1389 const int base = delayPos_ - readInt;
1390 const int dm = delayMask_;
1391 const T p0 = dl[static_cast<size_t>((base + 1) & dm)];
1392 const T p1 = dl[static_cast<size_t>(base & dm)];
1393 const T p2 = dl[static_cast<size_t>((base - 1) & dm)];
1394 const T p3 = dl[static_cast<size_t>((base - 2) & dm)];
1395 T w;
1396 if (speedTransport)
1397 {
1398 // Four-point Lagrange (nodes -1, 0, 1, 2).
1399 const T f = frac;
1400 const T fm1 = f - T(1), fm2 = f - T(2), fp1 = f + T(1);
1401 w = -f * fm1 * fm2 * T(1.0 / 6.0) * p0 + fp1 * fm1 * fm2 * T(0.5) * p1
1402 - fp1 * f * fm2 * T(0.5) * p2 + fp1 * f * fm1 * T(1.0 / 6.0) * p3;
1403 }
1404 else
1405 {
1406 // Catmull-Rom.
1407 w = p1 + T(0.5) * frac * (p2 - p0
1408 + frac * (T(2) * p0 - T(5) * p1 + T(4) * p2 - p3
1409 + frac * (T(3) * (p1 - p2) + p3 - p0)));
1410 }
1411
1412 // Playback EQ (exact inverse de-emphasis; the circuit ran its
1413 // reproduce network before the downsampler).
1414 if (!circuit)
1415 w = static_cast<T>(playLF_[static_cast<size_t>(ch)].process(
1416 playHF_[static_cast<size_t>(ch)].process(static_cast<double>(w))));
1417 // The reproduce side of the emphasis trim (the tape's hiss crosses it too).
1418 w = static_cast<T>(playTrim_[static_cast<size_t>(ch)].process(static_cast<double>(w)));
1419 if (alignActive_)
1420 {
1421 // The channel's own treble (a first-order shelf) and level.
1422 const auto c = static_cast<size_t>(ch);
1423 const double xin = static_cast<double>(w);
1424 const double hp = alignHpA_ * (alignHpY_[c] + xin - alignHpX_[c]);
1425 alignHpX_[c] = xin;
1426 alignHpY_[c] = hp;
1427 w = static_cast<T>(alignLevel_[c] * (xin + alignShelf_[c] * hp));
1428 }
1429
1430 // Over-bias self-erasure: wider recording zone partially
1431 // erases short wavelengths (first-order low-pass engaged above
1432 // nominal bias only; identity at or below nominal). Its zero
1433 // matches the analog magnitude at Nyquist, so the roll-off is
1434 // the same at every rate (the plain one-pole fell 4 dB short
1435 // at 18 kHz at 48 kHz).
1436 if (overBiasOn_)
1437 {
1438 auto& lp = overBiasLp_[static_cast<size_t>(ch)];
1439 auto& x1 = overBiasX1_[static_cast<size_t>(ch)];
1440 const double xin = static_cast<double>(w);
1441 if (overBiasStart && i == 0) { lp = xin; x1 = xin; }
1442 lp = obB0_ * xin + obB1_ * x1 + obP_ * lp;
1443 x1 = xin;
1444 w = static_cast<T>(lp);
1445 }
1446
1447 // AC-coupled playback amplifier (2nd-order 24 Hz high-pass:
1448 // subsonic/DC roll-off of the real hardware).
1449 w = outHp_[static_cast<size_t>(ch)].process(w);
1450
1451 // Output transformer branch: always running, added by its share.
1452 {
1453 const double wd = static_cast<double>(w);
1454 const double u = trPre_[static_cast<size_t>(ch)].process(wd);
1455 double& m = trMean_[static_cast<size_t>(ch)];
1456 m = trMeanA_ * m + (1.0 - trMeanA_) * u * u;
1457 const double bent = trPost_[static_cast<size_t>(ch)].process(
1458 kTransformerEven * (u * u - m) - kTransformerOdd * u * u * u);
1459 // The iron's low end: a low-pass that always runs, taken
1460 // off by the same share (a first-order high-pass at the
1461 // full amount). What DC the even term leaves goes with it.
1462 double& low = ironLp_[static_cast<size_t>(ch)];
1463 const double sum = trShare > 0.0 ? wd + trShare * bent : wd;
1464 low += ironA_ * (sum - low);
1465 if (trShare > 0.0) w = static_cast<T>(sum - trShare * low);
1466 }
1467 wet_[static_cast<size_t>(ch)] = static_cast<double>(w);
1468 }
1469
1470 if (xtActive)
1471 {
1472 const double g = xt_.next();
1473 for (int ch = 0; ch + 1 < nCh; ch += 2)
1474 {
1475 const double a = wet_[static_cast<size_t>(ch)], b = wet_[static_cast<size_t>(ch + 1)];
1476 const double fromA = xtHp_[static_cast<size_t>(ch)].process(a);
1477 const double fromB = xtHp_[static_cast<size_t>(ch + 1)].process(b);
1478 wet_[static_cast<size_t>(ch)] = a + g * fromB;
1479 wet_[static_cast<size_t>(ch + 1)] = b + g * fromA;
1480 }
1481 }
1482 if (humActive)
1483 {
1484 const double amp = hum_.next();
1485 // A rotation per sample (its second harmonic 2 sin cos), the
1486 // radius held on the circle every block.
1487 const double s = humSin_ * humRotCos_ + humCos_ * humRotSin_;
1488 humCos_ = humCos_ * humRotCos_ - humSin_ * humRotSin_;
1489 humSin_ = s;
1490 const double h = amp * kHumNorm * (humSin_ + humSin_ * humCos_);
1491 for (int ch = 0; ch < nCh; ++ch) wet_[static_cast<size_t>(ch)] += h;
1492 }
1493
1494 // Latency-compensated monitor and mix.
1495 // While the machine warms up after a rest the dry side alone is
1496 // heard, and the mix and the monitor wait for it.
1497 const double monitor = i < warm ? 0.0 : (monitorMoving ? monitorRamp_.next() : 1.0);
1498 const T mixVal = moveTowards(mixStart, mixTarget, mixMaxStep_ * static_cast<T>(std::max(0, i + 1 - warm)));
1499 const double inTurn = dryInputLead_.advance(), outTurn = dryOutputLead_.advance(), ironTurn = dryIronLead_.advance();
1500 const bool wetAlone = mixVal == T(1) && monitor == 1.0;
1501 for (int ch = 0; ch < nCh; ++ch)
1502 {
1503 T* d = buffer.getChannel(ch);
1504 const auto& dry = dryRing_[static_cast<size_t>(ch)];
1505 const int dryIdx = (dryPos_ + i - dryDelay_) & (drySize_ - 1);
1506 const T rawDry = dry[static_cast<size_t>(dryIdx)];
1507 const T turned = turnDry(ch, rawDry, inTurn, outTurn, ironTurn);
1508 const T drySample = wetAlone ? rawDry : turned;
1509 T w = static_cast<T>(wet_[static_cast<size_t>(ch)]);
1510 if (monitor != 1.0)
1511 w = static_cast<T>(static_cast<double>(drySample)
1512 + (static_cast<double>(w) - static_cast<double>(drySample)) * monitor);
1513 d[i] = drySample + (w - drySample) * mixVal;
1514 }
1515
1516 firPos_ = (firPos_ + 1) & (firHalf_ - 1);
1517 delayPos_ = (delayPos_ + 1) & delayMask_;
1518 }
1519 dryPos_ = (dryPos_ + nS) & (drySize_ - 1);
1520 currentMix_ = moveTowards(mixStart, mixTarget, mixMaxStep_ * static_cast<T>(nS - warm));
1521 }
1522
1527 void aimDryPhase(T mixTarget) noexcept
1528 {
1529 const bool turn = mixTarget > T(0) && monitor_.load(std::memory_order_relaxed) != 2;
1530 const double iron = static_cast<double>(outputIron_.load(std::memory_order_relaxed));
1531 dryInputLead_.aim(turn);
1532 dryOutputLead_.aim(turn);
1533 // The iron takes off a share of a one-pole low-pass: an all-pass at
1534 // half that share of its corner leads by as much.
1535 dryIronLead_.setCorner(0.5 * kIronCornerHz * std::max(iron, 0.05));
1536 dryIronLead_.aim(turn && iron >= 0.05);
1537 }
1538
1540 [[nodiscard]] T turnDry(int channel, T x, double inTurn, double outTurn, double ironTurn) noexcept
1541 {
1542 return dryIronLead_.processSample(channel,
1543 dryOutputLead_.processSample(channel, dryInputLead_.processSample(channel, x, inTurn), outTurn), ironTurn);
1544 }
1545
1553 [[nodiscard]] int stepsInUse(double rate) const noexcept
1554 {
1555 const bool whole = osFactor_ == 1 || osFactor_ == 2 || osFactor_ == 4;
1556 const double internal = rate * static_cast<double>(osFactor_);
1557 return fourLevel_ && whole && 4.0 * internal > 0.999999 * kAutomaticInternalRate && internal < 0.999999 * kFourLevelInternalRate ? 2 : 1;
1558 }
1559
1561 struct Stepped
1562 {
1563 double in[3] {};
1564 double even[5] {};
1565 double odd[3] {};
1566 };
1567
1576 [[nodiscard]] double twoSteps(Stepped& s, Hysteresis<T>& hp, Hysteresis<T>& hn, double x, double amplitude, int phase) const noexcept
1577 {
1578 const auto solve = [&](double field, int at) noexcept
1579 {
1580 const double c = carrier(amplitude, biasNominal_, at);
1581 return static_cast<double>(hp.processSample(static_cast<T>(field + c)))
1582 + static_cast<double>(hn.processSample(static_cast<T>(field - c)));
1583 };
1584 const double first = (9.0 * (s.in[0] + s.in[1]) - (x + s.in[2])) * 0.0625;
1585 const double second = s.in[0];
1586 s.in[2] = s.in[1];
1587 s.in[1] = s.in[0];
1588 s.in[0] = x;
1589
1590 const double a = solve(first, phase);
1591 const double out = (3.0 * (a + s.even[4]) - 25.0 * (s.even[0] + s.even[3]) + 150.0 * (s.even[1] + s.even[2])) * (1.0 / 512.0)
1592 + 0.5 * s.odd[2];
1593 const double b = solve(second, (phase + 1) & 7);
1594 s.even[4] = s.even[3];
1595 s.even[3] = s.even[2];
1596 s.even[2] = s.even[1];
1597 s.even[1] = s.even[0];
1598 s.even[0] = a;
1599 s.odd[2] = s.odd[1];
1600 s.odd[1] = s.odd[0];
1601 s.odd[0] = b;
1602 return out;
1603 }
1604
1611 [[nodiscard]] double carrier(double amplitude, double nominal, int phase) const noexcept
1612 {
1613 const double sign = kBiasTable[static_cast<size_t>(phase)];
1614 if (!fourLevel_) return amplitude * sign;
1615 return sign * ((phase & 1) ? kOuterLevel * amplitude : kInnerLevel * std::min(amplitude, nominal));
1616 }
1617
1619 struct LinearRamp
1620 {
1621 double now = 0.0, target = 0.0, step = 0.0;
1622
1623 void aim(double to, double samples) noexcept
1624 {
1625 if (to == target) return;
1626 target = to;
1627 step = std::abs(to - now) / std::max(1.0, samples);
1628 }
1629 [[nodiscard]] double next() noexcept
1630 {
1631 if (now != target)
1632 now = (now < target) ? std::min(target, now + step) : std::max(target, now - step);
1633 return now;
1634 }
1635 [[nodiscard]] bool active() const noexcept { return now != 0.0 || target != 0.0; }
1636 };
1637
1638 [[nodiscard]] bool hissOn() const noexcept { return noiseDb_.load(std::memory_order_relaxed) > T(-120); }
1639
1641 void aimRamps(bool land) noexcept
1642 {
1643 const double fs = sampleRate_;
1644 // Hiss: the setting, less what the track width, the formulation and
1645 // the operating level take off it against the signal.
1646 double hiss = 0.0;
1647 if (hissOn())
1648 {
1649 static constexpr double kTrackWidthMm[3] = { 2.0, 6.3, 1.0 };
1650 const int track = std::clamp(trackFormat_.load(std::memory_order_relaxed), 0, 2);
1651 const double offset = 10.0 * std::log10(kTrackWidthMm[0] / kTrackWidthMm[static_cast<size_t>(track)])
1652 + formulationOf(formulation_.load(std::memory_order_relaxed)).hissDb
1653 - static_cast<double>(calLevel_.load(std::memory_order_relaxed));
1654 hiss = std::pow(10.0, (static_cast<double>(noiseDb_.load(std::memory_order_relaxed)) + offset) / 20.0);
1655 }
1656 const T humDb = humDb_.load(std::memory_order_relaxed);
1657 const double hum = humDb > T(-120) ? std::pow(10.0, static_cast<double>(humDb) / 20.0) : 0.0;
1658 const T xtDb = channelBleedDb_.load(std::memory_order_relaxed);
1659 const double xt = xtDb > T(-120) ? std::pow(10.0, static_cast<double>(xtDb) / 20.0) * xtNorm_ : 0.0;
1660 if (xt > 0.0 && !xt_.active())
1661 for (auto& s : xtHp_) s.clear();
1662 const double monitor = monitor_.load(std::memory_order_relaxed) == 2 ? 0.0 : 1.0;
1663 hiss_.aim(hiss, 0.05 * fs);
1664 hum_.aim(hum, 0.05 * fs);
1665 xt_.aim(xt, 0.05 * fs);
1666 tr_.aim(static_cast<double>(outputIron_.load(std::memory_order_relaxed)), 0.02 * fs);
1667 asym_.aim(static_cast<double>(evenHarmonics_.load(std::memory_order_relaxed)), 0.02 * fs * static_cast<double>(osFactor_));
1668 monitorRamp_.aim(monitor, 0.02 * fs);
1669 if (land)
1670 {
1671 hiss_.now = hiss_.target;
1672 hum_.now = hum_.target;
1673 xt_.now = xt_.target;
1674 tr_.now = tr_.target;
1675 asym_.now = asym_.target;
1676 monitorRamp_.now = monitorRamp_.target;
1677 }
1678 }
1679
1686 void computeHissNorm() noexcept
1687 {
1688 hissNormDirty_ = false;
1689 if (numChannels_ <= 0) return;
1690 constexpr int kGrid = 256;
1691 double power = 0.0;
1692 for (int k = 0; k < kGrid; ++k)
1693 {
1694 const double w = std::numbers::pi * (static_cast<double>(k) + 0.5) / kGrid;
1695 const double cw = std::cos(w), sw = std::sin(w);
1696 double re = 0.0, im = 0.0, rr = 1.0, ri = 0.0;
1697 for (int n = 0; n < firLen_; ++n)
1698 {
1699 re += designTaps_[static_cast<size_t>(n)] * rr;
1700 im += designTaps_[static_cast<size_t>(n)] * ri;
1701 const double nr = rr * cw + ri * sw;
1702 ri = ri * cw - rr * sw;
1703 rr = nr;
1704 }
1705 double g2 = (re * re + im * im) * firNorm_ * firNorm_;
1706 if (contourActive_)
1707 for (const auto& s : headContour_[0]) g2 *= peakMagnitude(s, w) * peakMagnitude(s, w);
1708 else
1709 g2 *= peakMagnitude(headBump_[0], w) * peakMagnitude(headBump_[0], w);
1710 const double play = shelfMagnitude(playHF_[0], w) * shelfMagnitude(playLF_[0], w);
1711 g2 *= play * play;
1712 if (overBiasOn_)
1713 {
1714 const double nr = obB0_ + obB1_ * cw, ni = -obB1_ * sw;
1715 const double dr = 1.0 - obP_ * cw, di = obP_ * sw;
1716 g2 *= (nr * nr + ni * ni) / (dr * dr + di * di);
1717 }
1718 g2 *= peakMagnitude(outHp_[0], w) * peakMagnitude(outHp_[0], w);
1719 power += g2;
1720 }
1721 power /= kGrid;
1722 hissNorm_ = power > 1e-20 ? 1.0 / std::sqrt(power) : 1.0;
1723 }
1724
1725 // -- Building blocks -----------------------------------------------------------
1726 // -- Building blocks -----------------------------------------------------------
1727
1729 struct ShelfSection
1730 {
1731 double b0 = 1.0, b1 = 0.0, a1 = 0.0;
1732 double x1 = 0.0, y1 = 0.0;
1733
1734 void clear() noexcept { x1 = 0.0; y1 = 0.0; }
1735 [[nodiscard]] double process(double x) noexcept
1736 {
1737 const double y = b0 * x + b1 * x1 - a1 * y1;
1738 x1 = x;
1739 y1 = y;
1740 return y;
1741 }
1742 };
1743
1745 struct PeakSection
1746 {
1747 double b0 = 1.0, b1 = 0.0, b2 = 0.0, a1 = 0.0, a2 = 0.0;
1748 double z1 = 0.0, z2 = 0.0;
1749
1750 void clear() noexcept { z1 = 0.0; z2 = 0.0; }
1751 [[nodiscard]] T process(T x) noexcept
1752 {
1753 const double in = static_cast<double>(x);
1754 const double y = b0 * in + z1;
1755 z1 = b1 * in - a1 * y + z2;
1756 z2 = b2 * in - a2 * y;
1757 return static_cast<T>(y);
1758 }
1759 };
1760
1763 static ShelfSection makeHFShelf(double t, double kHi, double fs, bool inverse) noexcept
1764 {
1765 const double kt = 2.0 * fs * t;
1766 double n0 = kHi * kt + 1.0, n1 = 1.0 - kHi * kt;
1767 double d0 = kt + 1.0, d1 = 1.0 - kt;
1768 if (inverse) { std::swap(n0, d0); std::swap(n1, d1); }
1769 return { n0 / d0, n1 / d0, d1 / d0, 0.0, 0.0 };
1770 }
1771
1772 static ShelfSection makeLFShelf(double t, double kLo, double fs, bool inverse) noexcept
1773 {
1774 const double kt = 2.0 * fs * t;
1775 double n0 = kt + kLo, n1 = kLo - kt;
1776 double d0 = kt + 1.0, d1 = 1.0 - kt;
1777 if (inverse) { std::swap(n0, d0); std::swap(n1, d1); }
1778 return { n0 / d0, n1 / d0, d1 / d0, 0.0, 0.0 };
1779 }
1780
1782 static ShelfSection firstOrder(double n1, double n0, double d1, double d0, double fs) noexcept
1783 {
1784 const double k = 2.0 * fs;
1785 const double a0 = d1 * k + d0;
1786 return { (n1 * k + n0) / a0, (n0 - n1 * k) / a0, (d0 - d1 * k) / a0, 0.0, 0.0 };
1787 }
1788
1790 [[nodiscard]] static double shelfMagnitude(const ShelfSection& s, double w) noexcept
1791 {
1792 const double c = std::cos(w), sn = std::sin(w);
1793 const double nr = s.b0 + s.b1 * c, ni = -s.b1 * sn;
1794 const double dr = 1.0 + s.a1 * c, di = -s.a1 * sn;
1795 return std::sqrt((nr * nr + ni * ni) / std::max(1e-300, dr * dr + di * di));
1796 }
1797
1799 [[nodiscard]] static double peakMagnitude(const PeakSection& s, double w) noexcept
1800 {
1801 const double c1 = std::cos(w), s1 = std::sin(w), c2 = std::cos(2.0 * w), s2 = std::sin(2.0 * w);
1802 const double nr = s.b0 + s.b1 * c1 + s.b2 * c2, ni = -(s.b1 * s1 + s.b2 * s2);
1803 const double dr = 1.0 + s.a1 * c1 + s.a2 * c2, di = -(s.a1 * s1 + s.a2 * s2);
1804 return std::sqrt((nr * nr + ni * ni) / std::max(1e-300, dr * dr + di * di));
1805 }
1806
1808 struct FormulationParams
1809 {
1810 double ms, a, alpha, k, c, hissDb;
1811 };
1812
1813 [[nodiscard]] static FormulationParams formulationOf(int f) noexcept
1814 {
1815 switch (std::clamp(f, 0, 2))
1816 {
1817 case 1: return { 3.5e5 * 1.4125375446227544, 2.2e4 * 1.4125375446227544, 1.6e-3, 2.7e4 * 1.2, 0.17, -1.5 };
1818 case 2: return { 3.5e5 * 0.7943282347242815, 2.2e4 * 0.7943282347242815, 1.6e-3, 2.7e4 * 0.8, 0.25, 3.0 };
1819 default: return { 3.5e5, 2.2e4, 1.6e-3, 2.7e4, 0.17, 0.0 };
1820 }
1821 }
1822
1826 void clearMachine() noexcept
1827 {
1828 for (auto& h : hysteresis_) h.reset();
1829 for (auto& h : hysteresisN_) h.reset();
1830 for (auto& s : stepped_) s = Stepped {};
1831 for (auto& f : firState_) std::fill(f.begin(), f.end(), T(0));
1832 for (auto& d : delayRing_) std::fill(d.begin(), d.end(), T(0));
1833 for (auto& s : inputAc_) s = {};
1834 for (auto& s : recTrim_) s.clear();
1835 for (auto& s : playTrim_) s.clear();
1836 for (auto& v : ironLp_) v = 0.0;
1837 for (auto& s : recordHF_) s.clear();
1838 for (auto& s : recordLF_) s.clear();
1839 for (auto& s : playHF_) s.clear();
1840 for (auto& s : playLF_) s.clear();
1841 for (auto& v : overBiasLp_) v = 0.0;
1842 for (auto& v : overBiasX1_) v = 0.0;
1843 // Clear STATE only: wiping coefficients here used to leave the head
1844 // bump at identity until the next parameter change re-ran recompute.
1845 for (auto& b : headBump_) b.clear();
1846 for (auto& hp : outHp_) hp.clear();
1847 for (auto& s : hissHF_) s.clear();
1848 for (auto& s : hissLF_) s.clear();
1849 for (auto& s : xtHp_) s.clear();
1850 for (auto& s : trPre_) s.clear();
1851 for (auto& s : trPost_) s.clear();
1852 for (auto& v : trMean_) v = 0.0;
1853 for (auto& v : asymMean_) v = 0.0;
1854 for (auto& v : wet_) v = 0.0;
1855 for (auto& chain : headContour_) for (auto& s : chain) s.clear();
1856 for (auto& n : recNet_) for (auto& s : n) s.reset();
1857 for (auto& n : playNet_) for (auto& s : n) s.reset();
1858 if (oversampler_) oversampler_->reset();
1859 }
1860
1862 [[nodiscard]] static double speedInIps(Speed speed) noexcept
1863 {
1864 switch (speed)
1865 {
1866 case Speed::IPS_3_75: return 3.75;
1867 case Speed::IPS_7_5: return 7.5;
1868 case Speed::IPS_30: return 30.0;
1869 case Speed::IPS_15: break;
1870 }
1871 return 15.0;
1872 }
1873
1874 void recomputeLinear() noexcept
1875 {
1876 const double driveDbV = static_cast<double>(driveDb_.load(std::memory_order_relaxed));
1877 const double drive = std::pow(10.0, driveDbV / 20.0);
1878 const double bias = static_cast<double>(bias_.load(std::memory_order_relaxed));
1879 const auto speed = static_cast<Speed>(speed_.load(std::memory_order_relaxed));
1880 const double ips = speedInIps(speed);
1881 const auto standard = static_cast<Standard>(standard_.load(std::memory_order_relaxed));
1882 const double lossAmt = static_cast<double>(loss_.load(std::memory_order_relaxed));
1883 const double bumpAmt = static_cast<double>(headBumpAmt_.load(std::memory_order_relaxed));
1884
1885 // --- bias -> carrier amplitude and over-bias erasure -------------------
1886 // Real AC bias: the control maps to the push-pull carrier amplitude in
1887 // units of the JA 'a' parameter. Nominal (0.5) sits at B = 3a: the
1888 // carrier sweeps well past the coercivity every cycle, erasing the
1889 // loop's branch memory exactly like hardware bias (measured: LF gain
1890 // history-independent to < 0.1 dB). Under-bias drops B below the
1891 // erase threshold: the loop keeps partial branch memory - the REAL
1892 // grit and level instability of an under-biased machine. Over-bias
1893 // adds the self-erasure of short wavelengths (wider recording zone)
1894 // as a one-pole roll-off.
1895 // Formulation: the JA parameters of the material, set on the running
1896 // pairs when it changes; the bias scales with its coercive force so
1897 // that 0.5 stays the optimum of the material.
1898 const int form = formulation_.load(std::memory_order_relaxed);
1899 const FormulationParams fp = formulationOf(form);
1900 if (form != formApplied_)
1901 {
1902 for (auto& h : hysteresis_) h.setParameters(fp.ms, fp.a, fp.alpha, fp.k, fp.c);
1903 for (auto& h : hysteresisN_) h.setParameters(fp.ms, fp.a, fp.alpha, fp.k, fp.c);
1904 formApplied_ = form;
1905 hissNormDirty_ = true;
1906 }
1907 calReq_.form = fp;
1908 const double biasB = std::min(6.0, 3.0 * std::pow(9.0, bias - 0.5));
1909 calReq_.biasAmp = biasB * 2.2e4 * (fp.k / 2.7e4);
1910 biasNominal_ = 3.0 * 2.2e4 * (fp.k / 2.7e4);
1911 calReq_.biasNominal = biasNominal_;
1912 if (biasB > 3.0)
1913 {
1914 // Gentle self-erasure (corner gliding 22 kHz -> ~12.8 kHz at full
1915 // over-bias): first-order low-pass with its pole at the analog
1916 // corner and a zero that matches the analog gain at Nyquist.
1917 // Between the optimum (B = 3) and B = 3.5 the low-pass at its
1918 // widest comes in by degrees, so the top end darkens from the
1919 // optimum on without a step.
1920 const double fc = 22000.0 * (3.5 / std::max(biasB, 3.5));
1921 const double pole = std::exp(-2.0 * std::numbers::pi * fc / sampleRate_);
1922 const double r = 0.5 * sampleRate_ / fc;
1923 const double nyq = 1.0 / std::sqrt(1.0 + r * r);
1924 const double b0 = 0.5 * ((1.0 - pole) + nyq * (1.0 + pole));
1925 const double b1 = 0.5 * ((1.0 - pole) - nyq * (1.0 + pole));
1926 const double share = std::min(1.0, (biasB - 3.0) / 0.5);
1927 obP_ = pole;
1928 obB0_ = (1.0 - share) + share * b0;
1929 obB1_ = share * b1 - (1.0 - share) * pole;
1930 overBiasOn_ = true;
1931 }
1932 else if (bias < 0.5)
1933 {
1934 // Under the optimum the short wavelengths record more strongly
1935 // than the long ones: a high shelf that grows as the bias falls,
1936 // around a frequency that follows the speed (the wavelength).
1937 const double lift = std::pow(10.0, kUnderBiasLiftDb * (1.0 - 2.0 * bias) / 20.0);
1938 const double centre = std::clamp(kUnderBiasCentreHz * ips / 15.0, 1000.0, 0.3 * sampleRate_);
1939 const ShelfSection s = makeHFShelf(1.0 / (2.0 * std::numbers::pi * centre * std::sqrt(lift)), lift, sampleRate_, false);
1940 obP_ = -s.a1;
1941 obB0_ = s.b0;
1942 obB1_ = s.b1;
1943 overBiasOn_ = true;
1944 }
1945 else
1946 {
1947 overBiasOn_ = false;
1948 }
1949
1950 // --- EQ time constants per standard and speed --------------------------
1951 double t2 = 50e-6; // HF time constant
1952 bool useLF = false; // NAB LF constant 3180 us
1953 switch (standard)
1954 {
1955 case Standard::NAB:
1956 t2 = (speed == Speed::IPS_30) ? 17.5e-6 : (speed == Speed::IPS_3_75) ? 90e-6 : 50e-6;
1957 useLF = speed != Speed::IPS_30;
1958 break;
1959 case Standard::CCIR:
1960 // 3.75 ips carries 90 us and the low-frequency constant in both standards.
1961 t2 = (speed == Speed::IPS_3_75) ? 90e-6
1962 : (speed == Speed::IPS_7_5) ? 70e-6
1963 : (speed == Speed::IPS_15) ? 35e-6 : 17.5e-6;
1964 useLF = speed == Speed::IPS_3_75;
1965 break;
1966 }
1967 constexpr double kHiCap = 4.0; // +12 dB emphasis cap (practical alignment)
1968 constexpr double kLoBoost = 2.0; // +6 dB NAB LF record boost
1969 const double tLo = 3180e-6;
1970 const double hfTrim = static_cast<double>(alignHf_.load(std::memory_order_relaxed));
1971 const double lfTrim = static_cast<double>(alignLf_.load(std::memory_order_relaxed));
1972 const double gHf = std::pow(10.0, hfTrim / 20.0), gLf = std::pow(10.0, lfTrim / 20.0);
1973
1974 // The emphasis trim: a shelf on the record side and its exact inverse
1975 // on the reproduce side (both the identity, to the bit, at 0 dB).
1976 double trimAt1k = 1.0;
1977 {
1978 const double gRec = std::pow(10.0, static_cast<double>(recordEmphasis_.load(std::memory_order_relaxed)) / 20.0);
1979 const double tTrim = 1.0 / (2.0 * std::numbers::pi * kEmphasisTrimHz * std::sqrt(gRec));
1980 const ShelfSection up = makeHFShelf(tTrim, gRec, sampleRate_, false);
1981 const ShelfSection down = makeHFShelf(tTrim, gRec, sampleRate_, true);
1982 for (auto& s : recTrim_)
1983 {
1984 const double x1 = s.x1, y1 = s.y1;
1985 s = up;
1986 s.x1 = x1;
1987 s.y1 = y1;
1988 }
1989 for (auto& s : playTrim_)
1990 {
1991 const double x1 = s.x1, y1 = s.y1;
1992 s = down;
1993 s.x1 = x1;
1994 s.y1 = y1;
1995 }
1996 trimAt1k = shelfMagnitude(up, 2.0 * std::numbers::pi * 1000.0 / sampleRate_);
1997 }
1998
1999 // --- drive scaling with operating-level makeup -------------------------
2000 // 0 dBFS at nominal drive maps to H = 1.2a: moderate saturation. Tape
2001 // gain is level-dependent, so unity can only be defined at one
2002 // operating point: calibrate empirically at -12 dBFS programme level
2003 // by running a short 1 kHz burst through the same push-pull biased
2004 // chain on two scratch instances (a few thousand model samples, only
2005 // on parameter changes). Quieter material reads slightly low, hotter
2006 // material blooms into compression - like tape.
2007 // The operating level drives the tape harder; the makeup measures the
2008 // whole gain, so the output level is kept.
2009 const double calGain = std::pow(10.0, static_cast<double>(calLevel_.load(std::memory_order_relaxed)) / 20.0);
2010 calReq_.hScale = drive * 1.2 * 2.2e4 * calGain;
2011 {
2012 // -12 dBFS reference, seen through the record emphasis: at 1 kHz
2013 // the HF emphasis already lifts the level (about +3.7 dB NAB-15),
2014 // so calibrating with the raw amplitude would leave the whole
2015 // path low by the differential compression. Align at the level
2016 // the loop actually sees, like a real machine's record-level
2017 // alignment.
2018 const double w1 = 2.0 * std::numbers::pi * 1000.0 * t2;
2019 const double emph1k = std::sqrt((1.0 + kHiCap * kHiCap * w1 * w1)
2020 / (1.0 + w1 * w1));
2021 calReq_.calAmp = 0.25 * emph1k * trimAt1k;
2022 calReq_.drive = drive;
2023 }
2024
2025 for (int ch = 0; ch < numChannels_; ++ch)
2026 {
2027 auto& rhf = recordHF_[static_cast<size_t>(ch)];
2028 auto& rlf = recordLF_[static_cast<size_t>(ch)];
2029 auto& phf = playHF_[static_cast<size_t>(ch)];
2030 auto& plf = playLF_[static_cast<size_t>(ch)];
2031
2032 const double sx1 = rhf.x1, sy1 = rhf.y1;
2033 rhf = makeHFShelf(t2, kHiCap, sampleRate_, false);
2034 rhf.x1 = sx1; rhf.y1 = sy1;
2035
2036 const double lx1 = rlf.x1, ly1 = rlf.y1;
2037 rlf = useLF ? makeLFShelf(tLo, kLoBoost, sampleRate_, false) : ShelfSection {};
2038 rlf.x1 = lx1; rlf.y1 = ly1;
2039
2040 const double px1 = phf.x1, py1 = phf.y1;
2041 phf = makeHFShelf(t2, kHiCap / gHf, sampleRate_, true);
2042 phf.x1 = px1; phf.y1 = py1;
2043
2044 const double qx1 = plf.x1, qy1 = plf.y1;
2045 plf = useLF ? makeLFShelf(tLo, kLoBoost / gLf, sampleRate_, true)
2046 : (lfTrim != 0.0 ? makeLFShelf(tLo, 1.0 / gLf, sampleRate_, true) : ShelfSection {});
2047 plf.x1 = qx1; plf.y1 = qy1;
2048
2049 // The hiss's own de-emphasis, for the circuit (whose reproduce
2050 // network runs before the tape's noise is laid on).
2051 auto& hhf = hissHF_[static_cast<size_t>(ch)];
2052 auto& hlf = hissLF_[static_cast<size_t>(ch)];
2053 const double hx1 = hhf.x1, hy1 = hhf.y1, lx = hlf.x1, ly = hlf.y1;
2054 hhf = phf; hhf.x1 = hx1; hhf.y1 = hy1;
2055 hlf = plf; hlf.x1 = lx; hlf.y1 = ly;
2056 }
2057
2058 // Circuit electronics: the record and reproduce networks from their
2059 // analog transfer functions, at the internal rate, as ladders.
2060 const bool circuitWanted = electronics_.load(std::memory_order_relaxed) == 1;
2061 if (circuitWanted)
2062 {
2063 const double osRate = sampleRate_ * static_cast<double>(osFactor_);
2064 const double kLoR = useLF ? kLoBoost : 1.0;
2065 const double kHiP = kHiCap / gHf, kLoP = kLoR / gLf;
2066 const AnalogSection rec1 = AnalogSection::make(kHiCap * t2 * tLo, kHiCap * t2 * kLoR + tLo, kLoR,
2067 t2 * tLo, t2 + tLo, 1.0);
2068 const AnalogSection play1 = AnalogSection::make(t2 * tLo, t2 + tLo, 1.0,
2069 kHiP * t2 * tLo, kHiP * t2 * kLoP + tLo, kLoP);
2070 const double recLimit = std::min(45000.0, 0.45 * osRate), playPole = std::min(50000.0, 0.45 * osRate);
2071 const double corner = 1.0 / (2.0 * std::numbers::pi * t2);
2072 const BiquadCoeffs r1 = FilterDesign::bilinear(rec1, osRate, corner);
2073 const BiquadCoeffs r2 = FilterDesign::bilinear(AnalogSection::lowPass(recLimit), osRate, recLimit);
2074 const BiquadCoeffs q1 = FilterDesign::bilinear(play1, osRate, corner);
2075 const BiquadCoeffs q2 = FilterDesign::bilinear(AnalogSection::firstOrderLowPass(playPole), osRate, playPole);
2076 const int ramp = static_cast<int>(0.05 * osRate);
2077 for (int ch = 0; ch < numChannels_; ++ch)
2078 {
2079 auto& rec = recNet_[static_cast<size_t>(ch)];
2080 auto& play = playNet_[static_cast<size_t>(ch)];
2081 if (!circuitActive_)
2082 {
2083 rec[0].setCoeffs(r1); rec[1].setCoeffs(r2); play[0].setCoeffs(q1); play[1].setCoeffs(q2);
2084 for (auto& s : rec) s.reset();
2085 for (auto& s : play) s.reset();
2086 }
2087 else
2088 {
2089 rec[0].rampCoeffs(r1, ramp); rec[1].rampCoeffs(r2, ramp);
2090 play[0].rampCoeffs(q1, ramp); play[1].rampCoeffs(q2, ramp);
2091 }
2092 }
2093 if (!circuitActive_)
2094 for (auto& s : hissHF_) s.clear();
2095 }
2096 else if (circuitActive_)
2097 {
2098 // Back to the ideal shelves: they start from rest.
2099 for (auto& s : recordHF_) s.clear();
2100 for (auto& s : recordLF_) s.clear();
2101 for (auto& s : playHF_) s.clear();
2102 for (auto& s : playLF_) s.clear();
2103 }
2104 circuitActive_ = circuitWanted;
2105
2106 // --- loss-effect FIR (63 taps, linear phase) ---------------------------
2107 // A new speed under the speed transport: the tape keeps moving at the
2108 // old one and glides to the new one with inertia.
2109 if (speedTransportActive_ && speedIps_ > 0.0) tapeTransport_.setSpeed(ips);
2110 else tapeTransport_.setSpeedNow(ips);
2111 speedIps_ = ips;
2112 const double v = ips * 0.0254; // m/s
2113 // The record head (record-head monitoring) has the wider gap and spacing.
2114 const bool sync = monitor_.load(std::memory_order_relaxed) == 1;
2115 const double gap = sync ? 6.0e-6 : 3.0e-6; // playback head gap (m)
2116 const double spacing = sync ? 1.0e-6 : 0.5e-6; // head-tape spacing (m)
2117 constexpr double thickness = 1.0e-6; // effective coating depth (m)
2118
2119 const int grid = firLen_ + 1; // design grid (64 points at 48 kHz)
2120 double* mags = designMags_.data();
2121 for (int kBin = 0; kBin <= grid / 2; ++kBin)
2122 {
2123 const double f = kBin * sampleRate_ / grid;
2124 double mag = 1.0;
2125 if (f > 1.0)
2126 {
2127 const double lambda = v / f;
2128 const double spacingLoss = std::pow(10.0, -54.6 * (spacing / lambda) / 20.0);
2129 const double gx = std::numbers::pi * gap / lambda;
2130 const double gapLoss = (gx < 1e-9) ? 1.0
2131 : std::abs(std::sin(gx) / gx);
2132 const double tx = 4.0 * std::numbers::pi * thickness / lambda;
2133 const double thickLoss = (tx < 1e-9) ? 1.0 : (1.0 - std::exp(-tx)) / tx;
2134 mag = spacingLoss * gapLoss * thickLoss;
2135 }
2136 mags[kBin] = (1.0 - lossAmt) + lossAmt * mag;
2137 // Physical reproduce-gap cutoff: no real head reads anything
2138 // above ~21.5 kHz. Always active (independent of the loss
2139 // amount); it also removes the last even-order bias
2140 // intermodulation sidebands just below the base-rate Nyquist.
2141 // Raised-cosine transition 19.5k -> 21.5k avoids the passband
2142 // Gibbs ripple of a hard step on the design grid.
2143 if (f >= 21500.0)
2144 mags[kBin] = 0.0;
2145 else if (f > 19500.0)
2146 mags[kBin] *= 0.5 + 0.5 * std::cos(std::numbers::pi * (f - 19500.0) / 2000.0);
2147 }
2148 double* taps = designTaps_.data();
2149 for (int n = 0; n < firLen_; ++n)
2150 {
2151 // Frequency sampling with the cosines taken from a table built in
2152 // prepare(): the design stays cheap at any FIR length.
2153 const int offset = n - firCenter_;
2154 double acc = mags[0];
2155 for (int kBin = 1; kBin < grid / 2; ++kBin)
2156 {
2157 const int idx = ((kBin * offset) % grid + grid) % grid;
2158 acc += 2.0 * mags[kBin] * cosTable_[static_cast<size_t>(idx)];
2159 }
2160 acc += mags[grid / 2] * ((offset & 1) ? -1.0 : 1.0);
2161 const double hann = 0.5 - 0.5 * cosTable_[static_cast<size_t>((n + 1) % grid)];
2162 taps[n] = acc * hann / grid;
2163 }
2164 // Normalize to exact unity at the 1 kHz calibration frequency so the
2165 // windowing/gap-cut of the design never shifts the calibrated level.
2166 {
2167 const double w1k = 2.0 * std::numbers::pi * 1000.0 / sampleRate_;
2168 double re = 0.0, im = 0.0;
2169 for (int n = 0; n < firLen_; ++n)
2170 {
2171 re += taps[n] * std::cos(w1k * n);
2172 im -= taps[n] * std::sin(w1k * n);
2173 }
2174 const double g = std::sqrt(re * re + im * im);
2175 const double norm = (g > 1e-9) ? 1.0 / g : 1.0;
2176 for (int n = 0; n < firLen_; ++n) taps[n] *= norm;
2177 firNorm_ = 1.0;
2178 }
2179 for (int n = 0; n < firLen_; ++n)
2180 firTaps_[static_cast<size_t>(firLen_ - 1 - n)] =
2181 static_cast<T>(taps[n]); // reversed for dotProduct
2182
2183 // --- head bump ----------------------------------------------------------
2184 // The bump sits where the recorded wavelength meets the length of the
2185 // head's contact with the tape: its frequency is the speed over that
2186 // length, and each track format has its head (the wider the track,
2187 // the longer the contact).
2188 static constexpr double kContactRatio[3] = { 1.0, 0.8, 1.25 }; // half, full and quarter track
2189 const double bumpHz = kBumpHzPerIps * ips
2190 * kContactRatio[static_cast<size_t>(std::clamp(trackFormat_.load(std::memory_order_relaxed), 0, 2))];
2191 const double bumpDb = 2.5 * bumpAmt;
2192 const auto bc = BiquadCoeffs::makePeak(sampleRate_, bumpHz, 0.9, bumpDb);
2193 for (auto& b : headBump_)
2194 {
2195 const double pz1 = b.z1, pz2 = b.z2;
2196 b = PeakSection { bc.b0, bc.b1, bc.b2, bc.a1, bc.a2, 0.0, 0.0 };
2197 b.z1 = pz1;
2198 b.z2 = pz2;
2199 }
2200
2201 // Head contour: the bump and three ripples above it, each a resonance
2202 // designed on its analog prototype.
2203 contourActive_ = headModel_.load(std::memory_order_relaxed) == 1;
2204 if (contourActive_)
2205 {
2206 static constexpr double kRatio[kContourSections] = { 1.0, 1.45, 1.95, 2.5 };
2207 static constexpr double kShare[kContourSections] = { 1.0, -0.5, 0.28, -0.15 };
2208 static constexpr double kQ[kContourSections] = { 0.9, 2.0, 2.5, 3.0 };
2209 for (int k = 0; k < kContourSections; ++k)
2210 {
2211 const size_t kk = static_cast<size_t>(k);
2212 const BiquadCoeffs c = FilterDesign::digital(
2213 AnalogSection::peak(bumpHz * kRatio[kk], kQ[kk], kContourDb * bumpAmt * kShare[kk]), sampleRate_);
2214 for (auto& chain : headContour_)
2215 {
2216 auto& s = chain[kk];
2217 const double z1 = s.z1, z2 = s.z2;
2218 s = PeakSection { c.b0, c.b1, c.b2, c.a1, c.a2, z1, z2 };
2219 }
2220 }
2221 }
2222 hissNormDirty_ = true;
2223 }
2224
2232 void startCalibration() noexcept
2233 {
2234 calRun_ = calReq_;
2235 const double fs4 = sampleRate_ * static_cast<double>(osFactor_ * steps_);
2236 // 16 ms settle + 8 ms measured: the biased loop's mean state needs a
2237 // few hundred carrier cycles to reach its steady branch.
2238 calN_ = static_cast<int>(0.024 * fs4);
2239 calFrom_ = (calN_ * 2) / 3;
2240 calW_ = 2.0 * std::numbers::pi * 1000.0 / fs4;
2241 const FormulationParams& fp = calRun_.form;
2242 calib_.prepare(fs4);
2243 calib_.setParameters(fp.ms, fp.a, fp.alpha, fp.k, fp.c);
2244 calib2_.prepare(fs4);
2245 calib2_.setParameters(fp.ms, fp.a, fp.alpha, fp.k, fp.c);
2246 calI_ = 0;
2247 calRe_ = calIm_ = 0.0;
2248 calMeas_ = 0;
2249 calActive_ = true;
2250 }
2251
2254 void stepCalibration(int budget) noexcept
2255 {
2256 const int stop = std::min(calN_, calI_ + std::max(budget, 0));
2257 for (; calI_ < stop; ++calI_)
2258 {
2259 const int i = calI_;
2260 const double s = std::sin(calW_ * i);
2261 const double x = calRun_.hScale * calRun_.calAmp * s;
2262 const double c = carrier(calRun_.biasAmp, calRun_.biasNominal, i & 7);
2263 const double m = 0.5
2264 * (static_cast<double>(calib_.processSample(static_cast<T>(x + c)))
2265 + static_cast<double>(calib2_.processSample(static_cast<T>(x - c))));
2266 // Measure the FUNDAMENTAL of the averaged pair (Goertzel-style
2267 // correlation), not the raw RMS: the raw output still carries the
2268 // even-order carrier residue that the downsampler removes in the
2269 // real path, and it would inflate the measurement.
2270 if (i >= calFrom_)
2271 {
2272 calRe_ += m * std::cos(calW_ * i);
2273 calIm_ += m * s;
2274 ++calMeas_;
2275 }
2276 }
2277 if (calI_ < calN_) return;
2278 const double fund = 2.0 * std::sqrt(calRe_ * calRe_ + calIm_ * calIm_)
2279 / std::max(1, calMeas_);
2280 // Partial loudness link: a calibration that pins the reference level
2281 // EXACTLY kills the drive knob (inaudible below 0 dB where tape stays
2282 // clean, a pure attenuator above as compression eats level). A
2283 // +0.25 dB/dB residual slope keeps it alive: backing off cleans AND
2284 // drops slightly, pushing holds level while the tape density grows.
2285 // Four levels compress the tone harder than a programme 9 dB under
2286 // it, so pushed they take 0.23: the programme then stays within the
2287 // 8 dB the knob is allowed over its whole travel.
2288 const double link = fourLevel_ && calRun_.drive > 1.0 ? kFourLevelDriveLink : kDriveLink;
2289 mScale_ = ((fund > 0.0) ? calRun_.calAmp / fund : 1.0) * std::pow(calRun_.drive, link);
2290 hScale_ = calRun_.hScale;
2291 biasAmp_ = calRun_.biasAmp;
2292 calActive_ = false;
2293 if (calRestart_)
2294 {
2295 calRestart_ = false;
2296 startCalibration();
2297 }
2298 }
2299
2307 [[nodiscard]] double nextTransportMod(double depth) noexcept
2308 {
2309 if (modAt_ == 0)
2310 {
2311 modFrom_ = modTo_;
2312 modTo_ = transportModAhead(depth);
2313 }
2314 const double share = static_cast<double>(++modAt_) / static_cast<double>(kTransportControl);
2315 if (modAt_ == kTransportControl) modAt_ = 0;
2316 return modFrom_ + (modTo_ - modFrom_) * share;
2317 }
2318
2319 [[nodiscard]] double transportModAhead(double depth) noexcept
2320 {
2321 // Always advance the transport state so engaging the control later
2322 // does not jump phases; only the output is scaled by depth.
2323 const double dt = static_cast<double>(kTransportControl) / sampleRate_;
2324 modPhaseWow_ += 0.55 * dt;
2325 modPhaseWow_ -= std::floor(modPhaseWow_);
2326 modPhaseFlut_ += 8.3 * dt;
2327 modPhaseFlut_ -= std::floor(modPhaseFlut_);
2328 modPhaseFlut2_ += 23.0 * dt;
2329 modPhaseFlut2_ -= std::floor(modPhaseFlut2_);
2330
2331 rng_ = rng_ * 1664525u + 1013904223u;
2332 // One draw a control step, scaled by 1 / sqrt(kTransportControl).
2333 const double n = (static_cast<double>(rng_ >> 8) / 8388608.0 - 1.0) * 0.25;
2334
2335 // Slow drift: heavily low-passed random walk, clamped to +/-18 samples.
2336 driftState_ = driftA_ * driftState_ + (1.0 - driftA_) * n * 600.0;
2337 const double drift = std::clamp(driftState_, -18.0, 18.0);
2338
2339 // Scrape band (~40-90 Hz): difference of two one-poles on noise.
2340 scrapeLp1_ = scrapeA1_ * scrapeLp1_ + (1.0 - scrapeA1_) * n;
2341 scrapeLp2_ = scrapeA2_ * scrapeLp2_ + (1.0 - scrapeA2_) * n;
2342 const double scrape = (scrapeLp1_ - scrapeLp2_) * 0.6;
2343
2344 if (depth <= 0.0)
2345 return 0.0;
2346
2347 const double twoPi = 2.0 * std::numbers::pi;
2348 // Component amplitudes in delay samples at 48k, scaled to the actual
2349 // rate (the delay centre scales identically). The 0.4 factor calibrates
2350 // full depth to ~0.6 % peak-to-peak measured pitch deviation (a worn
2351 // machine); the 0.15 default lands near healthy-transport spec.
2352 const double rateScale = sampleRate_ / 48000.0;
2353 const double wow = 27.8 * std::sin(twoPi * modPhaseWow_);
2354 const double flut = 0.55 * std::sin(twoPi * modPhaseFlut_);
2355 const double flut2 = 0.066 * std::sin(twoPi * modPhaseFlut2_);
2356
2357 return 0.4 * depth * rateScale * (drift + wow + flut + flut2 + scrape);
2358 }
2359
2360 // -- Members --------------------------------------------------------------------
2361 static constexpr int kFirLenAt48k = 63;
2362 static constexpr double kGainRampSeconds = 0.03;
2363 static constexpr double kUniformToUnitRms = 1.7320508075688772;
2364 static constexpr int kContourSections = 4;
2365 static constexpr double kContourDb = 3.0;
2366 static constexpr double kAsymmetryShare = 0.15;
2367 static constexpr double kTransformerCornerHz = 60.0;
2368 static constexpr double kInputCouplingHz = 4.0;
2369 static constexpr double kOutputCouplingHz = 24.0;
2370 static constexpr double kIronCornerHz = 20.0;
2371 static constexpr double kUnderBiasLiftDb = 4.5;
2372 static constexpr double kUnderBiasCentreHz = 6000.0;
2373 static constexpr double kEmphasisTrimHz = 4000.0;
2374 static constexpr double kBumpHzPerIps = 6.0;
2375 static constexpr double kTransformerEven = 0.03;
2376 static constexpr double kTransformerOdd = 0.2;
2377 static constexpr double kHumNorm = 1.2649110640673518;
2378
2379 AudioSpec spec_ {};
2380 double sampleRate_ = 48000.0;
2381 int numChannels_ = 0;
2382 int maxBlock_ = 0;
2383 std::atomic<bool> prepared_ { false };
2384 int latency_ = 0;
2385 int drySize_ = 1;
2386 int osRequested_ = 4;
2387 bool fourLevel_ = true;
2388 int steps_ = 1;
2389 static constexpr double kDriveLink = 0.25, kFourLevelDriveLink = 0.23;
2390 static constexpr int kStepDelay = 4;
2391 static constexpr double kExactTolerance = 1e-9, kFourLevelTolerance = 1e-6;
2392 std::vector<Stepped> stepped_;
2393 double biasNominal_ = 3.0 * 2.2e4;
2394 static constexpr double kFourLevelInternalRate = 352800.0;
2395 static constexpr double kInnerLevel = 0.2, kOuterLevel = 0.6;
2396 int osFactor_ = 4;
2397 bool osAutomatic_ = false;
2399 OversamplingDryPath<T> dryPath_;
2400 AudioBuffer<T> dryScratch_;
2401 detail::DryPhase dryInputLead_, dryOutputLead_, dryIronLead_;
2402 bool dryThroughFilters_ = false;
2403 int dryDelay_ = 0;
2404 static constexpr double kAutomaticInternalRate = 176400.0;
2405 static constexpr int kCarrierPeriod = 4;
2406
2407 std::unique_ptr<Oversampling<T>> oversampler_;
2408 std::vector<Hysteresis<T>> hysteresis_;
2409 std::vector<Hysteresis<T>> hysteresisN_;
2410 Hysteresis<T> calib_;
2411 Hysteresis<T> calib2_;
2412
2430 static constexpr double kBiasTable[8] = {
2431 1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, -1.0
2432 };
2433
2434 std::vector<ShelfSection> recordHF_, recordLF_, playHF_, playLF_;
2435 std::vector<PeakSection> headBump_;
2436 std::vector<PeakSection> outHp_;
2437 std::vector<double> overBiasLp_;
2438 std::vector<double> overBiasX1_;
2439 std::vector<std::array<double, 4>> inputAc_;
2440 double inputAcPole_ = 0.0;
2441 std::vector<ShelfSection> recTrim_, playTrim_;
2442 std::vector<double> ironLp_;
2443 double ironA_ = 0.0;
2444 bool resting_ = false;
2445 int wakeHold_ = 0;
2446
2447 std::vector<T> firTaps_;
2448 std::vector<std::vector<T>> firState_;
2449 std::vector<double> cosTable_, designMags_, designTaps_;
2450 int firLen_ = kFirLenAt48k;
2451 int firCenter_ = (kFirLenAt48k - 1) / 2;
2452 int firHalf_ = 64;
2453 int firPos_ = 0;
2454
2455 std::vector<std::vector<T>> delayRing_;
2456 int delayPos_ = 0;
2457 int delayCenter_ = 96;
2458 int delayMask_ = 255;
2459 double driftA_ = 0.0, scrapeA1_ = 0.0, scrapeA2_ = 0.0;
2460 static constexpr int kTransportControl = 16;
2461 double modFrom_ = 0.0, modTo_ = 0.0;
2462 int modAt_ = 0;
2463 double humCos_ = 1.0, humSin_ = 0.0, humRotCos_ = 1.0, humRotSin_ = 0.0, humStepFor_ = -1.0;
2464
2465 std::vector<std::vector<T>> dryRing_;
2466 int dryPos_ = 0;
2467
2468 double hScale_ = 1.0, mScale_ = 1.0;
2469 // The channels' alignment (setAlignmentTolerance()).
2470 static constexpr int kMaxAligned = 16;
2471 std::atomic<T> alignTolerance_ { T(0) };
2472 double alignFor_ = 0.0, alignHpA_ = 0.0;
2473 bool alignActive_ = false;
2474 std::array<double, kMaxAligned> alignBias_ {}, alignShelf_ {}, alignLevel_ {}, alignHpX_ {}, alignHpY_ {};
2475
2477 [[nodiscard]] static double alignDraw(int ch, int quantity) noexcept
2478 {
2479 uint64_t x = 0x9E3779B97F4A7C15ull * static_cast<uint64_t>(ch * 3 + quantity + 1);
2480 x = (x ^ (x >> 30)) * 0xBF58476D1CE4E5B9ull;
2481 x = (x ^ (x >> 27)) * 0x94D049BB133111EBull;
2482 x ^= x >> 31;
2483 return static_cast<double>(x >> 11) * (2.0 / 9007199254740992.0) - 1.0;
2484 }
2485
2487 bool updateAlignment(int channels) noexcept
2488 {
2489 const double tol = static_cast<double>(alignTolerance_.load(std::memory_order_relaxed));
2490 if (tol != alignFor_)
2491 {
2492 alignFor_ = tol;
2493 alignHpA_ = std::exp(-2.0 * 3.141592653589793 * kAlignShelfHz / sampleRate_);
2494 for (int ch = 0; ch < kMaxAligned; ++ch)
2495 {
2496 const auto c = static_cast<size_t>(ch);
2497 alignBias_[c] = 1.0 + kAlignBias * tol * alignDraw(ch, 0);
2498 alignShelf_[c] = std::pow(10.0, kAlignShelfDb * tol * alignDraw(ch, 1) / 20.0) - 1.0;
2499 alignLevel_[c] = std::pow(10.0, kAlignLevelDb * tol * alignDraw(ch, 2) / 20.0);
2500 }
2501 }
2502 (void)channels;
2503 alignActive_ = tol > 0.0;
2504 return alignActive_;
2505 }
2506 static constexpr double kAlignBias = 0.08;
2507 static constexpr double kAlignShelfDb = 0.75;
2508 static constexpr double kAlignShelfHz = 6000.0;
2509 static constexpr double kAlignLevelDb = 0.25;
2510
2511 // The record level's peak (getRecordPeak()).
2512 static constexpr int kMaxRecordPeaks = 16;
2513 static constexpr double kRecordPeakSeconds = 0.3;
2514 static constexpr double kRecordFullScale = 1.2 * 2.2e4;
2515 std::vector<double> recordHeld_;
2516 double recordFall_ = 0.9999;
2517 std::array<std::atomic<T>, kMaxRecordPeaks> recordPeak_ {};
2518 double biasAmp_ = 3.0 * 2.2e4;
2519 double hSm_ = 1.0, mSm_ = 1.0, bSm_ = 3.0 * 2.2e4;
2520 bool overBiasOn_ = false;
2521 bool overBiasActive_ = false;
2522 double obB0_ = 1.0, obB1_ = 0.0, obP_ = 0.0;
2523
2524 struct CalibrationRequest
2525 {
2526 double hScale = 1.0, biasAmp = 3.0 * 2.2e4, biasNominal = 3.0 * 2.2e4, calAmp = 0.25, drive = 1.0;
2527 FormulationParams form { 3.5e5, 2.2e4, 1.6e-3, 2.7e4, 0.17, 0.0 };
2528 };
2529 CalibrationRequest calReq_, calRun_;
2530 bool calActive_ = false, calRestart_ = false;
2531 int calN_ = 0, calFrom_ = 0, calI_ = 0, calMeas_ = 0;
2532 double calW_ = 0.0, calRe_ = 0.0, calIm_ = 0.0;
2533 int biasPhase_ = 0;
2534
2535 double modPhaseWow_ = 0.0, modPhaseFlut_ = 0.0, modPhaseFlut2_ = 0.0;
2536 double driftState_ = 0.0, scrapeLp1_ = 0.0, scrapeLp2_ = 0.0;
2537 uint32_t rng_ = 0x1357feedu;
2538 uint32_t rngNoise_ = 0x2468beefu;
2539
2540 std::atomic<T> driveDb_ { T(0) };
2541 std::atomic<T> bias_ { T(0.5) };
2542 std::atomic<int> speed_ { static_cast<int>(Speed::IPS_15) };
2543 std::atomic<int> standard_ { static_cast<int>(Standard::NAB) };
2544 std::atomic<T> loss_ { T(0.5) };
2545 std::atomic<T> headBumpAmt_ { T(0.5) };
2546 std::atomic<T> wowFlutter_ { T(0.15) };
2547 std::atomic<T> noiseDb_ { T(-200) };
2548 std::atomic<T> mix_ { T(1) };
2549 T currentMix_ = T(1);
2550 T mixMaxStep_ = T(1.0 / 960.0);
2551 std::atomic<bool> dirty_ { true };
2552
2553 // The machine around the tape (settings).
2554 std::atomic<int> transport_ { 0 }, mains_ { 0 }, headModel_ { 0 }, electronics_ { 0 };
2555 std::atomic<int> formulation_ { 0 }, trackFormat_ { 0 }, monitor_ { 0 };
2556 std::atomic<T> humDb_ { T(-200) }, channelBleedDb_ { T(-200) }, evenHarmonics_ { T(0) }, outputIron_ { T(0) };
2557 std::atomic<T> alignHf_ { T(0) }, alignLf_ { T(0) }, calLevel_ { T(0) }, recordEmphasis_ { T(0) };
2558
2559 // ... and its state (audio thread).
2560 bool speedTransportActive_ = false, circuitActive_ = false, contourActive_ = false, hissNormDirty_ = true;
2561 int formApplied_ = -1;
2562 double speedIps_ = 0.0, lastMod_ = 0.0;
2563 TapeTransport<T> tapeTransport_;
2564 double hissNorm_ = 1.0, firNorm_ = 1.0, xtNorm_ = 1.0;
2565 double asymMeanA_ = 0.0, trMeanA_ = 0.0;
2566 LinearRamp hiss_, hum_, xt_, tr_, asym_, monitorRamp_ { 1.0, 1.0, 0.0 };
2567 std::vector<double> wet_, asymMean_, trMean_;
2568 std::vector<ShelfSection> hissHF_, hissLF_, xtHp_, trPre_, trPost_;
2569 std::vector<std::array<PeakSection, kContourSections>> headContour_;
2570 std::vector<std::array<NormalizedLadder<double, 1>, 2>> recNet_, playNet_;
2571};
2572
2573} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
static BiquadCoeffs digital(const AnalogSection &section, const Band &band) noexcept
The biquad whose magnitude follows an analog section up to Nyquist.
static BiquadCoeffs bilinear(const AnalogSection &section, double sampleRate, double exactHz) noexcept
The bilinear transform of a section, with one frequency mapped exactly.
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.
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
Reel-to-reel tape emulation with physical hysteresis and transport.
T getRecordPeakDb(int channel) const noexcept
The record level's peak in decibels (floored at -100).
void reset() noexcept
Clears all signal state (keeps parameters). RT-safe.
void setAlignmentTolerance(T amount) noexcept
How far the channels' alignment strays, 0 to 1 (0, the default: every channel the same,...
int getLatencySamples() const noexcept
Compatibility alias of getLatency(), in prepared-rate samples.
void setStandard(Standard s) noexcept
Equalization standard (NAB adds the LF time constant). Out-of-range values are clamped.
T getDrive() const noexcept
void setNoise(T dbfs) noexcept
Tape hiss RMS level in dBFS at the output (e.g. -55 for audible vintage hiss); values <= -120 disable...
void setOversampling(int factor)
Configures internal oversampling of the biased hysteresis core (visible, tunable and switchable off)....
bool isOversamplingAutomatic() const noexcept
Whether the factor follows the host rate (setAutomaticOversampling()).
void processBlock(AudioBufferView< T > buffer) noexcept
Processes a block in-place. Pass-through until prepare() succeeds.
void setHum(T dbfs, Mains mains=Mains::Hz50) noexcept
Mains hum after the tape: the mains frequency and its second harmonic 6 dB down, in phase on every ch...
void setOutputIron(T amount) noexcept
Output iron, 0 to 1 (0, the default, is off): a parallel branch that takes the reproduced signal thro...
T getBias() const noexcept
void setElectronics(Electronics e) noexcept
Record and reproduce electronics (see Electronics). Out-of-range values are clamped.
void setTrackFormat(TrackFormat f) noexcept
Track format (see TrackFormat). Out-of-range values are clamped.
T getLossEffects() const noexcept
Monitor
What the output monitors (setMonitor()). PlayHead, the default, is the reproduce head; RecordHead rea...
Standard getStandard() const noexcept
void prepare(const AudioSpec &spec)
Allocates the whole chain. Invalid specs (non-positive or non-finite rate, block size or channel coun...
void setAlignment(T hfDb, T lfDb) noexcept
Reproduce alignment trims, as the HF and LF reproduce adjustments of a machine (both 0 by default)....
void setBias(T bias) noexcept
Bias setting [0, 1]; 0.5 is nominal calibration (carrier at 3x the JA field constant: full branch-mem...
T getHeadBump() const noexcept
void setSpeed(Speed s) noexcept
Tape speed (changes EQ time constants, losses and head bump). Out-of-range values are clamped.
T getAlignmentHf() const noexcept
T getCalibrationLevel() const noexcept
T getAlignmentLf() const noexcept
T getRecordEmphasis() const noexcept
The trim of the record emphasis in dB (setRecordEmphasis()).
std::vector< uint8_t > getState() const
Serializes the parameter state (setup/UI threads; allocates).
T getWowFlutter() const noexcept
Electronics
Record and reproduce electronics (setElectronics()).
Speed
Tape speed (3.75 ips comes last, so stored states keep their meaning).
void setFormulation(Formulation f) noexcept
Tape formulation (see Formulation). Out-of-range values are clamped.
void setHeadModel(HeadModel m) noexcept
Reproduce head model (see HeadModel). Out-of-range values are clamped.
Monitor getMonitor() const noexcept
T getRecordPeak(int channel) const noexcept
The record level's peak, the overload lamp before the tape: what drives the curve,...
int getLatency() const noexcept
Total latency in samples (active oversampler + loss FIR + transport delay); reflects the current fact...
Formulation getFormulation() const noexcept
void setEvenHarmonics(T amount) noexcept
Even harmonics of the record path, 0 to 1 (0, the default, is off): a share of the square of the reco...
void setDrive(T driveDb) noexcept
Input drive in dB [-12, +24]. Level-compensated at -12 dBFS, with a quarter of a dB a dB left: more d...
Formulation
Tape formulation (setFormulation()).
T getNoise() const noexcept
Standard
Playback equalization standard.
Electronics getElectronics() const noexcept
Transport
How the transport moves the tape (setTransport()).
Mains getMains() const noexcept
OversamplingMode getOversamplingMode() const noexcept
The oversampler's filters (setOversamplingMode()).
T getAlignmentTolerance() const noexcept
TrackFormat
Track format (setTrackFormat()): the signal grows with the track width and the hiss with its square r...
void setChannelBleed(T dB) noexcept
Bleed between the channels of each pair (0 and 1, 2 and 3, and so on): each takes the other through a...
T getChannelBleed() const noexcept
void setOversamplingMode(OversamplingMode mode)
Chooses the oversampler's filters (SETUP THREAD ONLY, as setOversampling(): an active instance is pre...
void setBiasShape(BiasShape shape)
Chooses the levels of the bias carrier (SETUP THREAD ONLY, as setOversampling(): an active instance i...
HeadModel
The reproduce head's low end (setHeadModel()). Bump, the default, is the single head-bump resonance; ...
T getOutputIron() const noexcept
T getEvenHarmonics() const noexcept
TrackFormat getTrackFormat() const noexcept
void setLossEffects(T amount) noexcept
Playback loss intensity [0, 1] (0 bypasses the loss FIR). Non-finite values are ignored.
T getHum() const noexcept
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 setCalibrationLevel(T dB) noexcept
Operating level above the reference flux, 0 to 9 dB (0 by default): the tape is driven that much hard...
T getMix() const noexcept
Speed getSpeed() const noexcept
BiasShape
The levels of the bias carrier (see setBiasShape()).
@ FourLevel
An inner and an outer level of each sign: the gain only falls with the level (default).
@ TwoLevel
Every sample at plus or minus the amplitude: the gain rises with the level before it saturates.
void setWowFlutter(T amount) noexcept
Wow & flutter depth [0, 1] (~0.25% peak pitch deviation at 1). Non-finite values are ignored.
void setAutomaticOversampling(bool on)
Lets the host rate choose the factor (SETUP THREAD ONLY, as setOversampling()).
void setRecordEmphasis(T dB) noexcept
Trim of the record emphasis, -6 to +6 dB (0 by default): a high shelf around 4 kHz on the record side...
bool setState(const uint8_t *data, size_t size)
Restores parameters from a blob (tolerant; rejects foreign ids).
void setTransport(Transport t) noexcept
Transport model (see Transport). Out-of-range values are clamped.
HeadModel getHeadModel() const noexcept
void setHeadBump(T amount) noexcept
Head-bump resonance intensity [0, 1] (~2.5 dB at full). Non-finite values are ignored.
Mains
Mains frequency of the hum (setHum()).
void setMix(T mix) noexcept
Dry/wet mix [0, 1]; dry is latency-compensated. Non-finite values are ignored.
Transport getTransport() const noexcept
void setMonitor(Monitor m) noexcept
Monitored head or input (see Monitor). Out-of-range values are clamped.
int getOversamplingFactor() const noexcept
Active oversampling factor (1 = off, 4 = default; see setBiasShape()).
BiasShape getBiasShape() const noexcept
The levels of the bias carrier (setBiasShape()).
T processSample(int channel, T x, double amount) noexcept
A sample of a channel, with the amount that advance() returned.
void aim(bool on) noexcept
Where the amount goes.
double advance() noexcept
Moves the amount by a frame and returns it.
void setCorner(double hz) noexcept
Moves the corner (a tangent, when it changes).
static constexpr double kButterworthShare
constexpr Param stepped(const char *id, const char *name, float minValue, float maxValue, float defValue, int steps, const char *unit="") noexcept
Discrete parameter helper: steps + 1 evenly spaced positions from minValue to maxValue,...
float dotProduct(const float *DSPARK_RESTRICT a, const float *DSPARK_RESTRICT b, int count) noexcept
Computes the dot product of two arrays.
Definition SimdOps.h:644
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
T gainToDecibels(T gain, T minusInfinityDb=T(-100)) noexcept
Converts a linear gain value to decibels.
Definition DspMath.h:92
constexpr uint32_t stateId(const char(&tag)[5]) noexcept
Builds a FOURCC processor id, e.g. dspark::stateId("COMP").
Definition StateBlob.h:672
constexpr T twoPi
2 * Pi (6.28318...).
Definition DspMath.h:51
static AnalogSection peak(double hz, double q, double gainDb) noexcept
Bell: gainDb at the centre, bandwidth hz / Q at half that gain in decibels.
static AnalogSection lowPass(double hz, double q=0.7071067811865476) noexcept
Second-order low-pass, gain Q at the corner.
static AnalogSection make(double b2, double b1, double b0, double a2, double a1, double a0) noexcept
Builds a section from its six coefficients.
static AnalogSection firstOrderLowPass(double hz) noexcept
First-order low-pass, -3 dB at the corner.
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 makeHighPass(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
High-pass filter.
Definition Biquad.h:143
static BiquadCoeffs makePeak(double sampleRate, double freq, double Q, double gainDb) noexcept
Peak (parametric EQ) filter.
Definition Biquad.h:201