Γ-W1-T7: make Preserve's splices pitch-synchronous — the jump is a whole number of the source's own period, detected once at load
30 Hz out-of-band energy 15.45% -> 0.00%; the 29 Hz rate-2.0 detune -133 -> +0 cents. An unknown period keeps the fixed-window geometry bit for bit. The detector cannot reach process(): sampler_core does not link it.
This commit is contained in:
@@ -0,0 +1,266 @@
|
||||
// Standalone tests for reasampler::instrument::engine::detectPeriod — the offline source-period
|
||||
// estimate behind Preserve's pitch-synchronous splices. No VST3, no REAPER, no test framework.
|
||||
//
|
||||
// Covers:
|
||||
// 1. accuracy on pure tones across the searched band, at 44.1k and 48k, including the
|
||||
// non-integer periods every real capture actually has — the splice jump is n periods, so
|
||||
// a fractional-frame error lands multiplied by n.
|
||||
// 2. the fundamental, not a harmonic: a sawtooth and a missing-fundamental stack must both
|
||||
// report the repeat period, which is what a splice has to align on.
|
||||
// 3. graceful degradation — noise, silence, and a source whose period changes mid-sample all
|
||||
// return NONE. That is the contract the shifter's fixed-window fallback rests on: an
|
||||
// estimate that is merely wrong would misalign every splice, which is worse than none.
|
||||
// 4. the band edges and the short-sample path.
|
||||
// 5. what the load pays, and that it does not grow with the sample length.
|
||||
|
||||
#include "../src/core/instrument/engine/period_detect.h"
|
||||
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <vector>
|
||||
|
||||
using namespace reasampler;
|
||||
using namespace reasampler::instrument::engine;
|
||||
|
||||
static int g_fail = 0;
|
||||
#define CHECK(cond) do { if(!(cond)) { \
|
||||
std::printf("FAIL line %d: %s\n", __LINE__, #cond); ++g_fail; } } while(0)
|
||||
|
||||
constexpr double kPi = 3.14159265358979323846;
|
||||
|
||||
static std::vector<AudioSample> sineOfPeriod(std::size_t frames, double period,
|
||||
double phase = 0.0) {
|
||||
std::vector<AudioSample> s(frames);
|
||||
for (std::size_t i = 0; i < frames; ++i) {
|
||||
s[i] = static_cast<AudioSample>(
|
||||
std::sin(2.0 * kPi * static_cast<double>(i) / period + phase));
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
// --- 1. Accuracy on pure tones -------------------------------------------------------------
|
||||
|
||||
static void testPureTonePeriodIsFoundToBetterThanATenthOfAFrame() {
|
||||
// Deliberately non-integer periods: an integer-only estimator passes an integer-period
|
||||
// sweep and still misaligns every real capture.
|
||||
const double periods[] = {23.7, 50.0, 100.25, 200.45, 441.0, 999.9, 1470.0, 2000.3, 2756.0};
|
||||
for (double p : periods) {
|
||||
const std::vector<AudioSample> src = sineOfPeriod(120000, p);
|
||||
const PeriodEstimate est = detectPeriod(src, 44100);
|
||||
CHECK(est.valid());
|
||||
if (!est.valid()) {
|
||||
std::printf(" period %.2f: NOT DETECTED\n", p);
|
||||
continue;
|
||||
}
|
||||
const double errFrames = std::fabs(est.frames - p);
|
||||
std::printf(" period %8.2f -> %8.4f (err %.4f fr, conf %.3f)\n", p, est.frames,
|
||||
errFrames, est.confidence);
|
||||
CHECK(errFrames < 0.1);
|
||||
CHECK(est.confidence > 0.8);
|
||||
}
|
||||
}
|
||||
|
||||
static void testTheEstimateIsInSourceFramesSoTheRateOnlyMovesTheBand() {
|
||||
// The same 30 Hz tone at two rates: the answer is frames, so it must track the rate. This
|
||||
// is what lets the shifter compare it against a window that is also in frames.
|
||||
for (int rate : {44100, 48000}) {
|
||||
const double p = static_cast<double>(rate) / 30.0;
|
||||
const std::vector<AudioSample> src = sineOfPeriod(160000, p);
|
||||
const PeriodEstimate est = detectPeriod(src, rate);
|
||||
CHECK(est.valid());
|
||||
if (est.valid()) {
|
||||
std::printf(" 30 Hz @ %d: %.3f fr (want %.3f)\n", rate, est.frames, p);
|
||||
CHECK(std::fabs(est.frames - p) < 0.5);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- 2. The fundamental, not a harmonic ----------------------------------------------------
|
||||
|
||||
static void testHarmonicRichSourceReportsTheRepeatPeriodNotAPartial() {
|
||||
// A sawtooth's strongest correlation dips at EVERY multiple of its period; a global-minimum
|
||||
// estimator picks 2P or 3P about as often as P. YIN's first-dip rule is what makes this
|
||||
// pass, and a jump quantized to 2P would splice a whole cycle out of phase half the time.
|
||||
const double p = 512.0;
|
||||
std::vector<AudioSample> src(120000);
|
||||
for (std::size_t i = 0; i < src.size(); ++i) {
|
||||
double v = 0.0;
|
||||
for (int h = 1; h <= 12; ++h) {
|
||||
v += std::sin(2.0 * kPi * h * static_cast<double>(i) / p) / h;
|
||||
}
|
||||
src[i] = static_cast<AudioSample>(0.5 * v);
|
||||
}
|
||||
const PeriodEstimate est = detectPeriod(src, 44100);
|
||||
CHECK(est.valid());
|
||||
if (est.valid()) {
|
||||
std::printf(" sawtooth P=512 -> %.3f\n", est.frames);
|
||||
CHECK(std::fabs(est.frames - p) < 1.0);
|
||||
}
|
||||
}
|
||||
|
||||
static void testMissingFundamentalStillReportsTheRepeatPeriod() {
|
||||
// Partials 2..6 of a 700-frame period: there is no energy AT the fundamental, but the
|
||||
// waveform still repeats every 700 frames — and repetition, not spectral content, is what
|
||||
// a splice has to land on.
|
||||
const double p = 700.0;
|
||||
std::vector<AudioSample> src(120000);
|
||||
for (std::size_t i = 0; i < src.size(); ++i) {
|
||||
double v = 0.0;
|
||||
for (int h = 2; h <= 6; ++h) {
|
||||
v += std::sin(2.0 * kPi * h * static_cast<double>(i) / p);
|
||||
}
|
||||
src[i] = static_cast<AudioSample>(0.2 * v);
|
||||
}
|
||||
const PeriodEstimate est = detectPeriod(src, 44100);
|
||||
CHECK(est.valid());
|
||||
if (est.valid()) {
|
||||
std::printf(" missing fundamental P=700 -> %.3f\n", est.frames);
|
||||
CHECK(std::fabs(est.frames - p) < 2.0);
|
||||
}
|
||||
}
|
||||
|
||||
// --- 3. Graceful degradation ---------------------------------------------------------------
|
||||
|
||||
static void testNoiseSilenceAndAPeriodChangeAllReportNone() {
|
||||
// White noise: no dip below the absolute threshold anywhere.
|
||||
{
|
||||
std::vector<AudioSample> src(120000);
|
||||
std::uint32_t rng = 22222u;
|
||||
for (auto& x : src) {
|
||||
rng = rng * 1664525u + 1013904223u;
|
||||
x = static_cast<AudioSample>((static_cast<double>(rng >> 8) / 8388608.0) - 1.0);
|
||||
}
|
||||
const PeriodEstimate est = detectPeriod(src, 44100);
|
||||
std::printf(" white noise -> %s (%.3f)\n", est.valid() ? "DETECTED" : "none",
|
||||
est.frames);
|
||||
CHECK(!est.valid());
|
||||
}
|
||||
// Digital silence: the difference function is degenerate, not merely inconclusive.
|
||||
{
|
||||
const std::vector<AudioSample> src(120000, 0.0f);
|
||||
CHECK(!detectPeriod(src, 44100).valid());
|
||||
}
|
||||
// Two halves at genuinely different periods: the probes disagree, so there is no ONE
|
||||
// period, and reporting either half's would misalign every splice in the other half.
|
||||
{
|
||||
std::vector<AudioSample> src(160000);
|
||||
double phase = 0.0;
|
||||
for (std::size_t i = 0; i < src.size(); ++i) {
|
||||
phase += 2.0 * kPi / (i < 80000 ? 300.0 : 700.0);
|
||||
src[i] = static_cast<AudioSample>(std::sin(phase));
|
||||
}
|
||||
const PeriodEstimate est = detectPeriod(src, 44100);
|
||||
std::printf(" period change 300->700 -> %s (%.3f)\n", est.valid() ? "DETECTED" : "none",
|
||||
est.frames);
|
||||
CHECK(!est.valid());
|
||||
}
|
||||
// Degenerate inputs.
|
||||
CHECK(!detectPeriod({}, 44100).valid());
|
||||
CHECK(!detectPeriod(sineOfPeriod(120000, 441.0), 0).valid());
|
||||
}
|
||||
|
||||
static void testAPercussiveDecayIsNotForcedIntoAPeriod() {
|
||||
// Filtered noise with a fast decay — the shape of a one-shot drum hit. Nothing repeats, so
|
||||
// the answer must be none rather than whatever the envelope's own length looks like.
|
||||
std::vector<AudioSample> src(120000);
|
||||
std::uint32_t rng = 909090u;
|
||||
double lp = 0.0;
|
||||
for (std::size_t i = 0; i < src.size(); ++i) {
|
||||
rng = rng * 1664525u + 1013904223u;
|
||||
const double n = (static_cast<double>(rng >> 8) / 8388608.0) - 1.0;
|
||||
lp += 0.25 * (n - lp);
|
||||
const double env = std::exp(-static_cast<double>(i % 22050) / 2000.0);
|
||||
src[i] = static_cast<AudioSample>(lp * env);
|
||||
}
|
||||
const PeriodEstimate est = detectPeriod(src, 44100);
|
||||
std::printf(" percussive decay -> %s (%.3f)\n", est.valid() ? "DETECTED" : "none",
|
||||
est.frames);
|
||||
CHECK(!est.valid());
|
||||
}
|
||||
|
||||
// --- 4. Band edges and short sources -------------------------------------------------------
|
||||
|
||||
static void testBelowTheBandReportsNoneAndAboveItReportsAWholeMultiple() {
|
||||
// Below kPeriodDetectMinHz: none. This is the load-bearing edge — such a period cannot fit
|
||||
// the splice jump anyway, so an answer here would only be one the shifter must reject.
|
||||
const std::vector<AudioSample> low = sineOfPeriod(200000, 44100.0 / 8.0); // 8 Hz
|
||||
CHECK(!detectPeriod(low, 44100).valid());
|
||||
|
||||
// Above kPeriodDetectMaxHz the search floor sits well above the true period, so what comes
|
||||
// back is a WHOLE MULTIPLE of it — which is still an exactly aligned splice target, since
|
||||
// every multiple of a period is a period. That is why the high edge needs no special
|
||||
// handling: being outside the band costs nothing, because alignment was never in question
|
||||
// for a tone this short-period.
|
||||
const double p = 44100.0 / 6000.0; // 7.35 frames
|
||||
const PeriodEstimate high = detectPeriod(sineOfPeriod(120000, p), 44100);
|
||||
std::printf(" 6 kHz (P=%.3f) -> %s (%.3f, = %.3f periods)\n", p,
|
||||
high.valid() ? "detected" : "none", high.frames, high.frames / p);
|
||||
if (high.valid()) {
|
||||
const double n = high.frames / p;
|
||||
CHECK(std::fabs(n - std::floor(n + 0.5)) < 0.02);
|
||||
}
|
||||
}
|
||||
|
||||
static void testAShortSourceShortensTheSearchRatherThanRefusing() {
|
||||
// A 12000-frame one-shot cannot host a full-band probe; the search band shortens to fit and
|
||||
// a 200-frame period is still found. Below that the answer is none, not a guess.
|
||||
const std::vector<AudioSample> shortSrc = sineOfPeriod(12000, 200.0);
|
||||
const PeriodEstimate est = detectPeriod(shortSrc, 44100);
|
||||
std::printf(" 12000-frame source, P=200 -> %s (%.3f)\n", est.valid() ? "detected" : "none",
|
||||
est.frames);
|
||||
CHECK(est.valid());
|
||||
if (est.valid()) CHECK(std::fabs(est.frames - 200.0) < 0.5);
|
||||
|
||||
// Too short for even the minimum lag: none.
|
||||
CHECK(!detectPeriod(sineOfPeriod(40, 20.0), 44100).valid());
|
||||
}
|
||||
|
||||
// --- 5. What the load pays ------------------------------------------------------------------
|
||||
|
||||
// The whole reason a detector is affordable in a sampler is that it runs ONCE, off the audio
|
||||
// thread, on a source that is already fully known. This prints what that once costs, and
|
||||
// asserts the property that makes it safe: the cost does NOT grow with the sample length —
|
||||
// a fixed number of fixed-size probes is analysed however long the capture is. Meaningful
|
||||
// only in a Release build; asserted as a RATIO so it holds at either optimization level.
|
||||
static void testDetectionCostIsBoundedRegardlessOfSampleLength() {
|
||||
double shortMs = 0.0, longMs = 0.0;
|
||||
for (std::size_t frames : {std::size_t{220500}, std::size_t{4410000}}) { // 5 s and 100 s
|
||||
const std::vector<AudioSample> src = sineOfPeriod(frames, 441.0);
|
||||
const int reps = 5;
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
double guard = 0.0;
|
||||
for (int r = 0; r < reps; ++r) guard += detectPeriod(src, 44100).frames;
|
||||
const double ms =
|
||||
1000.0 * std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count()
|
||||
/ reps;
|
||||
CHECK(guard > 0.0);
|
||||
std::printf(" [measure] detectPeriod over %7.1f s of source: %.3f ms\n",
|
||||
static_cast<double>(frames) / 44100.0, ms);
|
||||
(frames == 220500 ? shortMs : longMs) = ms;
|
||||
}
|
||||
// 20x the source for well under 2x the cost — the probes are fixed-size and fixed in
|
||||
// number, so the only length dependence left is the cache behaviour of reaching further
|
||||
// into the buffer.
|
||||
CHECK(longMs < shortMs * 2.0 + 0.5);
|
||||
}
|
||||
|
||||
int main() {
|
||||
testPureTonePeriodIsFoundToBetterThanATenthOfAFrame();
|
||||
testTheEstimateIsInSourceFramesSoTheRateOnlyMovesTheBand();
|
||||
testHarmonicRichSourceReportsTheRepeatPeriodNotAPartial();
|
||||
testMissingFundamentalStillReportsTheRepeatPeriod();
|
||||
testNoiseSilenceAndAPeriodChangeAllReportNone();
|
||||
testAPercussiveDecayIsNotForcedIntoAPeriod();
|
||||
testBelowTheBandReportsNoneAndAboveItReportsAWholeMultiple();
|
||||
testAShortSourceShortensTheSearchRatherThanRefusing();
|
||||
testDetectionCostIsBoundedRegardlessOfSampleLength();
|
||||
|
||||
if (g_fail == 0) {
|
||||
std::printf("all period_detect tests passed\n");
|
||||
return 0;
|
||||
}
|
||||
std::printf("%d period_detect check(s) failed\n", g_fail);
|
||||
return 1;
|
||||
}
|
||||
Reference in New Issue
Block a user