JS8Call-Improved master
Loading...
Searching...
No Matches
decoder_aided_redemod.h File Reference

Decoder-aided re-demodulation helpers for JS8 near-miss rescue. More...

#include <algorithm>
#include <array>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdlib>
#include <functional>
#include <limits>
#include <numbers>
#include <vector>
Include dependency graph for decoder_aided_redemod.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Classes

struct  js8::aided::ConfidenceSummary
struct  js8::aided::MidpointResidual
struct  js8::aided::SymbolBaseline
 First-pass per-symbol extraction metadata for the refinement baseline. More...
struct  js8::aided::Hypothesis
struct  js8::aided::Refinement

Namespaces

namespace  js8
 JS8 namespace for Kalman filter-based trackers.

Typedefs

using js8::aided::CostasTones = std::array<std::array<int, 7>, 3>

Functions

bool js8::aided::redemodEnabled ()
 Kill switch for decoder-aided re-demodulation.
constexpr bool js8::aided::isCostasSymbol (int k)
 Whether global symbol k is a known Costas pilot.
constexpr int js8::aided::dataSymbolIndex (int j)
void js8::aided::codewordToTones (std::array< int8_t, kCodeBits > const &cw, CostasTones const &costas, std::array< int, kTotalSymbols > &tones)
 Convert a tentative 174-bit codeword into 79 expected tones.
ConfidenceSummary js8::aided::tentativeConfidences (std::array< float, kCodeBits > const &llr)
 Confidence weight per tentative data symbol from its 3 bit LLRs.
void js8::aided::buildSymbolWeights (ConfidenceSummary const &conf, std::array< float, kTotalSymbols > &weights)
 Expand 58 data confidences to 79 per-symbol weights.
void js8::aided::buildCostasWeights (std::array< float, kTotalSymbols > &weights)
 Expand confidences to Costas-only weights (1.0 on pilots, else 0).
float js8::aided::aidedFrameXdt (float xdt2, int aidedDt, float dtSecondsPerSample)
 Scalar frame timing seed from an aided timing delta.
MidpointResidual js8::aided::aidedPhysicalResidualAtMidpoint (double aidedDf, double aidedDd, std::array< SymbolBaseline, kTotalSymbols > const &baselines, int window, double sampleRateHz, std::array< float, kTotalSymbols > const &weights)
 Physical carrier residual at the frame midpoint.
bool js8::aided::symbolBoundsValid (std::array< SymbolBaseline, kTotalSymbols > const &baselines, int window, int numSamples, int maxAbsDelta)
 Validate candidate sample bounds for the aided search/extraction.
bool js8::aided::replayTrackerCorrection (std::complex< float > *window, int count, double trackerHz, double sampleRateHz)
 Replay one symbol's recorded FrequencyTracker correction.
double js8::aided::contrastEight (double expectedPower, double const *otherPowers)
 Tone-CONTRAST metric from the actual 8 JS8 FSK bins.
Refinement js8::aided::refineSync (std::complex< float > const *samples, int numSamples, std::array< SymbolBaseline, kTotalSymbols > const &baselines, int window, double sampleRateHz, std::array< int, kTotalSymbols > const &tones, std::array< float, kTotalSymbols > const &weights, std::function< bool()> const &shouldCancel={})
 Bounded local sync refinement around the first-pass solution.
bool js8::aided::refinementAccepted (Refinement const &r)
 Safety gate: accept the refined sync only when it is finite, off the search boundary, and measurably better than baseline (>= 0.5% gain, or any positive metric over a degenerate zero baseline).
double js8::aided::metricGainDb (double refined, double baseline)
template<std::size_t NBlades>
double js8::aided::llrNorm (std::array< float, NBlades > const &llr)

Variables

constexpr int js8::aided::kCodeBits = 174
constexpr int js8::aided::kDataSymbols = 58
constexpr int js8::aided::kTotalSymbols = 79
constexpr int js8::aided::kTones = 8
constexpr int js8::aided::kMaxSyndrome = 4
constexpr int js8::aided::kTimingDeltaMin = -2
constexpr int js8::aided::kTimingDeltaMax = 2
constexpr double js8::aided::kFreqStartHz = -0.5
constexpr double js8::aided::kFreqStepHz = 0.1
constexpr int js8::aided::kFreqSteps = 11
constexpr double js8::aided::kDriftValues [] = {-0.02, 0.0, 0.02}
constexpr int js8::aided::kDriftSteps
constexpr double js8::aided::kMinMetricGain = 1.005
constexpr double js8::aided::kConfidenceFloor = 0.5
constexpr double js8::aided::kConfidenceScale = 3.0

Detailed Description

Decoder-aided re-demodulation helpers for JS8 near-miss rescue.

When normal decoding fails but LDPC gets CLOSE (small syndrome), the best tentative 174-bit codeword is used as a waveform hypothesis: its 58 data tones plus the 21 known Costas tones refine timing/residual-frequency/drift against the candidate's actual received samples. The refined sync then drives ONE fresh 8-tone re-demodulation producing new LLRs for a final LDPC attempt. CRC remains the only acceptance gate.

This header holds the pure, deterministic algorithmic core (no Qt, no FFTW, no decoder state) so it can be unit-tested standalone:

  • tentative codeword -> 79 expected tones (exact decoder bit/tone mapping)
  • per-data-symbol confidence weights from LLR magnitudes
  • bounded local sync refinement with a tone-CONTRAST metric
  • baseline comparison / safety gate

Bit/tone mapping authority (derived from the decoder, not memory):

  • Decoder LLR formation (whitening_processor.h): data symbol j emits llr[3j] (tone bit 2, value 4), llr[3j+1] (tone bit 1, value 2), llr[3j+2] (tone bit 0, value 1); llr > 0 means bit 1.
  • bpdecode174 (JS8.cpp): hard slice cw[i] = zn[i] > 0 ? 1 : 0, positions preserved, so tone(j) = 4*cw[3j] + 2*cw[3j+1] + cw[3j+2].
  • Encoder (JS8::encode, JS8.cpp): parity words -> tones+7 (data symbols j=0..28, globals 7..35), message words -> tones+43 (j=29..57, globals 43..71); MSB-first accumulation matches the tone formula above.
  • Symbol layout (JS8.cpp demod loop): Costas globals 0-6, 36-42, 72-78; data globals 7-35 (j=0..28) and 43-71 (j=29..57).

Typedef Documentation

◆ CostasTones

using js8::aided::CostasTones = std::array<std::array<int, 7>, 3>

3x7 Costas tone layout, matching JS8::Costas::Array.

Function Documentation

◆ aidedFrameXdt()

float js8::aided::aidedFrameXdt ( float xdt2,
int aidedDt,
float dtSecondsPerSample )
inline

Scalar frame timing seed from an aided timing delta.

The aided search is relative to the tracked first-pass extraction whose scalar seed is xdt2 = ibest*DT2, so a global refinement of aidedDt downsampled samples moves the seed by aidedDt*dtSecondsPerSample (DT2). Per-symbol TimingTracker shifts are NOT folded in again: they already existed in the tracked solution and aidedDt is the new residual only. Positive aidedDt (later extraction) increases xdt, matching a late signal.

◆ aidedPhysicalResidualAtMidpoint()

MidpointResidual js8::aided::aidedPhysicalResidualAtMidpoint ( double aidedDf,
double aidedDd,
std::array< SymbolBaseline, kTotalSymbols > const & baselines,
int window,
double sampleRateHz,
std::array< float, kTotalSymbols > const & weights )
inline

Physical carrier residual at the frame midpoint.

Sign derivation from the decoder (do not change without re-deriving):

  • coarse correction multiplies cd0 by exp(-j*2*pi*delfbest*t), then f1 += delfbest, so f1 is the physical center for zero cd0 residual;
  • FrequencyTracker::apply() (and replayTrackerCorrection()) multiplies by exp(+j*2*pi*trackerHz*t_local), i.e. it ADDS trackerHz to the apparent residual, so a perfectly correcting tracker records trackerHz ~= -physicalResidualHz;
  • the aided refinement derotates by exp(-j*(2*pi*aidedDf*t+pi*aidedDd*t^2)) AFTER replaying the tracker correction, and the search centers the expected-tone peak, so at the optimum physicalResidual(t) ~= aidedDf + aidedDd*t - trackerHz(t).

The scalar seed is f1 + residual(midpoint). Per-symbol residuals r_k = aidedDf + aidedDd*t_k - trackerHz[k] (t_k = window-center absolute time) are combined with a weighted linear fit evaluated at the frame midpoint (weighted mean fallback); drift therefore enters through aidedDd*t_mid and is never discarded. Weights are caller-provided (Costas preferred for SIC seeding). Finite-input guarded, deterministic, no Qt.

◆ buildCostasWeights()

void js8::aided::buildCostasWeights ( std::array< float, kTotalSymbols > & weights)
inline

Expand confidences to Costas-only weights (1.0 on pilots, else 0).

Used for the final physical-frequency seed so low-confidence tentative data can never steer SIC subtraction; the search itself keeps the full confidence weights.

◆ buildSymbolWeights()

void js8::aided::buildSymbolWeights ( ConfidenceSummary const & conf,
std::array< float, kTotalSymbols > & weights )
inline

Expand 58 data confidences to 79 per-symbol weights.

Known Costas symbols get weight 1.0; data symbols get their confidence.

◆ codewordToTones()

void js8::aided::codewordToTones ( std::array< int8_t, kCodeBits > const & cw,
CostasTones const & costas,
std::array< int, kTotalSymbols > & tones )
inline

Convert a tentative 174-bit codeword into 79 expected tones.

Costas positions come from the exact known array; data tones use the exact decoder mapping tone(j) = 4*b0 + 2*b1 + b2 with bits cw[3j..3j+2] (non-zero int8 means bit 1, matching the bpdecode174 hard slice).

◆ contrastEight()

double js8::aided::contrastEight ( double expectedPower,
double const * otherPowers )
inline

Tone-CONTRAST metric from the actual 8 JS8 FSK bins.

contrast = P[expected] - mean(P[other 7 valid tones]). Broadband energy raises all eight bins together and scores ~0, so the metric answers "is the tentative waveform present?" rather than "is there more RF energy?". Unused FFT bins outside the 8 valid tones never enter the estimate. Returns NaN on invalid input.

◆ dataSymbolIndex()

int js8::aided::dataSymbolIndex ( int j)
constexpr

Global channel-symbol index for data symbol j (j=0..57).

◆ isCostasSymbol()

bool js8::aided::isCostasSymbol ( int k)
constexpr

Whether global symbol k is a known Costas pilot.

Layout mirrors the decoder demod loop: pilots at globals 0-6, 36-42, 72-78; data at 7-35 and 43-71.

◆ llrNorm()

template<std::size_t NBlades>
double js8::aided::llrNorm ( std::array< float, NBlades > const & llr)
inline

L2 norm of an LLR vector, skipping non-finite entries (telemetry).

◆ metricGainDb()

double js8::aided::metricGainDb ( double refined,
double baseline )
inline

Metric gain in dB for telemetry (0 when baseline is not positive).

◆ redemodEnabled()

bool js8::aided::redemodEnabled ( )
inline

Kill switch for decoder-aided re-demodulation.

When the JS8_DISABLE_REDEMOD environment variable is present (any value), the aided pass is completely disabled and decoder behavior matches the implementation without this feature.

◆ refineSync()

Refinement js8::aided::refineSync ( std::complex< float > const * samples,
int numSamples,
std::array< SymbolBaseline, kTotalSymbols > const & baselines,
int window,
double sampleRateHz,
std::array< int, kTotalSymbols > const & tones,
std::array< float, kTotalSymbols > const & weights,
std::function< bool()> const & shouldCancel = {} )
inline

Bounded local sync refinement around the first-pass solution.

The baseline (delta 0,0,0) replays the ACTUAL first-pass per-symbol extraction: recorded window starts plus the recorded FrequencyTracker correction for each symbol. That correction depends on timing, not on the residual frequency/drift hypothesis, so each used (timing, symbol) window is replayed once and reused throughout the grid. Search hypotheses are refinements RELATIVE to that baseline (trial start = recorded start + deltaSamples, recorded tracker rotation followed by the candidate freq/drift derotation), so the gate can never claim a fake gain by rediscovering a correction the first pass already applied.

Each hypothesis scores every useful symbol with the tone contrast of the actual 8 JS8 FSK bins: the window is derotated once, all 8 bins are computed together with a tiny direct DFT (no FFTW plan per hypothesis), and contrast = P[expected] - mean(P[other 7]). Unused FFT bins never enter the estimate. Ties keep the earliest (baseline wins all ties: grid entries must STRICTLY beat it). Any invalid input yields searched=false rather than partial garbage.

◆ replayTrackerCorrection()

bool js8::aided::replayTrackerCorrection ( std::complex< float > * window,
int count,
double trackerHz,
double sampleRateHz )
inline

Replay one symbol's recorded FrequencyTracker correction.

This mirrors FrequencyTracker::apply() operation-for-operation (positive rotation wstep^(n+1) with wstep = exp(j*2*pi*trackerHz/sampleRateHz), fresh phase every window, float arithmetic) so the aided baseline reproduces the first-pass per-symbol extraction bit-faithfully for finite inputs. The added finiteness guard only rejects corrupt input the decoder would discard downstream anyway.

Returns
False on any invalid/non-finite input (caller must skip the symbol); true with window rotated in place otherwise.

◆ symbolBoundsValid()

bool js8::aided::symbolBoundsValid ( std::array< SymbolBaseline, kTotalSymbols > const & baselines,
int window,
int numSamples,
int maxAbsDelta )
inline

Validate candidate sample bounds for the aided search/extraction.

Every baseline start plus/minus the maximum hypothesis delta must lie in [0, numSamples - window] WITHOUT clamping, so no hypothesis reads out of bounds and no symbol is degenerately clamped onto its neighbor.

◆ tentativeConfidences()

ConfidenceSummary js8::aided::tentativeConfidences ( std::array< float, kCodeBits > const & llr)
inline

Confidence weight per tentative data symbol from its 3 bit LLRs.

weight = clamp((minAbs - floor) / (scale - floor), 0, 1), i.e. zero below kConfidenceFloor, ramping to 1.0 at min|LLR| = kConfidenceScale. Non-finite LLRs force zero weight so NaN/Inf can never steer the fit. One huge LLR cannot dominate: each symbol contributes at most 1.0.

Variable Documentation

◆ kCodeBits

int js8::aided::kCodeBits = 174
inlineconstexpr

Coded bits per frame (matches decoder N).

◆ kConfidenceFloor

double js8::aided::kConfidenceFloor = 0.5
inlineconstexpr

Symbols whose weakest bit |LLR| is below this get zero weight.

◆ kConfidenceScale

double js8::aided::kConfidenceScale = 3.0
inlineconstexpr

min|LLR| is scaled by this to reach full weight 1.0 (clamped).

◆ kDataSymbols

int js8::aided::kDataSymbols = 58
inlineconstexpr

Data symbols per frame (matches decoder ND).

◆ kDriftSteps

int js8::aided::kDriftSteps
inlineconstexpr
Initial value:
=
static_cast<int>(sizeof(kDriftValues) / sizeof(kDriftValues[0]))
constexpr double kDriftValues[]
Definition decoder_aided_redemod.h:70

◆ kDriftValues

double js8::aided::kDriftValues[] = {-0.02, 0.0, 0.02}
inlineconstexpr

Linear-drift search values (Hz/s).

◆ kFreqStartHz

double js8::aided::kFreqStartHz = -0.5
inlineconstexpr

Residual-frequency search: start/step/count covering about +/-0.5 Hz.

◆ kMaxSyndrome

int js8::aided::kMaxSyndrome = 4
inlineconstexpr

Near-miss trigger: best syndrome must be in (0, kMaxSyndrome].

◆ kMinMetricGain

double js8::aided::kMinMetricGain = 1.005
inlineconstexpr

Minimum refined-vs-baseline metric gain required to re-demodulate (0.5%: small but real; rejects floating-point dust).

◆ kTimingDeltaMin

int js8::aided::kTimingDeltaMin = -2
inlineconstexpr

Timing search offsets (downsampled samples) around the first-pass start.

◆ kTones

int js8::aided::kTones = 8
inlineconstexpr

FSK tones (matches decoder NROWS).

◆ kTotalSymbols

int js8::aided::kTotalSymbols = 79
inlineconstexpr

Total channel symbols per frame (matches decoder NN).