JS8Call-Improved master
Loading...
Searching...
No Matches
sic_refinement.h
Go to the documentation of this file.
1
5#pragma once
6
7#include <algorithm>
8#include <array>
9#include <cmath>
10#include <complex>
11#include <cstddef>
12#include <cstdlib>
13#include <limits>
14#include <numeric>
15#include <utility>
16#include <vector>
17
18namespace js8 {
20 std::vector<std::complex<float>> reference;
21 int timingAdjustSamples = 0;
22 float frequencyOffsetHz = 0.0f;
23 float driftHzPerSecond = 0.0f;
24 double nominalMetric = 0.0;
25 double refinedMetric = 0.0;
26 double phaseFitRmsHz = 0.0;
27 int phasePairs = 0;
28 bool refined = false;
29
30 // Part #5c: continuous linear timing drift. slope is sample-clock drift in
31 // samples per second; endToEnd is that slope integrated over the frame in
32 // samples (bounded to ~2); fitRMS is the regional-optimum residual in
33 // samples; regions is the count of useful regions feeding the fit.
34 double timingDriftSamplesPerSecond = 0.0;
35 double timingEndToEndSamples = 0.0;
36 double timingFitRmsSamples = 0.0;
37 int timingRegions = 0;
38 bool timingRefined = false;
39};
40
41// Continuous, phase-preserving fractional delay of a complex JS8 reference.
42//
43// A sample-clock drift is a time warp, not merely a waveform interpolation
44// problem. Linear Cartesian interpolation would systematically attenuate a
45// nonzero-carrier waveform, so unwrap the reference phase once and linearly
46// interpolate that phase (and magnitude). The returned vector has the same
47// length; source samples outside the frame become zero, matching the existing
48// #5b shift/edge convention.
49inline std::vector<std::complex<float>> applySicTimingWarp(
50 std::vector<std::complex<float>> const &reference,
51 double interceptSamples, double slopeSamplesPerSecond,
52 double sampleRate) {
53 std::size_t const length = reference.size();
54 if (length < 2 || !(sampleRate > 0.0) ||
55 !std::isfinite(interceptSamples) ||
56 !std::isfinite(slopeSamplesPerSecond))
57 return reference;
58
59 std::vector<double> unwrapped;
60 unwrapped.reserve(length);
61 double phase = std::arg(reference.front());
62 if (!std::isfinite(phase))
63 return reference;
64 unwrapped.push_back(phase);
65 for (std::size_t i = 1; i < length; ++i) {
66 if (!std::isfinite(reference[i].real()) ||
67 !std::isfinite(reference[i].imag()))
68 return reference;
69 double const step =
70 std::arg(reference[i] * std::conj(reference[i - 1]));
71 if (!std::isfinite(step))
72 return reference;
73 phase += step;
74 unwrapped.push_back(phase);
75 }
76
77 double const last = static_cast<double>(length - 1);
78 std::vector<std::complex<float>> warped(length, {0.0F, 0.0F});
79 for (std::size_t p = 0; p < length; ++p) {
80 double const time = static_cast<double>(p) / sampleRate;
81 double const source =
82 static_cast<double>(p) - (interceptSamples + slopeSamplesPerSecond * time);
83 if (!(source >= 0.0) || !(source <= last))
84 continue;
85 std::size_t const i0 = static_cast<std::size_t>(source);
86 std::size_t const i1 = std::min(i0 + 1, length - 1);
87 double const fraction = source - static_cast<double>(i0);
88 if (fraction == 0.0) {
89 // Preserve the original sample exactly at integer source indices.
90 warped[p] = reference[i0];
91 continue;
92 }
93 double const sourcePhase = unwrapped[i0] * (1.0 - fraction) +
94 unwrapped[i1] * fraction;
95 double const sourceMagnitude =
96 std::abs(reference[i0]) * (1.0 - fraction) +
97 std::abs(reference[i1]) * fraction;
98 warped[p] = std::polar(static_cast<float>(sourceMagnitude),
99 static_cast<float>(sourcePhase));
100 }
101 return warped;
102}
103
104// Wrap an angle to [-pi, pi] so phase residuals stay on the principal branch.
105inline double wrapSicPhase(double angle) {
106 constexpr double twoPi = 6.283185307179586476925286766559;
107 double wrapped = std::fmod(angle + 0.5 * twoPi, twoPi);
108 if (wrapped < 0.0)
109 wrapped += twoPi;
110 return wrapped - 0.5 * twoPi;
111}
112
113// Solve a 3x3 linear system by Gaussian elimination with partial pivoting.
114// Returns false for singular/degenerate systems. The tolerance is relative to
115// the matrix scale so both small and large correlation magnitudes are handled.
116inline bool solveSicLinearSystem3(double const normal[3][3],
117 double const right[3], double solution[3]) {
118 double augmented[3][4] = {};
119 double scale = 0.0;
120 for (int row = 0; row < 3; ++row) {
121 for (int column = 0; column < 3; ++column) {
122 augmented[row][column] = normal[row][column];
123 scale = std::max(scale, std::abs(normal[row][column]));
124 }
125 augmented[row][3] = right[row];
126 }
127 if (!(scale > 0.0) || !std::isfinite(scale))
128 return false;
129
130 for (int column = 0; column < 3; ++column) {
131 int pivot = column;
132 for (int row = column + 1; row < 3; ++row) {
133 if (std::abs(augmented[row][column]) >
134 std::abs(augmented[pivot][column]))
135 pivot = row;
136 }
137 for (int column2 = column; column2 < 4; ++column2)
138 std::swap(augmented[column][column2], augmented[pivot][column2]);
139 if (!(std::abs(augmented[column][column]) > 1.0e-12 * scale))
140 return false;
141 for (int row = 0; row < 3; ++row) {
142 if (row == column)
143 continue;
144 double const factor =
145 augmented[row][column] / augmented[column][column];
146 for (int column2 = column; column2 < 4; ++column2)
147 augmented[row][column2] -=
148 factor * augmented[column][column2];
149 }
150 }
151
152 for (int row = 0; row < 3; ++row) {
153 solution[row] = augmented[row][3] / augmented[row][row];
154 if (!std::isfinite(solution[row]))
155 return false;
156 }
157 return true;
158}
159
164inline int sicStartSample(float seconds) {
165 return static_cast<int>(std::round(static_cast<double>(seconds) * 12000.0));
166}
167
172template <int SymbolSamples, std::size_t Symbols, typename Samples, typename Tones>
174 std::vector<std::complex<float>> nominal, Samples const &samples,
175 Tones const &tones, float const dt, bool const allowTimingDrift) {
176 constexpr double sampleRate = 12000.0;
177 constexpr double twoPi = 6.283185307179586476925286766559;
178
179 SicRefinementResult result;
180 result.reference = std::move(nominal);
181 auto const originalReference = result.reference;
182
183 auto const correlationsFor =
184 [&](std::vector<std::complex<float>> const &reference,
185 int const nstart, int const symbolStride) {
186 std::array<std::complex<double>, Symbols> correlations{};
187 int const stride = std::max(symbolStride, 1);
188
189 for (std::size_t symbol = 0; symbol < Symbols;
190 symbol += static_cast<std::size_t>(stride)) {
191 std::size_t const referenceBegin = symbol * SymbolSamples;
192 std::size_t const referenceEnd = std::min(
193 referenceBegin + static_cast<std::size_t>(SymbolSamples),
194 reference.size());
195
196 for (std::size_t referenceIndex = referenceBegin;
197 referenceIndex < referenceEnd; ++referenceIndex) {
198 long long const sampleIndex =
199 static_cast<long long>(nstart) +
200 static_cast<long long>(referenceIndex);
201 if (sampleIndex < 0 ||
202 sampleIndex >= static_cast<long long>(samples.size()))
203 continue;
204
205 auto const r = std::complex<double>{
206 reference[referenceIndex].real(),
207 reference[referenceIndex].imag()};
208 correlations[symbol] +=
209 static_cast<double>(samples[static_cast<std::size_t>(sampleIndex)]) *
210 std::conj(r);
211 }
212 }
213
214 return correlations;
215 };
216
217 auto const correlationPower = [](auto const &correlations) {
218 return std::accumulate(
219 correlations.begin(), correlations.end(), 0.0,
220 [](double const total, auto const &value) {
221 return total + std::norm(value);
222 });
223 };
224
225 auto const metricFor = [&](auto const &reference, int const nstart,
226 int const symbolStride) {
227 return correlationPower(
228 correlationsFor(reference, nstart, symbolStride));
229 };
230
231 auto const applyPhaseModel = [&](auto &reference,
232 double const frequencyOffsetHz,
233 double const driftHzPerSecond) {
234 for (std::size_t i = 0; i < reference.size(); ++i) {
235 double const t = static_cast<double>(i) / sampleRate;
236 double const phase =
237 twoPi * (frequencyOffsetHz * t +
238 0.5 * driftHzPerSecond * t * t);
239 reference[i] *= std::complex<float>{
240 static_cast<float>(std::cos(phase)),
241 static_cast<float>(std::sin(phase))};
242 }
243 };
244
245 int const nominalStart = sicStartSample(dt);
246 result.nominalMetric = metricFor(result.reference, nominalStart, 1);
247 result.refinedMetric = result.nominalMetric;
248
249 if (!(result.nominalMetric > std::numeric_limits<double>::epsilon()) ||
250 !std::isfinite(result.nominalMetric))
251 return result;
252
253 // The complete decoded message gives us all transmitted tones. Refine the
254 // start time against short coherent windows around known tone transitions;
255 // those boundaries contain far more timing information than the interiors
256 // of constant-frequency symbols, where a sample shift mostly looks like a
257 // harmless phase rotation.
258 int bestStart = nominalStart;
259 int bestDelta = 0;
260 int const searchRadius = std::clamp(SymbolSamples / 16, 8, 120);
261 int const transitionHalfWindow = std::clamp(SymbolSamples / 8, 16, 160);
262
263 auto const transitionMetricOf =
264 [&](std::vector<std::complex<float>> const &ref, int const nstart) {
265 double metric = 0.0;
266 int transitions = 0;
267 for (std::size_t symbol = 1; symbol < Symbols; ++symbol) {
268 if (tones[symbol] == tones[symbol - 1])
269 continue;
270
271 long long const center =
272 static_cast<long long>(symbol) * SymbolSamples;
273 std::complex<double> correlation{};
274 for (int offset = -transitionHalfWindow;
275 offset < transitionHalfWindow; ++offset) {
276 long long const referenceIndex = center + offset;
277 long long const sampleIndex =
278 static_cast<long long>(nstart) + referenceIndex;
279 if (referenceIndex < 0 ||
280 referenceIndex >=
281 static_cast<long long>(ref.size()) ||
282 sampleIndex < 0 ||
283 sampleIndex >= static_cast<long long>(samples.size()))
284 continue;
285
286 auto const r = std::complex<double>{
287 ref[static_cast<std::size_t>(referenceIndex)].real(),
288 ref[static_cast<std::size_t>(referenceIndex)].imag()};
289 correlation +=
290 static_cast<double>(samples[static_cast<std::size_t>(sampleIndex)]) *
291 std::conj(r);
292 }
293 metric += std::norm(correlation);
294 ++transitions;
295 }
296 return std::pair<double, int>{metric, transitions};
297 };
298
299 // Convenience wrapper evaluating the transition correlation for the current
300 // (in-out) reference.
301 auto const transitionMetric = [&](int const nstart) {
302 return transitionMetricOf(result.reference, nstart);
303 };
304
305 auto const [nominalTransitionMetric, transitionCount] =
306 transitionMetric(nominalStart);
307 double bestTransitionMetric = nominalTransitionMetric;
308
309 if (transitionCount >= 6 && nominalTransitionMetric > 0.0) {
310 for (int delta = -searchRadius; delta <= searchRadius; delta += 4) {
311 auto const [metric, ignored] =
312 transitionMetric(nominalStart + delta);
313 (void)ignored;
314 if (metric > bestTransitionMetric) {
315 bestTransitionMetric = metric;
316 bestDelta = delta;
317 }
318 }
319
320 int const localStart = std::max(-searchRadius, bestDelta - 3);
321 int const localEnd = std::min(searchRadius, bestDelta + 3);
322 for (int delta = localStart; delta <= localEnd; ++delta) {
323 auto const [metric, ignored] =
324 transitionMetric(nominalStart + delta);
325 (void)ignored;
326 if (metric > bestTransitionMetric) {
327 bestTransitionMetric = metric;
328 bestDelta = delta;
329 }
330 }
331
332 // Require a visible transition-score gain and ensure that the ordinary
333 // full-frame metric is not materially degraded. #5a still performs the
334 // final before/after subtraction guard.
335 double const timingMetric =
336 metricFor(result.reference, nominalStart + bestDelta, 1);
337 bool const transitionImproved =
338 bestTransitionMetric >= nominalTransitionMetric * 1.005;
339 bool const fullFrameSafe =
340 std::isfinite(timingMetric) &&
341 timingMetric >= result.nominalMetric * 0.999;
342 if (transitionImproved && fullFrameSafe) {
343 bestStart = nominalStart + bestDelta;
344 result.timingAdjustSamples = bestDelta;
345 result.refinedMetric = timingMetric;
346 }
347 }
348
349 // With timing aligned, the per-symbol complex correlations expose the
350 // phase trajectory of the decoded signal. Adjacent phase differences give
351 // a residual-frequency measurement without needing an absolute channel
352 // phase. Fit a straight line in frequency, i.e. a quadratic phase model,
353 // to capture a constant offset plus linear drift.
354 auto const correlations = correlationsFor(result.reference, bestStart, 1);
355 std::array<double, Symbols> magnitudes{};
356 for (std::size_t i = 0; i < Symbols; ++i)
357 magnitudes[i] = std::abs(correlations[i]);
358
359 auto sortedMagnitudes = magnitudes;
360 std::nth_element(sortedMagnitudes.begin(),
361 sortedMagnitudes.begin() + sortedMagnitudes.size() / 2,
362 sortedMagnitudes.end());
363 double const medianMagnitude =
364 sortedMagnitudes[sortedMagnitudes.size() / 2];
365
366 if (medianMagnitude > std::numeric_limits<double>::epsilon() &&
367 std::isfinite(medianMagnitude)) {
368 double const symbolSeconds =
369 static_cast<double>(SymbolSamples) / sampleRate;
370 double const minimumMagnitude = 0.25 * medianMagnitude;
371 double const maximumWeight = 4.0 * medianMagnitude;
372 double sw = 0.0;
373 double swt = 0.0;
374 double swtt = 0.0;
375 double swy = 0.0;
376 double swty = 0.0;
377
378 for (std::size_t k = 0; k + 1 < Symbols; ++k) {
379 double const m0 = magnitudes[k];
380 double const m1 = magnitudes[k + 1];
381 if (m0 < minimumMagnitude || m1 < minimumMagnitude)
382 continue;
383
384 double const phaseStep =
385 std::arg(correlations[k + 1] * std::conj(correlations[k]));
386 double const residualHz = phaseStep / (twoPi * symbolSeconds);
387 double const t = static_cast<double>(k + 1) * symbolSeconds;
388 double const weight = std::min({m0, m1, maximumWeight});
389
390 sw += weight;
391 swt += weight * t;
392 swtt += weight * t * t;
393 swy += weight * residualHz;
394 swty += weight * t * residualHz;
395 ++result.phasePairs;
396 }
397
398 if (result.phasePairs >= 12 && sw > 0.0) {
399 double const meanFrequency = swy / sw;
400 double frequencyOffsetHz = meanFrequency;
401 double driftHzPerSecond = 0.0;
402 double const determinant = sw * swtt - swt * swt;
403
404 if (std::abs(determinant) >
405 std::numeric_limits<double>::epsilon()) {
406 frequencyOffsetHz =
407 (swy * swtt - swt * swty) / determinant;
408 driftHzPerSecond =
409 (sw * swty - swt * swy) / determinant;
410 }
411
412 double residualSum = 0.0;
413 for (std::size_t k = 0; k + 1 < Symbols; ++k) {
414 double const m0 = magnitudes[k];
415 double const m1 = magnitudes[k + 1];
416 if (m0 < minimumMagnitude || m1 < minimumMagnitude)
417 continue;
418
419 double const phaseStep = std::arg(
420 correlations[k + 1] * std::conj(correlations[k]));
421 double const residualHz =
422 phaseStep / (twoPi * symbolSeconds);
423 double const t = static_cast<double>(k + 1) * symbolSeconds;
424 double const weight = std::min({m0, m1, maximumWeight});
425 double const error =
426 residualHz - (frequencyOffsetHz + driftHzPerSecond * t);
427 residualSum += weight * error * error;
428 }
429
430 result.phaseFitRmsHz = std::sqrt(residualSum / sw);
431
432 bool const frequencyValid =
433 std::isfinite(meanFrequency) && std::abs(meanFrequency) <= 1.0;
434 bool const driftValid =
435 std::isfinite(frequencyOffsetHz) &&
436 std::isfinite(driftHzPerSecond) &&
437 std::isfinite(result.phaseFitRmsHz) &&
438 std::abs(frequencyOffsetHz) <= 1.0 &&
439 std::abs(driftHzPerSecond) <= 0.15 &&
440 std::abs(driftHzPerSecond) *
441 (static_cast<double>(Symbols) * symbolSeconds) <=
442 1.0 &&
443 result.phaseFitRmsHz <= 1.0;
444
445 auto bestReference = result.reference;
446 double bestMetric = result.refinedMetric;
447 double chosenFrequency = 0.0;
448 double chosenDrift = 0.0;
449
450 if (frequencyValid) {
451 auto candidate = result.reference;
452 applyPhaseModel(candidate, meanFrequency, 0.0);
453 double const metric = metricFor(candidate, bestStart, 1);
454 if (std::isfinite(metric) &&
455 metric >= bestMetric * 1.0001) {
456 bestReference = std::move(candidate);
457 bestMetric = metric;
458 chosenFrequency = meanFrequency;
459 }
460 }
461
462 if (driftValid) {
463 auto candidate = result.reference;
464 applyPhaseModel(candidate, frequencyOffsetHz, driftHzPerSecond);
465 double const metric = metricFor(candidate, bestStart, 1);
466 if (std::isfinite(metric) &&
467 metric >= bestMetric * 1.0001) {
468 bestReference = std::move(candidate);
469 bestMetric = metric;
470 chosenFrequency = frequencyOffsetHz;
471 chosenDrift = driftHzPerSecond;
472 }
473 }
474
475 result.reference = std::move(bestReference);
476 result.frequencyOffsetHz = static_cast<float>(chosenFrequency);
477 result.driftHzPerSecond = static_cast<float>(chosenDrift);
478 result.refinedMetric = bestMetric;
479 }
480 }
481
482 // Part #5c: sample-clock/timing drift across the frame. #5b aligns one
483 // global timing offset; the decoded 79-symbol waveform also lets us fit how
484 // that offset drifts linearly, timing(t) = tau0 + tau_dot * t.
485 //
486 // Slow (1-2 samples, end-to-end) drift is distributed sub-sample, so it is
487 // recovered from the phase trajectory across the whole frame rather than
488 // from the amplitude peak of a single broad transition window. Adjacent
489 // symbols with different tones expose the drift: their phase difference
490 // depends on the known instantaneous frequencies at the two centers. Those
491 // tone-transition pairs are grouped into six temporal regions. A bounded
492 // line is fit through the useful regional timing corrections and then
493 // applied as a continuous, phase-preserving warp. The warp is baked into
494 // result.reference, so subtractjs8 sees no change to its timing path and
495 // needs no new parameters. Skipped when disabled.
496 if (allowTimingDrift) {
497 constexpr std::size_t regionCount = 6;
498 constexpr std::size_t requiredRegions = 4;
499 constexpr std::size_t minRegionPairs = 2;
500 std::size_t const frameSamples =
501 Symbols * static_cast<std::size_t>(SymbolSamples);
502 std::size_t const refLen = result.reference.size();
503 if (refLen == frameSamples && frameSamples > 0) {
504 double const frameSeconds =
505 static_cast<double>(frameSamples) / sampleRate;
506
507 // End-to-end bound: at most ~2 samples across the whole frame, but
508 // also a small fraction of one symbol so short-symbol modes stay
509 // bounded (2.0 samples for every current mode).
510 double const maxEndToEndDrift =
511 std::min(2.0, 0.5 * static_cast<double>(SymbolSamples));
512
513 // Baseline whole-frame metric (non-degradation guard) and the #5b
514 // single global integer offset. bestStart already folds bestDelta.
515 double const baseWhole =
516 metricFor(result.reference, bestStart, 1);
517 auto const [baseTWM, baseTransitions] =
518 transitionMetricOf(result.reference, bestStart);
519 if (std::isfinite(baseWhole) && baseWhole > 0.0 &&
520 std::isfinite(baseTWM) && baseTWM > 0.0 &&
521 baseTransitions >= 6) {
522 // Instantaneous reference frequency within each symbol. Averaging
523 // the complex phasor over the central half of a symbol avoids the
524 // phase-slope discontinuity at its edges while retaining the
525 // baseband, data-tone, and accepted #5b frequency corrections.
526 std::array<double, Symbols> symbolFrequency{};
527 std::array<bool, Symbols> symbolFrequencyValid{};
528 for (std::size_t symbol = 0; symbol < Symbols; ++symbol) {
529 std::size_t const begin =
530 symbol * static_cast<std::size_t>(SymbolSamples);
531 std::size_t const end =
532 std::min(begin + static_cast<std::size_t>(SymbolSamples),
533 refLen);
534 if (end <= begin)
535 continue;
536
537 std::size_t const usable = end - begin;
538 std::size_t margin = usable / 4;
539 if (margin == 0)
540 margin = usable;
541 std::size_t first = begin + margin;
542 std::size_t last = (end > margin) ? end - margin : end;
543 if (last <= first + 1) {
544 first = begin;
545 last = end;
546 }
547 if (last <= first + 1)
548 continue;
549
550 std::complex<double> phasorSum{};
551 std::size_t phasorCount = 0;
552 for (std::size_t i = first; i + 1 < last; ++i) {
553 phasorSum += static_cast<std::complex<double>>(
554 result.reference[i + 1]) *
555 std::conj(static_cast<std::complex<double>>(
556 result.reference[i]));
557 ++phasorCount;
558 }
559 if (phasorCount == 0 ||
560 !(std::abs(phasorSum) > 0.0) ||
561 !std::isfinite(phasorSum.real()) ||
562 !std::isfinite(phasorSum.imag()))
563 continue;
564 double const omega = std::arg(phasorSum);
565 if (!std::isfinite(omega))
566 continue;
567 symbolFrequency[symbol] = omega;
568 symbolFrequencyValid[symbol] = true;
569 }
570
571 // Per-symbol complex correlations aligned with the accepted
572 // integer #5b offset. Their phases expose timing drift through
573 // the known frequency of each symbol.
574 auto const timingCorrelations =
575 correlationsFor(result.reference, bestStart, 1);
576 std::array<double, Symbols> timingMagnitudes{};
577 for (std::size_t i = 0; i < Symbols; ++i)
578 timingMagnitudes[i] = std::abs(timingCorrelations[i]);
579 auto sortedMagnitudes = timingMagnitudes;
580 std::nth_element(sortedMagnitudes.begin(),
581 sortedMagnitudes.begin() +
582 sortedMagnitudes.size() / 2,
583 sortedMagnitudes.end());
584 double const medianMagnitude =
585 sortedMagnitudes[sortedMagnitudes.size() / 2];
586 if (std::isfinite(medianMagnitude) &&
587 medianMagnitude >
588 std::numeric_limits<double>::epsilon()) {
589 double const minimumMagnitude = 0.25 * medianMagnitude;
590 double const maximumWeight = 4.0 * medianMagnitude;
591
592 struct TimingPhasePair {
593 double deltaTime;
594 double interceptGain;
595 double slopeGain;
596 double phase;
597 double weight;
598 double centerTime;
599 std::size_t region;
600 };
601 std::vector<TimingPhasePair> pairs;
602 pairs.reserve(Symbols);
603 std::array<std::size_t, regionCount> regionTransitionCounts{};
604
605 for (std::size_t symbol = 0; symbol + 1 < Symbols; ++symbol) {
606 if (tones[symbol + 1] == tones[symbol])
607 continue;
608 if (!symbolFrequencyValid[symbol] ||
609 !symbolFrequencyValid[symbol + 1])
610 continue;
611
612 double const magnitude0 =
613 timingMagnitudes[symbol];
614 double const magnitude1 =
615 timingMagnitudes[symbol + 1];
616 if (magnitude0 < minimumMagnitude ||
617 magnitude1 < minimumMagnitude)
618 continue;
619 double const weight =
620 std::min({magnitude0, magnitude1, maximumWeight});
621 if (!(weight > 0.0) || !std::isfinite(weight))
622 continue;
623
624 double const center0 =
625 (static_cast<double>(symbol) *
626 static_cast<double>(SymbolSamples) +
627 0.5 * static_cast<double>(SymbolSamples)) /
628 sampleRate;
629 double const center1 =
630 (static_cast<double>(symbol + 1) *
631 static_cast<double>(SymbolSamples) +
632 0.5 * static_cast<double>(SymbolSamples)) /
633 sampleRate;
634 double const interceptGain =
635 -(symbolFrequency[symbol + 1] -
636 symbolFrequency[symbol]);
637 if (!(std::abs(interceptGain) > 1.0e-9))
638 continue;
639 double const slopeGain =
640 -(symbolFrequency[symbol + 1] * center1 -
641 symbolFrequency[symbol] * center0);
642 std::complex<double> const pairProduct =
643 timingCorrelations[symbol + 1] *
644 std::conj(timingCorrelations[symbol]);
645 double const phase = std::arg(pairProduct);
646 if (!std::isfinite(phase))
647 continue;
648
649 std::size_t const region = std::min(
650 regionCount - 1,
651 (regionCount * (2 * symbol + 1)) / (2 * Symbols));
652 pairs.push_back(TimingPhasePair{
653 center1 - center0, interceptGain, slopeGain, phase,
654 weight, 0.5 * (center0 + center1), region});
655 ++regionTransitionCounts[region];
656 }
657
658 // Global seed line from the tone-transition pair phases. Absolute
659 // channel phase cancels in adjacent-symbol differences. A small
660 // residual carrier-frequency nuisance is retained diagnostically
661 // but never applied; only the timing intercept/slope below can
662 // alter the returned reference.
663 double residualFrequency = 0.0;
664 double seedIntercept = 0.0;
665 double seedSlope = 0.0;
666 bool phaseFit = false;
667 for (int iteration = 0; iteration < 8; ++iteration) {
668 double normal[3][3] = {};
669 double right[3] = {};
670 for (auto const &pair : pairs) {
671 double const coordinates[3] = {pair.deltaTime,
672 pair.interceptGain,
673 pair.slopeGain};
674 double const error = wrapSicPhase(
675 pair.phase -
676 (residualFrequency * pair.deltaTime +
677 seedIntercept * pair.interceptGain +
678 seedSlope * pair.slopeGain));
679 for (int row = 0; row < 3; ++row) {
680 right[row] += pair.weight * coordinates[row] * error;
681 for (int column = 0; column < 3; ++column)
682 normal[row][column] += pair.weight *
683 coordinates[row] *
684 coordinates[column];
685 }
686 }
687
688 double step[3] = {};
689 if (!solveSicLinearSystem3(normal, right, step)) {
690 phaseFit = false;
691 break;
692 }
693 residualFrequency += step[0];
694 seedIntercept += step[1];
695 seedSlope += step[2];
696 phaseFit = true;
697 }
698
699 if (phaseFit) {
700 // Regional intercepts around the seed line. Each useful bin
701 // supplies one locally preferred timing offset, weighted by
702 // its tone-difference timing information. Low-informativeness
703 // bins cannot steer the result.
704 struct RegionTimingAccumulator {
705 std::size_t pairs = 0;
706 double offsetNumerator = 0.0;
707 double offsetDenominator = 0.0;
708 double timeNumerator = 0.0;
709 };
710 std::array<RegionTimingAccumulator, regionCount>
711 regionAccumulators{};
712 for (auto const &pair : pairs) {
713 double const error = wrapSicPhase(
714 pair.phase -
715 (residualFrequency * pair.deltaTime +
716 seedIntercept * pair.interceptGain +
717 seedSlope * pair.slopeGain));
718 auto &accumulator =
719 regionAccumulators[pair.region];
720 ++accumulator.pairs;
721 accumulator.offsetNumerator +=
722 pair.weight * pair.interceptGain * error;
723 accumulator.offsetDenominator +=
724 pair.weight * pair.interceptGain * pair.interceptGain;
725 accumulator.timeNumerator += pair.weight *
726 pair.interceptGain *
727 pair.interceptGain *
728 pair.centerTime;
729 }
730
731 struct RegionTimingPoint {
732 double time;
733 double offset;
734 double weight;
735 };
736 std::vector<RegionTimingPoint> points;
737 points.reserve(regionCount);
738 for (std::size_t region = 0; region < regionCount; ++region) {
739 if (regionTransitionCounts[region] < minRegionPairs)
740 continue;
741 auto const &accumulator = regionAccumulators[region];
742 if (accumulator.pairs < minRegionPairs ||
743 !(accumulator.offsetDenominator > 0.0) ||
744 !std::isfinite(accumulator.offsetNumerator) ||
745 !std::isfinite(accumulator.offsetDenominator) ||
746 !std::isfinite(accumulator.timeNumerator))
747 continue;
748
749 double const regionalCorrection =
750 accumulator.offsetNumerator /
751 accumulator.offsetDenominator;
752 double const regionalTime =
753 accumulator.timeNumerator /
754 accumulator.offsetDenominator;
755 points.push_back(RegionTimingPoint{
756 regionalTime,
757 seedIntercept + seedSlope * regionalTime +
758 regionalCorrection,
759 accumulator.offsetDenominator});
760 }
761
762 // Final weighted straight line through the regional timing
763 // offsets. This is the reported #5c timing model.
764 if (points.size() >= requiredRegions) {
765 double sw = 0.0;
766 double swt = 0.0;
767 double swtt = 0.0;
768 double swy = 0.0;
769 double swty = 0.0;
770 for (auto const &point : points) {
771 sw += point.weight;
772 swt += point.weight * point.time;
773 swtt += point.weight * point.time * point.time;
774 swy += point.weight * point.offset;
775 swty += point.weight * point.time * point.offset;
776 }
777 double const determinant = sw * swtt - swt * swt;
778 double const solutionScale =
779 std::max({1.0, std::abs(sw), std::abs(swt),
780 std::abs(swtt)});
781 if (std::isfinite(determinant) &&
782 std::abs(determinant) >
783 1.0e-12 * solutionScale * solutionScale) {
784 double const finalIntercept =
785 (swy * swtt - swt * swty) / determinant;
786 double const finalSlope =
787 (sw * swty - swt * swy) / determinant;
788 double const endToEnd =
789 finalSlope * frameSeconds;
790
791 double residualSum = 0.0;
792 for (auto const &point : points) {
793 double const prediction =
794 finalIntercept + finalSlope * point.time;
795 double const error = point.offset - prediction;
796 residualSum += point.weight * error * error;
797 }
798 double const fitRMS = std::sqrt(residualSum / sw);
799 double const timeSpread =
800 swtt - swt * swt / sw;
801 double const residualVariance =
802 residualSum / static_cast<double>(
803 std::max<std::size_t>(
804 1, points.size() - 2));
805 double const slopeVariance =
806 (timeSpread > 0.0 &&
807 std::isfinite(residualVariance))
808 ? residualVariance / timeSpread
809 : std::numeric_limits<double>::quiet_NaN();
810 double const slopeStd =
811 std::sqrt(slopeVariance);
812 bool const slopeSignificant =
813 (slopeStd > 0.0 &&
814 std::abs(finalSlope) >=
815 4.0 * slopeStd) ||
816 (slopeStd == 0.0 && finalSlope != 0.0);
817
818 // Keep every fitted degree of the warp tightly
819 // bounded: residual intercept near the accepted #5b
820 // integer alignment, drift within the end-to-end
821 // budget, a coherent regional trend, a plausible
822 // one-Hz-equivalent residual-frequency nuisance,
823 // and a significant slope. All of these thresholds
824 // deserve later benchmarking against captured
825 // signals.
826 double const totalIntercept =
827 static_cast<double>(
828 result.timingAdjustSamples) +
829 finalIntercept;
830 // A continuous correction can revisit the accepted
831 // #5b integer alignment, but it must stay inside the
832 // #5b integer search envelope. Without an accepted
833 // integer move, only a sub-sample correction is
834 // allowed.
835 double const interceptBound =
836 (result.timingAdjustSamples == 0)
837 ? 1.0
838 : static_cast<double>(searchRadius);
839 bool const acceptedFit =
840 std::isfinite(finalIntercept) &&
841 std::isfinite(finalSlope) &&
842 std::isfinite(fitRMS) &&
843 std::abs(totalIntercept) <= interceptBound &&
844 std::abs(endToEnd) <= maxEndToEndDrift &&
845 fitRMS <= 0.05 &&
846 std::abs(residualFrequency) <= twoPi &&
847 slopeSignificant;
848 if (acceptedFit) {
849 auto warped = applySicTimingWarp(
850 result.reference, totalIntercept,
851 finalSlope, sampleRate);
852
853 // Keep the warp only when it improves the summed
854 // transition correlation without materially
855 // degrading the whole-frame #5a metric. The
856 // strict transition improvement avoids replacing
857 // a better #5b reference over numerical noise.
858 double const warpedTransition =
859 transitionMetricOf(warped, nominalStart)
860 .first;
861 double const warpedWhole =
862 metricFor(warped, nominalStart, 1);
863 if (std::isfinite(warpedTransition) &&
864 warpedTransition > baseTWM &&
865 std::isfinite(warpedWhole) &&
866 warpedWhole >= baseWhole * 0.999) {
867 result.reference = std::move(warped);
868 result.timingDriftSamplesPerSecond =
869 finalSlope;
870 result.timingEndToEndSamples = endToEnd;
871 result.timingFitRmsSamples = fitRMS;
872 result.timingRegions =
873 static_cast<int>(points.size());
874 result.timingRefined = true;
875 }
876 }
877 }
878 }
879 }
880 }
881 }
882 }
883 }
884
885 // subtractjs8() still receives the decoder's nominal dt. Encode the small
886 // accepted timing correction into the returned reference itself, keeping
887 // the vector length unchanged so the existing #5a symbol accounting stays
888 // bounded. Samples shifted off either edge are simply zeroed. Skip this
889 // integer shift entirely once a continuous warp has been baked above, since
890 // that warp already encodes the global integer optimum.
891 if (!result.timingRefined && result.timingAdjustSamples > 0) {
892 std::size_t const shift = std::min(
893 static_cast<std::size_t>(result.timingAdjustSamples),
894 result.reference.size());
895 std::move_backward(result.reference.begin(),
896 result.reference.end() - shift,
897 result.reference.end());
898 std::fill(result.reference.begin(), result.reference.begin() + shift,
899 std::complex<float>{0.0f, 0.0f});
900 } else if (!result.timingRefined && result.timingAdjustSamples < 0) {
901 std::size_t const shift = std::min(
902 static_cast<std::size_t>(-result.timingAdjustSamples),
903 result.reference.size());
904 std::move(result.reference.begin() + shift, result.reference.end(),
905 result.reference.begin());
906 std::fill(result.reference.end() - shift, result.reference.end(),
907 std::complex<float>{0.0f, 0.0f});
908 }
909
910 double const finalMetric = metricFor(result.reference, nominalStart, 1);
911 if (!std::isfinite(finalMetric) ||
912 finalMetric < result.nominalMetric * 0.999) {
913 // Keep #5b strictly additive: discard a refinement whose final shifted
914 // waveform measurably degrades the decoded-signal correlation metric.
915 result.reference = originalReference;
916 result.timingAdjustSamples = 0;
917 result.frequencyOffsetHz = 0.0f;
918 result.driftHzPerSecond = 0.0f;
919 result.refinedMetric = result.nominalMetric;
920 result.timingDriftSamplesPerSecond = 0.0;
921 result.timingEndToEndSamples = 0.0;
922 result.timingFitRmsSamples = 0.0;
923 result.timingRegions = 0;
924 result.timingRefined = false;
925 result.refined = false;
926 return result;
927 }
928
929 result.refinedMetric = metricFor(result.reference, nominalStart, 1);
930 result.refined = result.timingAdjustSamples != 0 ||
931 result.frequencyOffsetHz != 0.0f ||
932 result.driftHzPerSecond != 0.0f ||
933 result.timingRefined;
934 return result;
935}
936} // namespace js8
937
938// JS8.cpp currently defines genjs8refsig() and invokes it inline as the first
939// argument to subtractjs8(). Dispatch on macro argument count lets us leave the
940// member definition structurally unchanged (its std::array<int, NN> parameter
941// is seen as three preprocessor arguments because of the template comma) while
942// wrapping the ordinary two-argument call with post-decode refinement.
943// The caller's finalized fs supplies the timing also used for subtraction.
944#define JS8_SIC_GENREF_SELECT(_1, _2, _3, NAME, ...) NAME
945#define JS8_SIC_GENREF_DEFINITION(_1, _2, _3) \
946 genjs8refsigRaw(_1, _2, _3)
947#define JS8_SIC_GENREF_CALL(_itone, _f0) \
948 ([&]() { \
949 auto sicReference = genjs8refsigRaw(_itone, _f0); \
950 if (std::getenv("JS8_DISABLE_SIC_REFINEMENT") != nullptr) \
951 return sicReference; \
952 auto const allowTimingDrift = \
953 std::getenv("JS8_DISABLE_SIC_TIMING_DRIFT") == nullptr; \
954 auto sicRefinement = \
955 ::js8::refineSicReference<Mode::NSPS, NN>( \
956 std::move(sicReference), dd, _itone, fs.xdtSeconds, \
957 allowTimingDrift); \
958 if (decoder_js8().isDebugEnabled()) { \
959 double const metricGainDb = \
960 sicRefinement.nominalMetric > 0.0 && \
961 sicRefinement.refinedMetric > 0.0 \
962 ? 10.0 * std::log10(sicRefinement.refinedMetric / \
963 sicRefinement.nominalMetric) \
964 : 0.0; \
965 qCDebug(decoder_js8) \
966 << "SIC refinement" \
967 << "timingSamples" \
968 << sicRefinement.timingAdjustSamples \
969 << "frequencyOffsetHz" \
970 << sicRefinement.frequencyOffsetHz \
971 << "driftHzPerSecond" \
972 << sicRefinement.driftHzPerSecond \
973 << "phasePairs" << sicRefinement.phasePairs \
974 << "phaseFitRmsHz" << sicRefinement.phaseFitRmsHz \
975 << "timingDriftSamplesPerSecond" \
976 << sicRefinement.timingDriftSamplesPerSecond \
977 << "timingEndToEndSamples" \
978 << sicRefinement.timingEndToEndSamples \
979 << "timingFitRmsSamples" \
980 << sicRefinement.timingFitRmsSamples \
981 << "timingRegions" << sicRefinement.timingRegions \
982 << "metricGainDb" << metricGainDb \
983 << "accepted" << sicRefinement.refined; \
984 } \
985 return std::move(sicRefinement.reference); \
986 }())
987#define genjs8refsig(...) \
988 JS8_SIC_GENREF_SELECT(__VA_ARGS__, JS8_SIC_GENREF_DEFINITION, \
989 JS8_SIC_GENREF_CALL, JS8_SIC_GENREF_UNUSED) \
990 (__VA_ARGS__)
JS8 namespace for Kalman filter-based trackers.
Definition bp_math.h:12
int sicStartSample(float seconds)
Converts SIC timing to the nearest 12-kHz sample for fit and subtraction.
Definition sic_refinement.h:164
SicRefinementResult refineSicReference(std::vector< std::complex< float > > nominal, Samples const &samples, Tones const &tones, float const dt, bool const allowTimingDrift)
Refines a decoded reference while guarding its matched correlation.
Definition sic_refinement.h:173
Definition sic_refinement.h:19