177 using Options = std::conditional_t<Soft, OfflineSoftClipOptions, OfflineClipOptions>;
185 static constexpr double kTailTolerance = std::is_same_v<T, float> ? 1e-9 : 1e-10;
223 return state_ !=
nullptr;
231 return state_ ? state_->report :
Report{};
235 return state_ ?
sizeof(State) + state_->exclusions.retainedBytes() : 0;
238 [[nodiscard]] std::span<const OfflineRegion>
exclusions() const noexcept
240 return state_ ? state_->exclusions.view() : std::span<const OfflineRegion>{};
251 Curve curve = Curve::Sine;
252 double inputPeak = 0, targetGain = 1, featherFrames = 1;
255 std::unique_ptr<State> state_;
287 validateOptions(options);
290 OfflineSession job(jobOptions);
294 job.charge(
sizeof(
typename Plan::State));
296 plan.state_ = std::make_unique<typename Plan::State>();
297 auto &state = *plan.state_;
298 state.spec = analysis.
getSpec();
301 state.featherFrames = std::max(1., std::round(.005 * state.spec.sampleRate));
303 state.curve = options.curve;
304 state.exclusions.assign(job, options.exclusions, state.spec.frames);
305 const bool allExcluded = state.exclusions.covers(state.spec.frames);
306 auto &report = state.report;
307 report.requestedReductionDb = options.reductionDb;
308 report.oversamplingFactor = options.oversamplingFactor;
309 report.inputSamplePeakDb =
310 gainToDecibels(state.inputPeak, -std::numeric_limits<double>::infinity());
311 if (state.inputPeak > 0)
313 state.targetGain = offlineRepresentablePeakGain<T>(
316 report.representabilityLimited =
317 (state.targetGain == 1 && options.reductionDb > 0) ||
318 options.reductionDb - report.effectiveReductionDb > 1e-6;
320 state.active = options.reductionDb > 0 && state.inputPeak > 0 && state.targetGain < 1 &&
328 if (source.
getSpec() != state.spec)
331 result.memoryBytes = job.bytes();
332 result.plan = std::move(plan);
347 validateOptions(options);
349 if (!analyzed.succeeded())
351 result.
status = analyzed.status;
354 result =
makePlan(source, analyzed.analysis, options,
356 result.memoryBytes = std::max(analyzed.memoryBytes,
357 result.memoryBytes + analyzed.analysis.retainedBytes());
370 return renderCurve<ClipperCurve::Hard>(source, plan, sink, job);
373 const auto curve = plan.
isValid() ? plan.state_->curve : Curve::Sine;
377 return renderCurve<ClipperCurve::Sine>(source, plan, sink, job);
379 return renderCurve<ClipperCurve::Tanh>(source, plan, sink, job);
380 case Curve::GoldenRatio:
381 return renderCurve<ClipperCurve::GoldenRatio>(source, plan, sink, job);
389 template <
int MaxChannels>
394 return offlineRun(*
this, input, output, sampleRate, options, job);
398 static void validateOptions(
const Options &options)
400 const int factor = options.oversamplingFactor;
401 if (!std::isfinite(options.reductionDb) || (options.reductionDb < 0) ||
402 (options.reductionDb > 12) ||
403 (factor != 1 && factor != 2 && factor != 4 && factor != 8 && factor != 16))
406 if (options.curve != Curve::Sine && options.curve != Curve::Tanh &&
407 options.curve != Curve::GoldenRatio)
410 template <ClipperCurve C>
static double initialCeiling(
double target)
412 double low = 0, high = 1;
413 while (clipperShape<C>(1., high) < target && high < 1e12)
415 for (
int i = 0; i < 64; ++i)
417 const double middle = (low + high) / 2;
418 if (clipperShape<C>(1., middle) > target)
423 return (low + high) / 2;
426 template <ClipperCurve C>
427 static Result renderCurve(OfflineAudioSource<T> &source,
const Plan &plan,
428 OfflineAudioSink<T> &sink,
const OfflineJobOptions &options)
431 OfflineSinkTransaction<T> transaction;
436 const auto &state = *plan.state_;
437 const auto spec = state.spec;
438 if (source.getSpec() != spec)
440 result.report = state.report;
441 auto &report = result.report;
442 OfflineSession job(options);
444 const int blockLimit = std::min(4096, options.blockFrames);
445 OfflineBlock<T> input(job, spec, blockLimit), output(job, spec, blockLimit);
446 const double normalizer = state.inputPeak > 0 ? state.inputPeak : 1;
447 const double maximum =
static_cast<double>(std::numeric_limits<T>::max());
452 double operator()(std::int64_t)
const noexcept
457 using Cache = OfflineGainSource<T, UnityControl>;
462 void operator()(std::int64_t first,
int count,
double *values)
464 cache->readAudio(channel, first, count, values);
467 using Projection = offline_clip::BoundedClip<C, Reader>;
468 std::optional<Cache> cached;
469 std::optional<offline_clip::TailPolicy<C>> policy;
470 std::array<offline_clip::TailCertificate, 2> sourceStats;
471 bool sourceStatsReady =
false;
474 cached.emplace(source, spec, state.fingerprint, state.inputPeak, job, options,
476 const int order = report.oversamplingFactor <= 2 ? 18 : 10;
478 job.charge(
static_cast<std::size_t
>(6 * (order + 1) + (order + 3) * (2 * order + 1)) *
480 policy.emplace(report.oversamplingFactor);
484 report.compensatedLatencyFrames = 0;
485 result.memoryBytes = job.bytes();
487 struct ProgressContext
489 const OfflineJobOptions *options;
491 } progress{&options, spec.frames};
492 if (options.progress)
494 passOptions.progressContext = &progress;
495 passOptions.progress = [](
void *context, OfflineProgress)
497 const auto &p = *
static_cast<ProgressContext *
>(context);
499 return p.options->progress(p.options->progressContext,
506 OfflineSession passJob(passOptions);
507 OfflineMemoryPool scratch(passJob,
false);
508 passJob.useScratchResource(scratch);
509 std::array<std::optional<Projection>, 2> projections;
510 const auto pass = [&](
double ceiling,
bool publish)
514 if (cached && ceiling > 0)
517 std::array<offline_clip::TailCertificate, 2> shapeStats;
518 for (std::size_t leaf = 0; leaf < cached->leaves(); ++leaf)
520 const auto first =
static_cast<std::int64_t
>(leaf) * cached->block();
521 const int count =
static_cast<int>(
522 std::min<std::int64_t>(cached->block(), spec.frames - first));
523 for (
int c = 0; c < spec.channels; ++c)
525 const auto *raw = cached->audio(leaf, c);
526 for (
int i = 0; i < count; ++i)
528 const double x =
static_cast<double>(raw[i]) / normalizer;
529 if (!sourceStatsReady)
530 sourceStats[c].append(x);
531 shapeStats[c].append(clipperShape<C>(x, ceiling));
536 sourceStatsReady =
true;
537 std::array<offline_clip::TailPlan, 2> tails;
538 std::int64_t padding = 64;
539 for (
int c = 0; c < spec.channels; ++c)
541 tails[c] = policy->choose(ceiling, sourceStats[c], shapeStats[c],
543 padding = std::max(padding, tails[c].padding);
548 long double best = std::numeric_limits<long double>::infinity();
549 const long double extent =
550 static_cast<long double>(spec.frames) + 2.L * padding;
551 for (
int candidate = 128;
552 candidate <= 16384 && candidate * report.oversamplingFactor <= 65536;
555 const long double cost =
556 (1000.L * report.oversamplingFactor - 32) * candidate +
557 3456.L * extent / candidate;
564 for (
int c = 0; c < spec.channels; ++c)
567 if (projections[c] && projections[c]->hasGeometry(padding, grid))
568 projections[c]->reset(ceiling, tails[c].exterior);
570 projections[c].emplace(passJob, Reader{&*cached, c}, spec.frames,
571 padding, report.oversamplingFactor, ceiling,
572 tails[c].exterior, grid);
573 projections[c]->prepareProjection();
576 result.memoryBytes = std::max(result.memoryBytes, job.bytes() + passJob.bytes());
580 transaction.sink = &sink;
583 job.checkpoint(phase, 0, spec.frames);
586 OfflineClipMeasurement measured;
587 OfflineFingerprint fingerprint;
588 TruePeakDetector<double, 2> detector;
589 std::int64_t written = 0;
590 const auto consume = [&](std::int64_t first,
int count,
591 const std::array<const double *, 2> &filtered)
593 if (first != written)
595 for (
int offset = 0; offset < count;)
597 const auto at = first + offset;
598 int length = std::min(input.frames(), count - offset);
599 std::array<const T *, 2> raw{};
602 const auto leaf =
static_cast<std::size_t
>(at / cached->block());
603 const int local =
static_cast<int>(at % cached->block());
604 length = std::min(length, cached->block() - local);
605 for (
int c = 0; c < spec.channels; ++c)
606 raw[c] = cached->audio(leaf, c) + local;
610 auto block = input.view(length);
612 for (
int c = 0; c < spec.channels; ++c)
613 raw[c] = block.getChannel(c);
615 auto out = output.view(length);
616 for (
int f = 0; f < length; ++f)
620 ? 1 - state.exclusions.apply(at + f, 0, state.featherFrames)
622 for (
int c = 0; c < spec.channels; ++c)
624 const T rawValue = raw[c][f];
625 if (!std::isfinite(rawValue))
627 if (std::abs(
static_cast<double>(rawValue)) > state.inputPeak)
630 double normalized =
static_cast<double>(rawValue) / normalizer;
634 const double shaped =
635 ceiling == 0 ? 0 : filtered[c][offset + f];
636 normalized = std::lerp(normalized, shaped, mask);
637 if (!std::isfinite(normalized))
639 if (std::abs(normalized) > maximum / normalizer)
641 measured.representable =
false;
647 value =
static_cast<T
>(normalized * normalizer);
648 if (!std::isfinite(value))
650 normalized =
static_cast<double>(value) / normalizer;
653 measured.peak = std::max(measured.peak, std::abs(normalized));
656 out.getChannel(c)[f] = value;
657 measured.truePeak = std::max(
658 measured.truePeak, detector.processSample(normalized, c));
666 std::array<const T *, 2> pointers{};
667 for (
int c = 0; c < spec.channels; ++c)
668 pointers[c] = out.getChannel(c);
669 return sink.write(at, {pointers.data(), spec.channels, length});
673 job.checkpoint(phase, written, spec.frames);
676 if (cached && ceiling > 0)
678 for (
auto leaf = projections[0]->firstLeaf(); leaf < projections[0]->endLeaf();
681 std::array<const double *, 2> filtered{};
683 for (
int c = 0; c < spec.channels; ++c)
685 const auto data = projections[c]->get(leaf);
686 filtered[c] = data.data();
687 if (c && count !=
static_cast<int>(data.size()))
689 count =
static_cast<int>(data.size());
691 consume(projections[0]->leafOrigin(leaf), count, filtered);
695 while (written < spec.frames)
698 std::min<std::int64_t>(input.frames(), spec.frames - written)),
700 if (written != spec.frames || fingerprint != state.fingerprint ||
701 source.getSpec() != spec)
704 for (
int c = 0; c < spec.channels; ++c)
705 measured.truePeak = std::max(measured.truePeak, detector.getTailPeak(c));
708 OfflineClipCalibration calibrated;
713 [&](
double ceiling) { return pass(ceiling, false); });
714 report.calibrationPasses = calibrated.attempts;
715 report.normalizedCeiling = calibrated.ceiling;
716 report.targetErrorDb = calibrated.errorDb;
717 if (!calibrated.converged)
719 const bool constrained =
720 !calibrated.bracketed && !state.exclusions.view().empty();
727 const auto final = pass(calibrated.ceiling,
true);
728 if (state.active && (!
final.representable ||
final.peak != calibrated.peak))
730 constexpr double silence = -std::numeric_limits<double>::infinity();
731 report.outputSamplePeakDb =
final.peak > 0 ?
gainToDecibels(
final.peak, silence) +
734 report.outputTruePeakDb =
final.truePeak > 0 ?
gainToDecibels(
final.truePeak, silence) +
737 report.achievedReductionDb =
738 state.inputPeak > 0 &&
final.peak > 0 ? -
gainToDecibels(
final.peak) : 0;
740 report.targetMet = state.inputPeak > 0 &&
742 report.targetErrorDb);
743 if (state.active && !report.targetMet)
749 if (source.getSpec() != spec)
752 transaction.sink =
nullptr;