DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
LoopFinder.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
27#include "../Core/AudioBuffer.h"
28#include "../Core/DspMath.h"
29#include "../Core/FFT.h"
30#include "../Effects/Crossfade.h"
31
32#include <algorithm>
33#include <array>
34#include <cmath>
35#include <cstddef>
36#include <cstdint>
37#include <limits>
38#include <numbers>
39#include <utility>
40#include <vector>
41
42namespace dspark {
43
55template <FloatType T>
56class LoopFinder final
57{
58public:
72
73 struct Range {
74 std::int64_t first = 0;
75 std::int64_t last = -1;
76 };
77
78 struct Settings {
79 int comparisonLength = 1024;
80 int crossfadeLength = 256;
81 int coarseStride = 64;
83 std::uint32_t maxCoarsePairs = 131072;
84 std::uint32_t maxRefinementPairs = 262144;
85 T maximumCost = T(0.20);
86 T minimumActivityRms = T(1.0e-5);
87 };
88
89 struct Result {
91 std::int64_t start = 0;
92 std::int64_t end = 0;
94 T seamCost = T(1);
95
96 [[nodiscard]] explicit operator bool() const noexcept
97 {
98 return status == Status::Success;
99 }
100
101 [[nodiscard]] std::int64_t renderedLength() const noexcept
102 {
103 if (status != Status::Success || start < 0 || end < start
104 || crossfadeLength < 2)
105 return 0;
106
107 // Safe because 0 <= start <= end <= INT64_MAX.
108 const std::int64_t sourceLength = end - start;
109 const std::int64_t fade = static_cast<std::int64_t>(crossfadeLength);
110 if (fade > sourceLength / 2)
111 return 0;
112 return sourceLength - fade;
113 }
114 };
115
125 Range startRange,
126 Range endRange,
127 std::int64_t minLoopLength,
128 std::int64_t maxLoopLength,
129 const Settings& settings = {}) const
130 {
131 const int channels = audio.getNumChannels();
132 const int sampleCount = audio.getNumSamples();
133 if (channels == 0 || sampleCount == 0)
134 return failure(Status::EmptyInput);
135
136 if (channels < 1 || channels > kMaxChannels)
137 return failure(Status::InvalidArgument);
138 for (int ch = 0; ch < channels; ++ch)
139 if (audio.getChannel(ch) == nullptr)
140 return failure(Status::InvalidArgument);
141
142 // Every comparison below is parenthesised on purpose. Left bare in a
143 // template, MSVC reads `endRange.last < ... || endRange.last >` as a
144 // template argument list on a member name it has not resolved yet and
145 // rejects the whole predicate.
146 if (!validSettings(settings)
147 || (startRange.first < 0) || (startRange.last < startRange.first)
148 || (startRange.last >= static_cast<std::int64_t>(sampleCount))
149 || (endRange.first < 0) || (endRange.last < endRange.first)
150 || (endRange.last > static_cast<std::int64_t>(sampleCount))
151 || (minLoopLength < 1) || (maxLoopLength < minLoopLength)
152 || (maxLoopLength > static_cast<std::int64_t>(sampleCount)))
153 return failure(Status::InvalidArgument);
154
155 const std::int64_t window = settings.comparisonLength;
156 const std::int64_t fade = settings.crossfadeLength;
157 if (window == std::numeric_limits<std::int64_t>::max()
158 || fade > std::numeric_limits<std::int64_t>::max() / 2)
159 return failure(Status::InvalidArgument);
160 const std::int64_t minimumPeriod =
161 std::max(window + 1, fade * 2);
162
163 if (sampleCount > kMaxInputSamples)
164 return failure(Status::InputTooLong);
165
166 long double sourceScale = 0.0L;
167 for (int ch = 0; ch < channels; ++ch)
168 {
169 const T* const samples = audio.getChannel(ch);
170 for (int n = 0; n < sampleCount; ++n)
171 {
172 if (!std::isfinite(samples[n]))
173 return failure(Status::NonFiniteInput);
174 sourceScale = std::max(sourceScale,
175 std::abs(static_cast<long double>(samples[n])));
176 }
177 }
178
179 if (sampleCount < minimumPeriod)
180 return failure(Status::InputTooShort);
181
182 bool sourceHasActivity = false;
183 long double sourceVarianceSum = 0.0L;
184 int sourceActiveChannels = 0;
185 if (sourceScale > 0.0L)
186 {
187 for (int ch = 0; ch < channels; ++ch)
188 {
189 const T* const samples = audio.getChannel(ch);
190 long double mean = 0.0L;
191 for (int n = 0; n < sampleCount; ++n)
192 mean += static_cast<long double>(samples[n]) / sourceScale;
193 mean /= static_cast<long double>(sampleCount);
194
195 long double variance = 0.0L;
196 for (int n = 0; n < sampleCount; ++n)
197 {
198 const long double centered =
199 static_cast<long double>(samples[n]) / sourceScale - mean;
200 variance += centered * centered;
201 }
202 variance /= static_cast<long double>(sampleCount);
203 variance = std::clamp(variance, 0.0L, 1.0L);
204 const long double rms = sourceScale * std::sqrt(variance);
205 if (!std::isfinite(variance) || !std::isfinite(rms))
206 return failure(Status::NumericalFailure);
207 if (rms >= static_cast<long double>(settings.minimumActivityRms))
208 {
209 sourceHasActivity = true;
210 sourceVarianceSum += variance;
211 ++sourceActiveChannels;
212 }
213 }
214 }
215 if (!sourceHasActivity)
216 return failure(Status::InsufficientActivity);
217
218 const long double sourceRms = sourceScale * std::sqrt(std::min(
219 1.0L, sourceVarianceSum
220 / static_cast<long double>(sourceActiveChannels)));
221 if (!std::isfinite(sourceRms))
222 return failure(Status::NumericalFailure);
223
224 const std::uint64_t startCount = latticeCount(startRange, settings.coarseStride);
225 const std::uint64_t endCount = latticeCount(endRange, settings.coarseStride);
226 std::uint64_t coarseUpper = 0;
227 if (!checkedMultiply(startCount, endCount, coarseUpper))
228 return failure(Status::CandidateLimitExceeded);
229
230 const std::uint64_t seedUpper = std::min<std::uint64_t>(8u, coarseUpper);
231 const std::uint64_t radiusSpan =
232 static_cast<std::uint64_t>(settings.refinementRadius) * 2u + 1u;
233 const std::uint64_t startSpan = std::min(
234 static_cast<std::uint64_t>(startRange.last - startRange.first) + 1u,
235 radiusSpan);
236 const std::uint64_t endSpan = std::min(
237 static_cast<std::uint64_t>(endRange.last - endRange.first) + 1u,
238 radiusSpan);
239 std::uint64_t refinementUpper = 0;
240 std::uint64_t upperRectangle = 0;
241 if (!checkedMultiply(startSpan, endSpan, upperRectangle)
242 || !checkedMultiply(seedUpper, upperRectangle, refinementUpper)
243 || coarseUpper > settings.maxCoarsePairs
244 || refinementUpper > settings.maxRefinementPairs)
245 return failure(Status::CandidateLimitExceeded);
246
247 ScoringScratch scratch(settings.comparisonLength);
248 std::array<Candidate, 8> seeds {};
249 int seedCount = 0;
250 Candidate best {};
251 bool hasBest = false;
252
253 auto geometricallyValid = [&](std::int64_t start,
254 std::int64_t end) noexcept {
255 if (start < 0 || end <= start
256 || end > static_cast<std::int64_t>(sampleCount))
257 return false;
258 const std::int64_t period = end - start;
259 return period >= minimumPeriod
260 && period >= minLoopLength && period <= maxLoopLength;
261 };
262
263 auto consider = [&](std::int64_t start, std::int64_t end,
264 bool keepSeed) {
265 if (!geometricallyValid(start, end)) return ScoreState::Inactive;
266 Candidate candidate { start, end, T(1) };
267 const ScoreState state = scoreCandidate(audio, start, end,
268 settings, scratch,
269 candidate.cost);
270 if (state != ScoreState::Scored) return state;
271 if (!hasBest || better(candidate, best))
272 {
273 best = candidate;
274 hasBest = true;
275 }
276 if (keepSeed) insertSeed(seeds, seedCount, candidate);
277 return ScoreState::Scored;
278 };
279
280 for (std::uint64_t si = 0; si < startCount; ++si)
281 {
282 const std::int64_t start = startRange.first
283 + static_cast<std::int64_t>(si)
284 * static_cast<std::int64_t>(settings.coarseStride);
285 for (std::uint64_t ei = 0; ei < endCount; ++ei)
286 {
287 const std::int64_t end = endRange.first
288 + static_cast<std::int64_t>(ei)
289 * static_cast<std::int64_t>(settings.coarseStride);
290 if (consider(start, end, true) == ScoreState::NumericalFailure)
291 return failure(Status::NumericalFailure);
292 }
293 }
294
295 std::uint64_t exactRefinementAttempts = 0;
296 for (int seed = 0; seed < seedCount; ++seed)
297 {
298 const std::int64_t lowStart = std::max(startRange.first,
299 seeds[static_cast<std::size_t>(seed)].start
300 - settings.refinementRadius);
301 const std::int64_t highStart = std::min(startRange.last,
302 seeds[static_cast<std::size_t>(seed)].start
303 + settings.refinementRadius);
304 const std::int64_t lowEnd = std::max(endRange.first,
305 seeds[static_cast<std::size_t>(seed)].end
306 - settings.refinementRadius);
307 const std::int64_t highEnd = std::min(endRange.last,
308 seeds[static_cast<std::size_t>(seed)].end
309 + settings.refinementRadius);
310 const std::uint64_t widthStart =
311 static_cast<std::uint64_t>(highStart - lowStart) + 1u;
312 const std::uint64_t widthEnd =
313 static_cast<std::uint64_t>(highEnd - lowEnd) + 1u;
314 std::uint64_t rectangle = 0;
315 if (!checkedMultiply(widthStart, widthEnd, rectangle)
316 || exactRefinementAttempts > refinementUpper
317 || rectangle > refinementUpper - exactRefinementAttempts)
318 return failure(Status::NumericalFailure);
319 exactRefinementAttempts += rectangle;
320 }
321 if (exactRefinementAttempts > settings.maxRefinementPairs)
322 return failure(Status::CandidateLimitExceeded);
323
324 for (int seed = 0; seed < seedCount; ++seed)
325 {
326 const std::int64_t lowStart = std::max(startRange.first,
327 seeds[static_cast<std::size_t>(seed)].start
328 - settings.refinementRadius);
329 const std::int64_t highStart = std::min(startRange.last,
330 seeds[static_cast<std::size_t>(seed)].start
331 + settings.refinementRadius);
332 const std::int64_t lowEnd = std::max(endRange.first,
333 seeds[static_cast<std::size_t>(seed)].end
334 - settings.refinementRadius);
335 const std::int64_t highEnd = std::min(endRange.last,
336 seeds[static_cast<std::size_t>(seed)].end
337 + settings.refinementRadius);
338 for (std::int64_t start = lowStart; start <= highStart; ++start)
339 {
340 for (std::int64_t end = lowEnd; end <= highEnd; ++end)
341 {
342 if (consider(start, end, false)
343 == ScoreState::NumericalFailure)
344 return failure(Status::NumericalFailure);
345 }
346 }
347 }
348
349 if (!hasBest || best.cost > settings.maximumCost)
350 return failure(Status::NoAcceptableLoop);
351 return { Status::Success, best.start, best.end,
352 settings.crossfadeLength, best.cost };
353 }
354
359 [[nodiscard]] static Status renderLoop(AudioBufferView<const T> audio,
360 const Result& loop,
361 AudioBufferView<T> output) noexcept
362 {
363 const int channels = audio.getNumChannels();
364 const int sampleCount = audio.getNumSamples();
365 // Parenthesised for the same reason as the range check in find():
366 // bare, `loop.end < ... || loop.end >` reads as a template argument
367 // list to MSVC.
368 if (loop.status != Status::Success || (channels < 1)
369 || (channels > kMaxChannels) || (sampleCount <= 0)
370 || (loop.start < 0) || (loop.end <= loop.start)
371 || (loop.end > static_cast<std::int64_t>(sampleCount))
372 || (loop.crossfadeLength < 2)
373 || !std::isfinite(loop.seamCost) || (loop.seamCost < T(0))
374 || (loop.seamCost > T(1)))
376 for (int ch = 0; ch < channels; ++ch)
377 if (audio.getChannel(ch) == nullptr)
379
380 const std::int64_t period = loop.end - loop.start;
381 const std::int64_t fade = loop.crossfadeLength;
382 if (fade > period / 2)
384 const std::int64_t rendered = period - fade;
385 if (rendered <= 0 || rendered > std::numeric_limits<int>::max())
387
388 if (output.getNumChannels() != channels
389 || output.getNumSamples() != static_cast<int>(rendered))
391 for (int ch = 0; ch < channels; ++ch)
392 if (output.getChannel(ch) == nullptr)
394
395 const std::size_t sourceBytes = static_cast<std::size_t>(sampleCount)
396 * sizeof(T);
397 const std::size_t outputBytes = static_cast<std::size_t>(rendered)
398 * sizeof(T);
399 for (int outChannel = 0; outChannel < channels; ++outChannel)
400 {
401 const T* const destination = output.getChannel(outChannel);
402 for (int sourceChannel = 0; sourceChannel < channels; ++sourceChannel)
403 if (rangesOverlap(audio.getChannel(sourceChannel), sourceBytes,
404 destination, outputBytes))
406 for (int other = 0; other < outChannel; ++other)
407 if (rangesOverlap(output.getChannel(other), outputBytes,
408 destination, outputBytes))
410 }
411
412 for (int ch = 0; ch < channels; ++ch)
413 {
414 const T* const source = audio.getChannel(ch);
415 for (int n = 0; n < sampleCount; ++n)
416 if (!std::isfinite(source[n]))
418 if (!dryRenderChannel(source, loop))
420 }
421
422 for (int ch = 0; ch < channels; ++ch)
423 {
424 const T* const source = audio.getChannel(ch);
425 T* const destination = output.getChannel(ch);
426 std::copy_n(source + static_cast<std::ptrdiff_t>(loop.start),
427 static_cast<std::size_t>(rendered), destination);
428 Crossfade<T> crossfade;
430 for (int i = 0; i < loop.crossfadeLength; ++i)
431 destination[i] = renderOverlapSample(source, loop, i, crossfade);
432 }
433 return Status::Success;
434 }
435
436private:
437 static constexpr int kMaxChannels = 16;
438 static constexpr int kMaxInputSamples = 1 << 26;
439
440 enum class ScoreState : std::uint8_t { Inactive, Scored, NumericalFailure };
441
442 struct Candidate {
443 std::int64_t start = 0;
444 std::int64_t end = 0;
445 T cost = T(1);
446 };
447
448 struct ScoringScratch {
449 explicit ScoringScratch(int windowSize)
450 : fft(static_cast<std::size_t>(windowSize)),
451 window(static_cast<std::size_t>(windowSize)),
452 timeA(static_cast<std::size_t>(windowSize)),
453 timeB(static_cast<std::size_t>(windowSize)),
454 frequencyA(static_cast<std::size_t>(windowSize + 2)),
455 frequencyB(static_cast<std::size_t>(windowSize + 2))
456 {
457 for (int i = 0; i < windowSize; ++i)
458 {
459 window[static_cast<std::size_t>(i)] = T(0.5)
460 - T(0.5) * std::cos(T(2) * std::numbers::pi_v<T>
461 * static_cast<T>(i) / static_cast<T>(windowSize));
462 }
463 }
464
465 FFTReal<T> fft;
466 std::vector<T> window;
467 std::vector<T> timeA;
468 std::vector<T> timeB;
469 std::vector<T> frequencyA;
470 std::vector<T> frequencyB;
471 std::array<std::pair<long double, long double>, kMaxChannels> channelCosts {};
472 };
473
474 [[nodiscard]] static Result failure(Status status) noexcept
475 {
476 return { status, 0, 0, 0, T(1) };
477 }
478
479 [[nodiscard]] static bool validSettings(const Settings& settings) noexcept
480 {
481 const int window = settings.comparisonLength;
482 return window >= 64 && window <= 4096
483 && (window & (window - 1)) == 0
484 && settings.crossfadeLength >= 2
485 && settings.crossfadeLength <= window
486 && settings.coarseStride >= 1 && settings.coarseStride <= 4096
487 && settings.refinementRadius >= 0
488 && settings.refinementRadius <= 4096
489 && settings.maxCoarsePairs >= 1
490 && settings.maxCoarsePairs <= 1048576u
491 && settings.maxRefinementPairs >= 1
492 && settings.maxRefinementPairs <= 1048576u
493 && std::isfinite(settings.maximumCost)
494 && settings.maximumCost >= T(0) && settings.maximumCost <= T(1)
495 && std::isfinite(settings.minimumActivityRms)
496 && settings.minimumActivityRms > T(0)
497 && settings.minimumActivityRms <= T(1);
498 }
499
500 [[nodiscard]] static std::uint64_t latticeCount(Range range,
501 int stride) noexcept
502 {
503 return static_cast<std::uint64_t>(range.last - range.first)
504 / static_cast<std::uint64_t>(stride) + 1u;
505 }
506
507 [[nodiscard]] static bool checkedMultiply(std::uint64_t a,
508 std::uint64_t b,
509 std::uint64_t& result) noexcept
510 {
511 if (a != 0u && b > std::numeric_limits<std::uint64_t>::max() / a)
512 return false;
513 result = a * b;
514 return true;
515 }
516
517 [[nodiscard]] static bool better(const Candidate& lhs,
518 const Candidate& rhs) noexcept
519 {
520 return lhs.cost < rhs.cost
521 || (lhs.cost == rhs.cost
522 && (lhs.start < rhs.start
523 || (lhs.start == rhs.start && lhs.end < rhs.end)));
524 }
525
526 static void insertSeed(std::array<Candidate, 8>& seeds,
527 int& count,
528 Candidate candidate) noexcept
529 {
530 int position = 0;
531 while (position < count
532 && !better(candidate, seeds[static_cast<std::size_t>(position)]))
533 ++position;
534 if (position >= 8) return;
535 const int newCount = std::min(8, count + 1);
536 for (int i = newCount - 1; i > position; --i)
537 seeds[static_cast<std::size_t>(i)] =
538 seeds[static_cast<std::size_t>(i - 1)];
539 seeds[static_cast<std::size_t>(position)] = candidate;
540 count = newCount;
541 }
542
543 [[nodiscard]] static ScoreState scoreCandidate(
544 AudioBufferView<const T> audio,
545 std::int64_t start,
546 std::int64_t end,
547 const Settings& settings,
548 ScoringScratch& scratch,
549 T& outputCost) noexcept
550 {
551 const int channels = audio.getNumChannels();
552 const int window = settings.comparisonLength;
553 // renderLoop() overlaps source[end - fade + i] with source[start + i],
554 // so that lag, not period - window, is the one the seam must match.
555 // The window is centred on the overlap. A loop whose windows would
556 // leave the file takes the largest lag that fits.
557 const std::int64_t fade = settings.crossfadeLength;
558 const std::int64_t room =
559 static_cast<std::int64_t>(audio.getNumSamples()) - window;
560 const std::int64_t lag = std::min(end - start - fade, room);
561 const std::int64_t head = std::clamp<std::int64_t>(
562 start - (window - fade) / 2, 0, room - lag);
563 const std::int64_t tail = head + lag;
564 long double scale = 0.0L;
565 for (int ch = 0; ch < channels; ++ch)
566 {
567 const T* const source = audio.getChannel(ch);
568 for (int i = 0; i < window; ++i)
569 {
570 scale = std::max(scale, std::abs(static_cast<long double>(
571 source[tail + i])));
572 scale = std::max(scale, std::abs(static_cast<long double>(
573 source[head + i])));
574 }
575 }
576 if (scale == 0.0L) return ScoreState::Inactive;
577
578 std::array<long double, kMaxChannels> meanA {};
579 std::array<long double, kMaxChannels> meanB {};
580 std::array<long double, kMaxChannels> varianceA {};
581 std::array<long double, kMaxChannels> varianceB {};
582 std::array<bool, kMaxChannels> included {};
583 int includedCount = 0;
584 long double aggregateVarianceA = 0.0L;
585 long double aggregateVarianceB = 0.0L;
586
587 for (int ch = 0; ch < channels; ++ch)
588 {
589 const T* const source = audio.getChannel(ch);
590 for (int i = 0; i < window; ++i)
591 {
592 meanA[static_cast<std::size_t>(ch)] +=
593 static_cast<long double>(source[tail + i]) / scale;
594 meanB[static_cast<std::size_t>(ch)] +=
595 static_cast<long double>(source[head + i]) / scale;
596 }
597 meanA[static_cast<std::size_t>(ch)] /= window;
598 meanB[static_cast<std::size_t>(ch)] /= window;
599 for (int i = 0; i < window; ++i)
600 {
601 const long double a =
602 static_cast<long double>(source[tail + i]) / scale
603 - meanA[static_cast<std::size_t>(ch)];
604 const long double b =
605 static_cast<long double>(source[head + i]) / scale
606 - meanB[static_cast<std::size_t>(ch)];
607 varianceA[static_cast<std::size_t>(ch)] += a * a;
608 varianceB[static_cast<std::size_t>(ch)] += b * b;
609 }
610 varianceA[static_cast<std::size_t>(ch)] = std::clamp(
611 varianceA[static_cast<std::size_t>(ch)] / window, 0.0L, 1.0L);
612 varianceB[static_cast<std::size_t>(ch)] = std::clamp(
613 varianceB[static_cast<std::size_t>(ch)] / window, 0.0L, 1.0L);
614 const long double rmsA = scale * std::sqrt(
615 varianceA[static_cast<std::size_t>(ch)]);
616 const long double rmsB = scale * std::sqrt(
617 varianceB[static_cast<std::size_t>(ch)]);
618 if (!std::isfinite(rmsA) || !std::isfinite(rmsB))
619 return ScoreState::NumericalFailure;
620 if (std::max(rmsA, rmsB)
621 >= static_cast<long double>(settings.minimumActivityRms))
622 {
623 included[static_cast<std::size_t>(ch)] = true;
624 ++includedCount;
625 aggregateVarianceA += varianceA[static_cast<std::size_t>(ch)];
626 aggregateVarianceB += varianceB[static_cast<std::size_t>(ch)];
627 }
628 }
629 if (includedCount == 0) return ScoreState::Inactive;
630 const long double aggregateRmsA = scale * std::sqrt(std::min(1.0L,
631 aggregateVarianceA / static_cast<long double>(includedCount)));
632 const long double aggregateRmsB = scale * std::sqrt(std::min(1.0L,
633 aggregateVarianceB / static_cast<long double>(includedCount)));
634 if (!std::isfinite(aggregateRmsA) || !std::isfinite(aggregateRmsB))
635 return ScoreState::NumericalFailure;
636 if (aggregateRmsA < static_cast<long double>(settings.minimumActivityRms)
637 || aggregateRmsB
638 < static_cast<long double>(settings.minimumActivityRms))
639 return ScoreState::Inactive;
640
641 int costCount = 0;
642 long double maximumChannelCost = 0.0L;
643 for (int ch = 0; ch < channels; ++ch)
644 {
645 if (!included[static_cast<std::size_t>(ch)]) continue;
646 const T* const source = audio.getChannel(ch);
647 long double d0Numerator = 0.0L;
648 long double d0Denominator = 0.0L;
649 long double d1Numerator = 0.0L;
650 long double d1Denominator = 0.0L;
651 long double previousA = 0.0L;
652 long double previousB = 0.0L;
653 for (int i = 0; i < window; ++i)
654 {
655 const long double a =
656 static_cast<long double>(source[tail + i]) / scale;
657 const long double b =
658 static_cast<long double>(source[head + i]) / scale;
659 const long double difference = a - b;
660 d0Numerator += difference * difference;
661 d0Denominator += a * a + b * b;
662 if (i > 0)
663 {
664 const long double derivativeA = a - previousA;
665 const long double derivativeB = b - previousB;
666 const long double derivativeDifference =
667 derivativeA - derivativeB;
668 d1Numerator += derivativeDifference * derivativeDifference;
669 d1Denominator += derivativeA * derivativeA
670 + derivativeB * derivativeB;
671 }
672 previousA = a;
673 previousB = b;
674 scratch.timeA[static_cast<std::size_t>(i)] = static_cast<T>(
675 (a - meanA[static_cast<std::size_t>(ch)])
676 * scratch.window[static_cast<std::size_t>(i)]);
677 scratch.timeB[static_cast<std::size_t>(i)] = static_cast<T>(
678 (b - meanB[static_cast<std::size_t>(ch)])
679 * scratch.window[static_cast<std::size_t>(i)]);
680 }
681
682 const long double d0 = d0Denominator == 0.0L ? 0.0L
683 : std::clamp(0.5L * d0Numerator / d0Denominator, 0.0L, 1.0L);
684 const long double d1 = d1Denominator == 0.0L ? 0.0L
685 : std::clamp(0.5L * d1Numerator / d1Denominator, 0.0L, 1.0L);
686
687 scratch.fft.forward(scratch.timeA.data(), scratch.frequencyA.data());
688 scratch.fft.forward(scratch.timeB.data(), scratch.frequencyB.data());
689 const int bins = window / 2 + 1;
690 long double totalA = 0.0L;
691 long double totalB = 0.0L;
692 for (int bin = 0; bin < bins; ++bin)
693 {
694 const long double weight =
695 (bin == 0 || bin == bins - 1) ? 1.0L : 2.0L;
696 const long double ar = scratch.frequencyA[2 * bin];
697 const long double ai = scratch.frequencyA[2 * bin + 1];
698 const long double br = scratch.frequencyB[2 * bin];
699 const long double bi = scratch.frequencyB[2 * bin + 1];
700 totalA += weight * (ar * ar + ai * ai);
701 totalB += weight * (br * br + bi * bi);
702 }
703
704 long double djs = 0.0L;
705 if ((totalA == 0.0L) != (totalB == 0.0L))
706 {
707 djs = 1.0L;
708 }
709 else if (totalA != 0.0L)
710 {
711 long double divergenceA = 0.0L;
712 long double divergenceB = 0.0L;
713 for (int bin = 0; bin < bins; ++bin)
714 {
715 const long double weight =
716 (bin == 0 || bin == bins - 1) ? 1.0L : 2.0L;
717 const long double ar = scratch.frequencyA[2 * bin];
718 const long double ai = scratch.frequencyA[2 * bin + 1];
719 const long double br = scratch.frequencyB[2 * bin];
720 const long double bi = scratch.frequencyB[2 * bin + 1];
721 const long double probabilityA =
722 weight * (ar * ar + ai * ai) / totalA;
723 const long double probabilityB =
724 weight * (br * br + bi * bi) / totalB;
725 const long double midpoint =
726 (probabilityA + probabilityB) * 0.5L;
727 if (probabilityA > 0.0L)
728 divergenceA += probabilityA
729 * std::log(probabilityA / midpoint);
730 if (probabilityB > 0.0L)
731 divergenceB += probabilityB
732 * std::log(probabilityB / midpoint);
733 }
734 djs = std::clamp((divergenceA + divergenceB)
735 * 0.5L / std::numbers::ln2_v<long double>, 0.0L, 1.0L);
736 }
737
738 const long double channelCost = std::clamp(
739 0.45L * d0 + 0.20L * d1 + 0.35L * djs, 0.0L, 1.0L);
740 const long double channelWeight =
741 varianceA[static_cast<std::size_t>(ch)]
742 + varianceB[static_cast<std::size_t>(ch)];
743 if (!std::isfinite(d0) || !std::isfinite(d1)
744 || !std::isfinite(djs) || !std::isfinite(channelCost)
745 || !std::isfinite(channelWeight))
746 return ScoreState::NumericalFailure;
747 scratch.channelCosts[static_cast<std::size_t>(costCount++)] =
748 { channelWeight, channelCost };
749 maximumChannelCost = std::max(maximumChannelCost, channelCost);
750 }
751
752 std::sort(scratch.channelCosts.begin(),
753 scratch.channelCosts.begin() + costCount,
754 [](const auto& lhs, const auto& rhs) {
755 return lhs.first < rhs.first
756 || (lhs.first == rhs.first && lhs.second < rhs.second);
757 });
758 long double weightedCost = 0.0L;
759 long double totalWeight = 0.0L;
760 for (int i = 0; i < costCount; ++i)
761 {
762 weightedCost += scratch.channelCosts[static_cast<std::size_t>(i)].first
763 * scratch.channelCosts[static_cast<std::size_t>(i)].second;
764 totalWeight += scratch.channelCosts[static_cast<std::size_t>(i)].first;
765 }
766 if (!(totalWeight > 0.0L) || !std::isfinite(weightedCost)
767 || !std::isfinite(totalWeight))
768 return ScoreState::NumericalFailure;
769 const long double cost = std::clamp(
770 0.75L * weightedCost / totalWeight
771 + 0.25L * maximumChannelCost,
772 0.0L, 1.0L);
773 if (!std::isfinite(cost)) return ScoreState::NumericalFailure;
774 outputCost = static_cast<T>(cost);
775 return std::isfinite(outputCost)
776 ? ScoreState::Scored : ScoreState::NumericalFailure;
777 }
778
779 [[nodiscard]] static bool rangesOverlap(const void* first,
780 std::size_t firstBytes,
781 const void* second,
782 std::size_t secondBytes) noexcept
783 {
784 const auto firstBegin = reinterpret_cast<std::uintptr_t>(first);
785 const auto secondBegin = reinterpret_cast<std::uintptr_t>(second);
786 if (firstBytes > std::numeric_limits<std::uintptr_t>::max() - firstBegin
787 || secondBytes
788 > std::numeric_limits<std::uintptr_t>::max() - secondBegin)
789 return true;
790 const auto firstEnd = firstBegin + firstBytes;
791 const auto secondEnd = secondBegin + secondBytes;
792 return firstBegin < secondEnd && secondBegin < firstEnd;
793 }
794
795 [[nodiscard]] static T renderOverlapSample(const T* source,
796 const Result& loop,
797 int index,
798 Crossfade<T>& crossfade) noexcept
799 {
800 const T tail = source[loop.end - loop.crossfadeLength + index];
801 const T head = source[loop.start + index];
802 if (index == 0) return tail;
803 if (index == loop.crossfadeLength - 1) return head;
804 const T scale = std::max(std::abs(tail), std::abs(head));
805 if (scale == T(0)) return T(0);
806 const T position = static_cast<T>(index)
807 / static_cast<T>(loop.crossfadeLength - 1);
808 crossfade.setPosition(position);
809 const T mixed = crossfade.process(tail / scale, head / scale);
810 const T denominator = crossfade.getGainA() + crossfade.getGainB();
811 const T normalized = std::clamp(mixed / denominator, T(-1), T(1));
812 return scale * normalized;
813 }
814
815 [[nodiscard]] static bool dryRenderChannel(const T* source,
816 const Result& loop) noexcept
817 {
818 Crossfade<T> crossfade;
819 crossfade.setCurve(Crossfade<T>::Curve::EqualPower);
820 for (int i = 0; i < loop.crossfadeLength; ++i)
821 if (!std::isfinite(renderOverlapSample(source, loop, i, crossfade)))
822 return false;
823 return true;
824 }
825};
826
827} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
int getNumSamples() const noexcept
Returns the number of samples per channel.
int getNumChannels() const noexcept
Returns the number of channels in this view.
T * getChannel(int ch) const noexcept
Returns a pointer to the sample data for the given channel.
Artifact-free, SIMD-friendly crossfader for two audio signals.
Definition Crossfade.h:63
@ EqualPower
Sine/cosine law. Constant power, no volume drop, smooth at both ends.
void setCurve(Curve curve) noexcept
Sets the crossfade curve type. Thread-safe. Can be called from the GUI thread. A curve change is blen...
Definition Crossfade.h:118
Finds and renders bounded, deterministic loop seams.
Definition LoopFinder.h:57
Result find(AudioBufferView< const T > audio, Range startRange, Range endRange, std::int64_t minLoopLength, std::int64_t maxLoopLength, const Settings &settings={}) const
Searches explicit inclusive endpoint ranges for the lowest-cost supported loop seam.
Definition LoopFinder.h:124
static Status renderLoop(AudioBufferView< const T > audio, const Result &loop, AudioBufferView< T > output) noexcept
Renders one normalized equal-power loop cycle without allocation.
Definition LoopFinder.h:359
Main namespace for the DSPark framework.
std::int64_t renderedLength() const noexcept
Definition LoopFinder.h:101
std::uint32_t maxRefinementPairs
Definition LoopFinder.h:84