DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
OfflineClip.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
10#include "../OfflineProcessing.h"
11#if DSPARK_HAS_OFFLINE
12#include "../../Analysis/OfflineEnergyAnalyzer.h"
13#include "../TruePeakDetector.h"
14#include "OfflineClipProjection.h"
15#include "OfflineGainSource.h"
16#include "OfflineWorker.h"
17#include <algorithm>
18#include <array>
19#include <cmath>
20#include <limits>
21#include <memory>
22#include <optional>
23#include <span>
24#include <type_traits>
25#include <utility>
26
27namespace dspark
28{
31{
32 Sine,
33 Tanh,
35};
36
37namespace detail
38{
40{
41 double reductionDb = 0;
43 std::span<const OfflineRegion> exclusions;
44};
49
51{
52 double peak = 0, truePeak = 0;
53 bool representable = true;
54};
56{
57 double ceiling = 1, peak = 0, errorDb = std::numeric_limits<double>::infinity();
58 int attempts = 0;
59 bool converged = false, bracketed = false;
60};
61
62inline double offlineClipPeakErrorDb(double peak, double target) noexcept
63{
64 return peak > 0 ? (20 / std::log(10.)) * std::log1p((peak - target) / target)
65 : -std::numeric_limits<double>::infinity();
66}
67
68// A fixed absolute dB tolerance can accept unity or even gain for a small
69// reduction request. Bound the error by half the representable reduction too.
70inline bool offlineClipTargetMet(double peak, double target, double errorDb) noexcept
71{
72 if (target == 1)
73 return peak == 1;
74 const double toleranceDb = std::min(.005, -(10 / std::log(10.)) * std::log1p(target - 1));
75 return peak < 1 && std::abs(errorDb) <= toleranceDb;
76}
77
78// Search the actual rounded output peak. The peak need not be monotone in the
79// ceiling: maintain a measured sign bracket and reset all DSP for every trial.
80// Neither a final limiter nor an output gain adjustment participates.
81template <class Render>
82OfflineClipCalibration offlineCalibrateClip(double initialCeiling, double target, Render render)
83{
84 constexpr int maximumPasses = 24;
86 const auto trial = [&](double ceiling)
87 {
88 const auto measured = render(ceiling);
89 ++best.attempts;
90 if (!(measured.peak >= 0) || !std::isfinite(measured.peak))
92 const double error = offlineClipPeakErrorDb(measured.peak, target);
93 if (measured.representable && std::abs(error) < std::abs(best.errorDb))
94 {
95 best.ceiling = ceiling;
96 best.peak = measured.peak;
97 best.errorDb = error;
98 }
99 best.converged = offlineClipTargetMet(best.peak, target, best.errorDb);
100 return measured.peak;
101 };
102 double lo = initialCeiling, hi = initialCeiling;
103 double fl = trial(initialCeiling), fh = fl;
104 if (best.converged)
105 return best;
106 if (fl < target)
107 {
108 while (best.attempts < maximumPasses && fh < target && hi < 1e12)
109 {
110 lo = hi;
111 fl = fh;
112 hi *= 2;
113 fh = trial(hi);
114 if (best.converged)
115 return best;
116 }
117 }
118 else
119 {
120 // The caller implements the exact zero-curve endpoint, including its
121 // exclusion mask. An arbitrary tiny positive ceiling is both more
122 // expensive and less reliable as the lower calibration bracket.
123 lo = 0;
124 fl = trial(lo);
125 if (best.converged)
126 return best;
127 }
128 best.bracketed = fl < target && fh > target;
129 if (!best.bracketed)
130 return best;
131 double lowWeight = 1, highWeight = 1;
132 int previousSide = 0;
133 bool flatEndpoint = false;
134 while (best.attempts < maximumPasses)
135 {
136 // Illinois weighting prevents a nearly flat unity endpoint from
137 // pinning false position. Keep the actual measured sign bracket.
138 const double lowResidual = lowWeight * (target - fl);
139 const double highResidual = highWeight * (fh - target);
140 const double fraction = flatEndpoint
141 ? .5
142 : std::clamp(lowResidual / (lowResidual + highResidual), .1, .9);
143 const double ceiling = lo + fraction * (hi - lo);
144 if (!(ceiling > lo && ceiling < hi))
145 break;
146 const double peak = trial(ceiling);
147 if (best.converged)
148 return best;
149 if (peak > target)
150 {
151 // Rounded PCM can have an exactly flat region. Bisect it rather
152 // than spending repeated complete renders on the same peak.
153 flatEndpoint = peak == fh;
154 hi = ceiling;
155 fh = peak;
156 lowWeight = previousSide == 1 ? lowWeight * .5 : 1;
157 highWeight = 1;
158 previousSide = 1;
159 }
160 else
161 {
162 flatEndpoint = peak == fl;
163 lo = ceiling;
164 fl = peak;
165 highWeight = previousSide == -1 ? highWeight * .5 : 1;
166 lowWeight = 1;
167 previousSide = -1;
168 }
169 }
170 return best;
171}
172
173template <FloatType T, bool Soft> class OfflineClipProcessor
174{
175 public:
177 using Options = std::conditional_t<Soft, OfflineSoftClipOptions, OfflineClipOptions>;
185 static constexpr double kTailTolerance = std::is_same_v<T, float> ? 1e-9 : 1e-10;
197 struct Report
198 {
203 double targetErrorDb = 0;
204 double inputSamplePeakDb = -std::numeric_limits<double>::infinity();
205 double outputSamplePeakDb = -std::numeric_limits<double>::infinity();
206 double outputTruePeakDb = -std::numeric_limits<double>::infinity();
207 double normalizedCeiling = 1;
211 bool targetMet = false;
213 };
215 class Plan final
216 {
217 public:
218 Plan() = default;
219 Plan(Plan &&) noexcept = default;
220 Plan &operator=(Plan &&) noexcept = default;
221 [[nodiscard]] bool isValid() const noexcept
222 {
223 return state_ != nullptr;
224 }
225 [[nodiscard]] OfflineAudioSpec getSpec() const noexcept
226 {
227 return state_ ? state_->spec : OfflineAudioSpec{};
228 }
229 [[nodiscard]] Report getReport() const noexcept
230 {
231 return state_ ? state_->report : Report{};
232 }
233 [[nodiscard]] std::size_t retainedBytes() const noexcept
234 {
235 return state_ ? sizeof(State) + state_->exclusions.retainedBytes() : 0;
236 }
238 [[nodiscard]] std::span<const OfflineRegion> exclusions() const noexcept
239 {
240 return state_ ? state_->exclusions.view() : std::span<const OfflineRegion>{};
241 }
242
243 private:
245 struct State
246 {
247 OfflineAudioSpec spec;
248 OfflineFingerprint fingerprint;
249 OfflineExclusions exclusions;
250 Report report;
251 Curve curve = Curve::Sine;
252 double inputPeak = 0, targetGain = 1, featherFrames = 1;
253 bool active = false;
254 };
255 std::unique_ptr<State> state_;
256 };
258 {
261 std::size_t memoryBytes = 0;
262 [[nodiscard]] bool succeeded() const noexcept
263 {
264 return offlineSucceeded(status);
265 }
266 };
267 struct Result
268 {
271 std::size_t memoryBytes = 0;
272 [[nodiscard]] bool succeeded() const noexcept
273 {
274 return offlineSucceeded(status);
275 }
276 };
277
280 const typename OfflineEnergyAnalyzer<T>::Analysis &analysis,
281 const Options &options = {},
282 const OfflineJobOptions &jobOptions = {}) const
283 {
284 PlanResult result;
285 try
286 {
287 validateOptions(options);
288 if (!analysis.isValid())
290 OfflineSession job(jobOptions);
291 if (source.getSpec() != analysis.getSpec())
293 job.checkpoint(OfflinePhase::Plan, 0, analysis.getSpec().frames);
294 job.charge(sizeof(typename Plan::State));
295 Plan plan;
296 plan.state_ = std::make_unique<typename Plan::State>();
297 auto &state = *plan.state_;
298 state.spec = analysis.getSpec();
299 state.fingerprint = analysis.fingerprint();
300 state.inputPeak = analysis.samplePeak();
301 state.featherFrames = std::max(1., std::round(.005 * state.spec.sampleRate));
302 if constexpr (Soft)
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)
312 {
313 state.targetGain = offlineRepresentablePeakGain<T>(
314 state.inputPeak, decibelsToGain(-options.reductionDb));
315 report.effectiveReductionDb = -gainToDecibels(state.targetGain);
316 report.representabilityLimited =
317 (state.targetGain == 1 && options.reductionDb > 0) ||
318 options.reductionDb - report.effectiveReductionDb > 1e-6;
319 }
320 state.active = options.reductionDb > 0 && state.inputPeak > 0 && state.targetGain < 1 &&
321 !allExcluded;
322 report.reason = options.reductionDb == 0 ? Reason::ZeroAmount
323 : state.inputPeak == 0 ? Reason::NoSignal
324 : allExcluded ? Reason::AllExcluded
325 : state.targetGain == 1 ? Reason::RepresentabilityLimited
327 job.checkpoint(OfflinePhase::Plan, state.spec.frames, state.spec.frames);
328 if (source.getSpec() != state.spec)
330 result.status = state.active ? OfflineStatus::Success : OfflineStatus::NoChange;
331 result.memoryBytes = job.bytes();
332 result.plan = std::move(plan);
333 }
334 catch (...)
335 {
336 result.status = offlineExceptionStatus();
337 }
338 return result;
339 }
341 [[nodiscard]] PlanResult analyze(OfflineAudioSource<T> &source, const Options &options = {},
342 const OfflineJobOptions &job = {}) const
343 {
344 PlanResult result;
345 try
346 {
347 validateOptions(options);
348 auto analyzed = OfflineEnergyAnalyzer<T>().analyze(source, job);
349 if (!analyzed.succeeded())
350 {
351 result.status = analyzed.status;
352 return result;
353 }
354 result = makePlan(source, analyzed.analysis, options,
355 offlineRemaining(job, analyzed.analysis.retainedBytes()));
356 result.memoryBytes = std::max(analyzed.memoryBytes,
357 result.memoryBytes + analyzed.analysis.retainedBytes());
358 }
359 catch (...)
360 {
361 result.status = offlineExceptionStatus();
362 }
363 return result;
364 }
366 [[nodiscard]] Result render(OfflineAudioSource<T> &source, const Plan &plan,
367 OfflineAudioSink<T> &sink, const OfflineJobOptions &job = {}) const
368 {
369 if constexpr (!Soft)
370 return renderCurve<ClipperCurve::Hard>(source, plan, sink, job);
371 else
372 {
373 const auto curve = plan.isValid() ? plan.state_->curve : Curve::Sine;
374 switch (curve)
375 {
376 case Curve::Sine:
377 return renderCurve<ClipperCurve::Sine>(source, plan, sink, job);
378 case Curve::Tanh:
379 return renderCurve<ClipperCurve::Tanh>(source, plan, sink, job);
380 case Curve::GoldenRatio:
381 return renderCurve<ClipperCurve::GoldenRatio>(source, plan, sink, job);
382 }
383 Result result;
384 result.status = OfflineStatus::InvalidInput;
385 return result;
386 }
387 }
389 template <int MaxChannels>
390 [[nodiscard]] Result run(const AudioBuffer<T, MaxChannels> &input,
391 AudioBuffer<T, MaxChannels> &output, double sampleRate,
392 const Options &options = {}, const OfflineJobOptions &job = {}) const
393 {
394 return offlineRun(*this, input, output, sampleRate, options, job);
395 }
396
397 private:
398 static void validateOptions(const Options &options)
399 {
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))
405 if constexpr (Soft)
406 if (options.curve != Curve::Sine && options.curve != Curve::Tanh &&
407 options.curve != Curve::GoldenRatio)
409 }
410 template <ClipperCurve C> static double initialCeiling(double target)
411 {
412 double low = 0, high = 1;
413 while (clipperShape<C>(1., high) < target && high < 1e12)
414 high *= 2;
415 for (int i = 0; i < 64; ++i)
416 {
417 const double middle = (low + high) / 2;
418 if (clipperShape<C>(1., middle) > target)
419 high = middle;
420 else
421 low = middle;
422 }
423 return (low + high) / 2;
424 }
425
426 template <ClipperCurve C>
427 static Result renderCurve(OfflineAudioSource<T> &source, const Plan &plan,
428 OfflineAudioSink<T> &sink, const OfflineJobOptions &options)
429 {
430 Result result;
431 OfflineSinkTransaction<T> transaction;
432 try
433 {
434 if (!plan.isValid())
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);
443 job.checkpoint(OfflinePhase::Verify, 0, spec.frames);
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());
448 // Reuse the existing verified PCM cache. Unity control performs no
449 // gain processing; only its source validation and bounded reads are used.
450 struct UnityControl
451 {
452 double operator()(std::int64_t) const noexcept
453 {
454 return 1;
455 }
456 };
457 using Cache = OfflineGainSource<T, UnityControl>;
458 struct Reader
459 {
460 Cache *cache;
461 int channel;
462 void operator()(std::int64_t first, int count, double *values)
463 {
464 cache->readAudio(channel, first, count, values);
465 }
466 };
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;
472 if (state.active)
473 {
474 cached.emplace(source, spec, state.fingerprint, state.inputPeak, job, options,
475 UnityControl{});
476 const int order = report.oversamplingFactor <= 2 ? 18 : 10;
477 // All temporary inverseBoxPower vector requests, before construction.
478 job.charge(static_cast<std::size_t>(6 * (order + 1) + (order + 3) * (2 * order + 1)) *
479 sizeof(double));
480 policy.emplace(report.oversamplingFactor);
481 }
482 // Bilateral finite-source projection is evaluated at original indices;
483 // no causal source-frame delay is inserted and later removed.
484 report.compensatedLatencyFrames = 0;
485 result.memoryBytes = job.bytes();
486 auto passOptions = offlineRemaining(options, job.bytes());
487 struct ProgressContext
488 {
489 const OfflineJobOptions *options;
490 std::int64_t frames;
491 } progress{&options, spec.frames};
492 if (options.progress)
493 {
494 passOptions.progressContext = &progress;
495 passOptions.progress = [](void *context, OfflineProgress)
496 {
497 const auto &p = *static_cast<ProgressContext *>(context);
498 // Internal high-rate/padded clocks are not source positions.
499 return p.options->progress(p.options->progressContext,
500 {OfflinePhase::Verify, 0, p.frames});
501 };
502 }
503 // Keep allocation accounting and reusable storage alive across
504 // calibration. Geometry changes return their scratch to the same
505 // pool; only genuinely new upstream payload consumes the budget.
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)
511 {
512 const auto phase = publish ? OfflinePhase::Render : OfflinePhase::Verify;
513 job.checkpoint(OfflinePhase::Verify, 0, spec.frames);
514 if (cached && ceiling > 0)
515 {
516 cached->reset();
517 std::array<offline_clip::TailCertificate, 2> shapeStats;
518 for (std::size_t leaf = 0; leaf < cached->leaves(); ++leaf)
519 {
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)
524 {
525 const auto *raw = cached->audio(leaf, c);
526 for (int i = 0; i < count; ++i)
527 {
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));
532 }
533 }
534 job.checkpoint(OfflinePhase::Verify, first + count, spec.frames);
535 }
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)
540 {
541 tails[c] = policy->choose(ceiling, sourceStats[c], shapeStats[c],
543 padding = std::max(padding, tails[c].padding);
544 }
545 // Balance duration-sized moments against fixed FFT/cached PCM
546 // scratch. The actual allocations still enforce the job budget.
547 int grid = 128;
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;
553 candidate *= 2)
554 {
555 const long double cost =
556 (1000.L * report.oversamplingFactor - 32) * candidate +
557 3456.L * extent / candidate;
558 if (cost < best)
559 {
560 best = cost;
561 grid = candidate;
562 }
563 }
564 for (int c = 0; c < spec.channels; ++c)
565 {
566 cached->reset();
567 if (projections[c] && projections[c]->hasGeometry(padding, grid))
568 projections[c]->reset(ceiling, tails[c].exterior);
569 else
570 projections[c].emplace(passJob, Reader{&*cached, c}, spec.frames,
571 padding, report.oversamplingFactor, ceiling,
572 tails[c].exterior, grid);
573 projections[c]->prepareProjection();
574 }
575 }
576 result.memoryBytes = std::max(result.memoryBytes, job.bytes() + passJob.bytes());
577 // Prepare every owned DSP allocation before opening the destination.
578 if (publish)
579 {
580 transaction.sink = &sink;
581 offlineCallSink([&] { return sink.begin(spec); });
582 }
583 job.checkpoint(phase, 0, spec.frames);
584 if (cached)
585 cached->reset();
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)
592 {
593 if (first != written)
595 for (int offset = 0; offset < count;)
596 {
597 const auto at = first + offset;
598 int length = std::min(input.frames(), count - offset);
599 std::array<const T *, 2> raw{};
600 if (cached)
601 {
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;
607 }
608 else
609 {
610 auto block = input.view(length);
611 offlineRead(source, spec, at, block);
612 for (int c = 0; c < spec.channels; ++c)
613 raw[c] = block.getChannel(c);
614 }
615 auto out = output.view(length);
616 for (int f = 0; f < length; ++f)
617 {
618 const double mask =
619 state.active
620 ? 1 - state.exclusions.apply(at + f, 0, state.featherFrames)
621 : 0;
622 for (int c = 0; c < spec.channels; ++c)
623 {
624 const T rawValue = raw[c][f];
625 if (!std::isfinite(rawValue))
627 if (std::abs(static_cast<double>(rawValue)) > state.inputPeak)
629 offlineHash(fingerprint, rawValue);
630 double normalized = static_cast<double>(rawValue) / normalizer;
631 T value = rawValue;
632 if (mask != 0)
633 {
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)
640 {
641 measured.representable = false;
642 if (publish)
644 }
645 else
646 {
647 value = static_cast<T>(normalized * normalizer);
648 if (!std::isfinite(value))
650 normalized = static_cast<double>(value) / normalizer;
651 }
652 }
653 measured.peak = std::max(measured.peak, std::abs(normalized));
654 if (publish)
655 {
656 out.getChannel(c)[f] = value;
657 measured.truePeak = std::max(
658 measured.truePeak, detector.processSample(normalized, c));
659 }
660 }
661 }
662 if (publish)
664 [&]
665 {
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});
670 });
671 offset += length;
672 written += length;
673 job.checkpoint(phase, written, spec.frames);
674 }
675 };
676 if (cached && ceiling > 0)
677 {
678 for (auto leaf = projections[0]->firstLeaf(); leaf < projections[0]->endLeaf();
679 ++leaf)
680 {
681 std::array<const double *, 2> filtered{};
682 int count = 0;
683 for (int c = 0; c < spec.channels; ++c)
684 {
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());
690 }
691 consume(projections[0]->leafOrigin(leaf), count, filtered);
692 }
693 }
694 else
695 while (written < spec.frames)
696 consume(written,
697 static_cast<int>(
698 std::min<std::int64_t>(input.frames(), spec.frames - written)),
699 {});
700 if (written != spec.frames || fingerprint != state.fingerprint ||
701 source.getSpec() != spec)
703 if (publish)
704 for (int c = 0; c < spec.channels; ++c)
705 measured.truePeak = std::max(measured.truePeak, detector.getTailPeak(c));
706 return measured;
707 };
708 OfflineClipCalibration calibrated;
709 if (state.active)
710 {
711 calibrated =
712 offlineCalibrateClip(initialCeiling<C>(state.targetGain), state.targetGain,
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)
718 {
719 const bool constrained =
720 !calibrated.bracketed && !state.exclusions.view().empty();
721 report.reason =
725 }
726 }
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) +
732 gainToDecibels(normalizer, silence)
733 : silence;
734 report.outputTruePeakDb = final.truePeak > 0 ? gainToDecibels(final.truePeak, silence) +
735 gainToDecibels(normalizer, silence)
736 : silence;
737 report.achievedReductionDb =
738 state.inputPeak > 0 && final.peak > 0 ? -gainToDecibels(final.peak) : 0;
739 report.targetErrorDb = offlineClipPeakErrorDb(final.peak, state.targetGain);
740 report.targetMet = state.inputPeak > 0 &&
741 offlineClipTargetMet(final.peak, state.targetGain,
742 report.targetErrorDb);
743 if (state.active && !report.targetMet)
745 if (state.active)
746 report.reason = report.representabilityLimited ? Reason::RepresentabilityLimited
748 job.checkpoint(OfflinePhase::Render, spec.frames, spec.frames);
749 if (source.getSpec() != spec)
751 offlineCallSink([&] { return sink.commit(); });
752 transaction.sink = nullptr;
753 result.status = state.active ? OfflineStatus::Success : OfflineStatus::NoChange;
754 }
755 catch (...)
756 {
757 result.status = offlineExceptionStatus();
758 }
759 return result;
760 }
761};
762} // namespace detail
763} // namespace dspark
764#endif // DSPARK_HAS_OFFLINE
Owning audio buffer with contiguous, 32-byte aligned storage.
Transactional worker sink for arbitrarily long offline output.
Rewindable, complete-file source with int64 positions and bounded blocks.
virtual OfflineAudioSpec getSpec() const noexcept=0
Returns format and provenance by value.
Read-only source-bound energy map; owns bins, never source samples.
bool isValid() const noexcept
False for a failed or moved-from result.
OfflineFingerprint fingerprint() const noexcept
OfflineAudioSpec getSpec() const noexcept
Complete-file fixed-duration energy analysis for offline processors.
Result analyze(OfflineAudioSource< T > &source, const OfflineJobOptions &options={}) const
Analyzes a complete mono/stereo source, with no input mutation.
Immutable format/fingerprint/control plan, with owned exclusion regions.
std::size_t retainedBytes() const noexcept
OfflineAudioSpec getSpec() const noexcept
std::span< const OfflineRegion > exclusions() const noexcept
Borrowed regions, valid while the plan remains alive and unmoved.
Result run(const AudioBuffer< T, MaxChannels > &input, AudioBuffer< T, MaxChannels > &output, double sampleRate, const Options &options={}, const OfflineJobOptions &job={}) const
Owning render; aliasing is safe and failure leaves output unchanged.
PlanResult analyze(OfflineAudioSource< T > &source, const Options &options={}, const OfflineJobOptions &job={}) const
Analyzes the complete source and makes a reusable worker plan.
static constexpr double kTailTolerance
Bound on the omitted exterior tail of the clipped signal: the accuracy the analysis padding is sized ...
PlanResult makePlan(OfflineAudioSource< T > &source, const typename OfflineEnergyAnalyzer< T >::Analysis &analysis, const Options &options={}, const OfflineJobOptions &jobOptions={}) const
Reuses complete-source energy analysis; no PCM or filtered audio is retained.
Result render(OfflineAudioSource< T > &source, const Plan &plan, OfflineAudioSink< T > &sink, const OfflineJobOptions &job={}) const
Calibrates actual PCM, then verifies a provisional render before committing it.
std::conditional_t< Soft, OfflineSoftClipOptions, OfflineClipOptions > Options
void offlineFail(OfflineStatus status)
Processor::Result offlineRun(const Processor &processor, const AudioBuffer< T, MaxChannels > &input, AudioBuffer< T, MaxChannels > &output, double sampleRate, const Options &options, const OfflineJobOptions &job)
void offlineCallSink(Function &&function)
void offlineRead(OfflineAudioSource< T > &source, const OfflineAudioSpec &expected, std::int64_t first, AudioBufferView< T > block)
double offlineClipPeakErrorDb(double peak, double target) noexcept
Definition OfflineClip.h:62
void offlineHash(OfflineFingerprint &state, T sample) noexcept
bool offlineClipTargetMet(double peak, double target, double errorDb) noexcept
Definition OfflineClip.h:70
OfflineClipCalibration offlineCalibrateClip(double initialCeiling, double target, Render render)
Definition OfflineClip.h:82
OfflineJobOptions offlineRemaining(const OfflineJobOptions &job, std::size_t used)
OfflineStatus offlineExceptionStatus() noexcept
Main namespace for the DSPark framework.
bool offlineSucceeded(OfflineStatus status) noexcept
True for successful processing, including an explicit identity result.
T decibelsToGain(T dB, T minusInfinityDb=T(-100)) noexcept
Converts a value in decibels to linear gain.
Definition DspMath.h:77
OfflineSoftClipCurve
Soft curves shared with Clipper, including its sine approximation.
Definition OfflineClip.h:31
OfflineStatus
Explicit completion or no-publication outcome of an offline job.
@ TargetUnreachable
Exact protected PCM prevents the requested processing target.
T gainToDecibels(T gain, T minusInfinityDb=T(-100)) noexcept
Converts a linear gain value to decibels.
Definition DspMath.h:92
Immutable source format and host-provided content/timeline identity.
Noncryptographic PCM fingerprint, stable across block divisions.
Resource and cooperative-cancellation controls for one worker operation.
std::span< const OfflineRegion > exclusions
Copied source-frame regions; PCM stays exact.
Definition OfflineClip.h:43
double reductionDb
Positive sample-peak reduction, 0..12 dB; zero is exact identity.
Definition OfflineClip.h:41
int oversamplingFactor
Explicit local factor: 1, 2, 4, 8 or 16.
Definition OfflineClip.h:42
double effectiveReductionDb
After rounding the target toward the input PCM peak.
double normalizedCeiling
Curve ceiling divided by the complete-source peak.
bool targetMet
Set only after final rounded PCM verification.
double targetErrorDb
Final output peak relative to the effective target.
int compensatedLatencyFrames
Internal delay removed from the result.