66 static_assert(std::is_same_v<T, float> || std::is_same_v<T, double>);
67 static_assert(std::atomic<float>::is_always_lock_free && std::atomic<int>::is_always_lock_free);
99 if (!validConfiguration(spec, options))
102 const int source = State::sourceFactor(spec.sampleRate);
103 const int colorLatency = Color::latencyFor(options.oversampling, source);
104 const auto hp = highPassLayout(spec.sampleRate, options.lowCutHz);
105 const int totalLatency = colorLatency + hp.order / 2 + hp.block;
106 const auto buffer = [](std::size_t channels, std::size_t frames, std::size_t bytes) {
107 return channels * ((frames * bytes + 31) / 32 * 32) + 64;
109 auto bytes =
sizeof(State) + 64 + 2 * Color::allocationBound(options.oversampling, source) +
110 buffer(2, 256,
sizeof(
double)) + buffer(1, 256,
sizeof(
double)) +
111 buffer(1, 256,
sizeof(
double)) + buffer(1, colorLatency,
sizeof(
double)) +
112 buffer(2, 256,
sizeof(T)) + buffer(2, totalLatency,
sizeof(T));
114 bytes += 3 * ((
static_cast<std::size_t
>(hp.order) + 1) *
sizeof(double) + 64) +
125 return prepare(spec, options_);
131 if (!validConfiguration(spec, options))
133 auto next = std::make_unique<State>(spec, options,
getWidth());
134 state_ = std::move(next);
136 latency_.store(state_->latency, std::memory_order_relaxed);
144 if (!std::isfinite(width) || width < 0 || width > 1)
146 width_.store(width, std::memory_order_relaxed);
152 return width_.load(std::memory_order_relaxed);
162 return latency_.load(std::memory_order_relaxed);
167 return static_cast<Status>(status_.load(std::memory_order_relaxed));
172 return state_ ? state_->frame : 0;
217 const int count = buffer.getNumSamples();
218 if (buffer.getNumChannels() != 2 || count > state_->spec.maxBlockSize ||
219 (!generatedDelta.empty() && generatedDelta.size() !=
static_cast<std::size_t
>(count)))
221 if (
static_cast<std::uint64_t
>(count) >
222 std::numeric_limits<std::uint64_t>::max() - state_->frame)
226 auto *left = buffer.getChannel(0);
227 auto *right = buffer.getChannel(1);
230 if (!generatedDelta.empty() &&
231 (!generatedDelta.data() ||
232 overlaps(generatedDelta.data(),
233 static_cast<std::uint64_t
>(generatedDelta.size()) *
sizeof(
double), left,
234 static_cast<std::uint64_t
>(count) *
sizeof(T)) ||
235 overlaps(generatedDelta.data(),
236 static_cast<std::uint64_t
>(generatedDelta.size()) *
sizeof(
double), right,
237 static_cast<std::uint64_t
>(count) *
sizeof(T))))
239 const auto a =
reinterpret_cast<std::uintptr_t
>(left);
240 const auto b =
reinterpret_cast<std::uintptr_t
>(right);
241 if (
static_cast<std::uint64_t
>(a > b ? a - b : b - a) <
242 static_cast<std::uint64_t
>(count) *
sizeof(T))
244 for (
int i = 0; i < count; ++i)
245 if (!std::isfinite(left[i]) || !std::isfinite(right[i]))
247 state_->width.setTargetValue(
getWidth());
248 for (
int offset = 0; offset < count;)
250 const int size = std::min(256, count - offset);
251 state_->process(buffer.getSubView(offset, size),
252 generatedDelta.empty()
253 ? std::span<double>{}
254 : generatedDelta.subspan(
static_cast<std::size_t
>(offset),
255 static_cast<std::size_t
>(size)));
262 [[nodiscard]] std::vector<std::uint8_t>
getState()
const
268 return writer.
blob();
275 bool setState(
const std::uint8_t *data, std::size_t size)
281 std::array<bool, 3> seen{};
282 for (
const auto &entry : reader.
entries())
284 const int index = entry.key ==
"width" ? 0
285 : entry.key ==
"oversampling" ? 1
286 : entry.key ==
"lowCutHz" ? 2
290 if (seen[index] || entry.type != (index == 1 ? 1 : 0))
297 if (!std::isfinite(width) || width < 0 || width > 1 || !validOptions(options))
300 width_.store(width, std::memory_order_relaxed);
305 struct HighPassLayout
307 int order = 0, block = 0;
308 bool allReject =
false;
310 static HighPassLayout highPassLayout(
double rate,
double lowCut)
noexcept
312 HighPassLayout result;
315 const double transition =
316 std::min(std::max(50., lowCut * .25), std::min(lowCut * 1.5, rate - 2 * lowCut));
317 if (lowCut >= rate * .5 || transition < 30)
318 result.allReject =
true;
322 static_cast<int>(std::ceil(94 / (2.285 * twoPi<double> * transition / rate)));
323 if (result.order & 1)
326 while (result.block * 2 <= std::max(64,
static_cast<int>(std::round(rate / 93.75))))
331 static bool overlaps(
const void *left, std::uint64_t leftBytes,
const void *right,
332 std::uint64_t rightBytes)
noexcept
334 const auto a =
reinterpret_cast<std::uintptr_t
>(left);
335 const auto b =
reinterpret_cast<std::uintptr_t
>(right);
336 return a <= b ? b - a < leftBytes : a - b < rightBytes;
340 detail::TptSvfState<double> state{};
342 double rate, base, corridor, g = 0, gain = 0, dg = 0, dGain = 0;
345 void prepare(
int i,
double fs)
noexcept
349 const double first = i < 16 ? 210 : 45;
350 const double last = i < 16 ? std::min(14000., fs * .35) : 165;
351 corridor = std::log(last / first) / (i < 16 ? 15 : 3);
352 base = first * std::exp((i < 16 ? i : i - 16) * corridor);
354 double coefficient(
double t)
const noexcept
358 std::exp(.22 * corridor *
359 std::sin(twoPi<double> * (.029 + index * .0017) * t + index * 2.399963));
360 return std::tan(pi<double> * f / rate);
362 double amplitude(
double t)
const noexcept
364 const double db = (((index / 2 + index % 2) & 1) == 0 ? 1 : -1) *
365 (2.6 + .4 * std::sin(twoPi<double> * (.037 + index * .0013) * t +
367 return std::expm1(db * std::log(10.) / 20);
369 void position(std::uint64_t frame)
noexcept
371 const auto offset =
static_cast<int>(frame % 64);
372 const double t =
static_cast<double>(frame - offset) / rate;
373 const double future = t + 64. / rate;
376 dg = (coefficient(future) - g) / 64;
377 dGain = (amplitude(future) - gain) / 64;
378 for (
int i = 0; i < offset; ++i)
383 untilUpdate = 64 - offset;
385 double process(
double input, std::uint64_t frame)
noexcept
387 if (untilUpdate == 0)
389 const double a1 = 1 / (1 + g * (g + .5));
390 const double a2 = g * a1;
391 const double a3 = g * a2;
403 std::array<Band, 20> bands{};
404 AudioBuffer<double>
copy, delta;
405 DryWetMixer<T, 2> dry;
406 DryWetMixer<double, 1> linear;
407 Convolver<double> highPass;
408 detail::StereoColor<detail::ClipperCurve::AsymmetricKnee> tube;
409 detail::StereoColor<detail::ClipperCurve::SymmetricKnee> tape;
410 SmoothedValue<double> width;
411 std::uint64_t frame = 0;
413 bool useHighPass =
false, allReject =
false, fault =
false;
415 State(AudioSpec environment, Options options,
float initialWidth)
416 : spec(environment), tube(options.oversampling, sourceFactor(spec.sampleRate)),
417 tape(options.oversampling, sourceFactor(spec.sampleRate)),
latency(tube.
latency())
419 for (
int i = 0; i < 20; ++i)
420 bands[i].
prepare(i, spec.sampleRate);
422 delta.resize(1, 256);
423 linear.prepare({spec.sampleRate, 256, 1});
424 linear.setLatencyCompensation(tube.latency());
425 const auto hp = highPassLayout(spec.sampleRate, options.lowCutHz);
426 allReject = hp.allReject;
431 highPass.prepare(hp.block, taps.data(),
static_cast<int>(taps.size()));
432 latency += hp.order / 2 + hp.block;
435 dry.prepare({spec.sampleRate, 256, 2});
436 dry.setLatencyCompensation(latency);
437 width.prepare(spec.sampleRate, 5);
438 width.setSmoothingType(SmoothedValue<double>::SmoothingType::Linear);
439 reset(0, initialWidth);
441 static int sourceFactor(
double rate)
noexcept
443 return rate <= 48000 ? 8 : rate <= 96000 ? 4 : rate <= 192000 ? 2 : 1;
445 void reset(std::uint64_t position,
float targetWidth)
noexcept
448 for (
auto &band : bands)
451 band.position(position);
458 width.reset(targetWidth);
461 void process(AudioBufferView<T> input, std::span<double> generatedDelta)
noexcept
463 const int count = input.getNumSamples();
465 double *l =
copy.getChannel(0), *r =
copy.getChannel(1), *d = delta.getChannel(0);
468 for (
int i = 0; i < count; ++i)
471 for (
int j = 0; j < 20; ++j)
472 (j & 1 ? r[i] : l[i]) +=
473 bands[j].process(input.getChannel(j & 1)[i], frame + i);
474 d[i] = .5 * (l[i] - r[i]);
475 if (!std::isfinite(l[i]) || !std::isfinite(r[i]) || !std::isfinite(d[i]))
480 linear.pushDry(delta.toView().getSubView(0, count));
481 double *lc[]{l}, *rc[]{r};
482 tube.process({lc, 1, count});
483 tape.process({rc, 1, count});
484 const auto *aligned = linear.getDryChannel(0);
485 for (
int i = 0; i < count; ++i)
486 d[i] = aligned[i] + .1 * (.5 * (l[i] - r[i]) - aligned[i]);
488 highPass.processInPlace(d, count);
489 for (
int i = 0; i < count; ++i)
490 if (!std::isfinite(d[i]))
493 std::fill_n(d, count, 0.);
496 const auto *dl = dry.getDryChannel(0), *dr = dry.getDryChannel(1);
497 std::array<double, 256> changes{};
498 for (
int i = 0; i < count; ++i)
500 const double w = width.getNextValue();
501 const double change = fault || w == 0 ? 0 : 8 * w * d[i];
502 const double outL =
static_cast<double>(dl[i]) + change;
503 const double outR =
static_cast<double>(dr[i]) - change;
504 if (!std::isfinite(outL) || !std::isfinite(outR) ||
505 std::abs(outL) > std::numeric_limits<T>::max() ||
506 std::abs(outR) > std::numeric_limits<T>::max())
510 for (
int i = 0; i < count; ++i)
512 if (!generatedDelta.empty())
513 generatedDelta[i] = fault ? 0 : changes[i];
515 input.getChannel(0)[i] =
516 fault || changes[i] == 0 ? dl[i] :
static_cast<T
>(dl[i] + changes[i]);
517 input.getChannel(1)[i] =
518 fault || changes[i] == 0 ? dr[i] :
static_cast<T
>(dr[i] - changes[i]);
520 frame +=
static_cast<std::uint64_t
>(count);
524 static bool validConfiguration(
const AudioSpec &spec, Options options)
noexcept
526 return spec.isValid() && spec.numChannels == 2 && (spec.sampleRate >= 8000) &&
527 (spec.sampleRate <= 384000) && validOptions(options);
529 static bool validOptions(Options options)
noexcept
531 return options.oversampling >= 1 && options.oversampling <= 16 &&
532 (options.oversampling & (options.oversampling - 1)) == 0 &&
533 std::isfinite(options.lowCutHz) &&
534 (options.lowCutHz == 0 || (options.lowCutHz >= 20 && options.lowCutHz <= 5000));
536 bool publish(
Status status)
noexcept
538 status_.store(
static_cast<int>(status), std::memory_order_relaxed);
541 std::unique_ptr<State> state_;
543 std::atomic<float> width_{0};