JS8Call-Improved master
Loading...
Searching...
No Matches
JS8.cpp
Go to the documentation of this file.
1
7
8#include "JS8.h"
11#include "JS8_Mode/bp_math.h"
15#include "ldpc_feedback.h"
16#include "optional_work.h"
17#include "soft_combiner.h"
18
19#include <QDebug>
20#include <QLoggingCategory>
21#include <QtGlobal>
22
23#include <algorithm>
24#include <atomic>
25#include <boost/crc.hpp>
26#include <boost/math/ccmath/round.hpp>
27#include <boost/multi_index/key.hpp>
28#include <boost/multi_index/ordered_index.hpp>
29#include <boost/multi_index/ranked_index.hpp>
30#include <boost/multi_index_container.hpp>
31#include <chrono>
32#include <cmath>
33#include <complex>
34#include <concepts>
35#include <cstddef>
36#include <cstdint>
37#include <cstring>
38#include <cstdlib>
39#include <fftw3.h>
40#include <initializer_list>
41#include <limits>
42#include <memory>
43#include <mutex>
44#include <numbers>
45#include <numeric>
46#include <optional>
47#include <sstream>
48#include <stdexcept>
49#include <string_view>
50#include <unordered_map>
51#include <utility>
52#include <vector>
53#include <vendor/Eigen/Dense>
54
55Q_DECLARE_LOGGING_CATEGORY(decoder_js8);
56
57// A C++ conversion of the Fortran JS8 encoding and decoder function.
58// Some notes on the conversion:
59//
60// 1. Names of variables and functions as much as possible match those
61// of the Fortran routines, for ease in cross-referencing during the
62// debug comparison phase of testing. You don't have to like them; I
63// don't like them either, frankly, but it's the reasonable approach
64// to the problem as of this writing; we can make 'em pretty later.
65//
66// 2. The BP decoder should be a faithful reproduction of the Fortran
67// version, albeit modified for the column-major vs. row-major
68// differences between the two languages.
69//
70// 3. The OSD decoder is no longer used, and the depth is now fixed at
71// 2, instead of being variable 1 to 4.
72//
73// 4. The Fortran version didn't compute the 40% rank consistently in
74// syncjs8(); this version does. It wasn't typically off by much, but
75// it was reliably not going to be at 40%. Hopefully, this change will
76// result in more predictable first-pass candidate selection.
77//
78// 5. The Fortran version was very subject to Runge's phenomenon when
79// computing the baseline in baselinejs8(), and was using a ton of
80// data points below the 10% threshold for the polynomial determination.
81// Neither of these seemed to be helpful, so in contrast we're using
82// a number of Chebyshev nodes proportional to the desired polynomial
83// terms.
84//
85// 6. The Fortran version normalized `s1` by dividing by the median in
86// js8dec(), but did so in a naive manner, not checking for a median
87// of zero. Testing indicates that the normalization does not appear
88// to contribute to decoder yield, so it's been removed.
89//
90// 7. Translating array indices from the world of Fortran to that of C++
91// is no one's fun task. If you see things that aren't behaving as
92// expected, look at the Fortran code and compare the array indexing;
93// would not be surprised in the least to have off-by-one errors here.
94
95/******************************************************************************/
96// Compilation Utilities
97/******************************************************************************/
98
99namespace {
100// Full-range cosine function using symmetries of cos(x). std::cos
101// isn't constexpr until C++20, and we're targeting C++17 at the
102// moment. We only use this function during compilation; std::cos
103// is the better choice at runtime. Once we move to requiring a
104// C++20 compiler, we can just use std::cos.
105
106constexpr double cos_approx(double x) {
107 constexpr auto RAD_360 = std::numbers::pi * 2;
108 constexpr auto RAD_180 = std::numbers::pi;
109 constexpr auto RAD_90 = std::numbers::pi / 2;
110
111 // Polynomial approximation of cos(x) for x in [0, RAD_90],
112 // Accuracy here in theory is 1e-18, but double precision
113 // itself is only 1-e16, so within the domain of doubles,
114 // this should be extremely accurate.
115
116 constexpr auto poly = [](double const x) {
117 constexpr std::array coefficients = {
118 1.0, // Coefficient for x^0
119 -0.49999999999999994, // Coefficient for x^2
120 0.041666666666666664, // Coefficient for x^4
121 -0.001388888888888889, // Coefficient for x^6
122 0.000024801587301587, // Coefficient for x^8
123 -0.00000027557319223986, // Coefficient for x^10
124 0.00000000208767569878681, // Coefficient for x^12
125 -0.00000000001147074513875176, // Coefficient for x^14
126 0.0000000000000477947733238733 // Coefficient for x^16
127 };
128
129 auto const x2 = x * x;
130 auto const x4 = x2 * x2;
131 auto const x6 = x4 * x2;
132 auto const x8 = x4 * x4;
133 auto const x10 = x8 * x2;
134 auto const x12 = x8 * x4;
135 auto const x14 = x12 * x2;
136 auto const x16 = x8 * x8;
137
138 return coefficients[0] + coefficients[1] * x2 + coefficients[2] * x4 +
139 coefficients[3] * x6 + coefficients[4] * x8 +
140 coefficients[5] * x10 + coefficients[6] * x12 +
141 coefficients[7] * x14 + coefficients[8] * x16;
142 };
143
144 // Reduce x to [0, RAD_360)
145
146 x -= static_cast<long long>(x / RAD_360) * RAD_360;
147
148 // Map x to [0, RAD_180]
149
150 if (x > RAD_180)
151 x = RAD_360 - x;
152
153 // Map x to [0, RAD_90] and evaluate the polynomial;
154 // flip the sign for angles in the second quadrant.
155
156 return x > RAD_90 ? -poly(RAD_180 - x) : poly(x);
157};
158} // end anonymous namespace
159
160/******************************************************************************/
161// Constants
162/******************************************************************************/
163
164namespace {
165/* COMMON PARAMETERS */
166
167// !Common
168//
169// parameter (KK=87) !Information bits (75 + CRC12)
170// parameter (ND=58) !Data symbols
171// parameter (NS=21) !Sync symbols (3 @ Costas 7x7)
172// parameter (NN=NS+ND) !Total channel symbols (79)
173// parameter (ASYNCMIN=1.5) !Minimum Sync
174// parameter (NFSRCH=5) !Search frequency range in Hz (i.e.,
175// +/- 2.5 Hz) parameter (NMAXCAND=300) !Maximum number of
176// candidate signals
177
178// Parameter Value Description
179// KK 87 Number of information bits (75 message bits + 12 CRC bits).
180// ND 58 Number of data symbols in the JS8 transmission.
181// NS 21 Number of synchronization symbols (3 Costas arrays of size 7).
182// NN 79 Total number of channel symbols (NN = NS + ND).
183// ASYNCMIN 1.5 Minimum sync value for successful decoding.
184// NFSRCH 5 Search frequency range in Hz (±2.5 Hz).
185// NMAXCAND 300 Maximum number of candidate signals.
186
187constexpr int N = 174; // Total bits
188constexpr int K = 87; // Message bits
189constexpr int M = N - K; // Check bits
190constexpr int KK = 87; // Information bits (75 + CRC12)
191constexpr int ND = 58; // Data symbols
192constexpr int NS = 21; // Sync symbols (3 @ Costas 7x7)
193constexpr int NN = NS + ND; // Total channel symbols (79)
194constexpr float ASYNCMIN = 1.5f; // Normal coarse-sync threshold
195constexpr float ASYNCDEEP = 1.20f; // Bounded fallback coarse-sync threshold
196constexpr float SOFT_COSTAS_MIN = 1.5f; // Minimum soft Costas power ratio
197constexpr int NFSRCH = 5; // Search frequency range in Hz (i.e., +/- 2.5 Hz)
198constexpr std::size_t NMAXCAND = 300; // Maximum normal candidates
199constexpr std::size_t NMAXDEEP = 24; // Maximum deep-search candidates
200constexpr int NFILT = 1400; // Filter length
201constexpr int NROWS = 8;
202constexpr int NFOS = 2;
203constexpr int NSSY = 4;
204constexpr int NP = 3200;
205constexpr int NP2 = 2812;
206constexpr float TAU = 2.0f * std::numbers::pi_v<float>;
207constexpr auto ZERO = std::complex<float>{0.0f, 0.0f};
208// Key for the constants that follow:
209// Key for the constants that follow:
210//
211// NSUBMODE - ID of the submode
212// NCOSTAS - Which JS8 Costas Arrays to use
213// NSPS - Number of samples per second
214// NTXDUR - Duration of the transmission in seconds.
215// NDOWNSPS - Number of samples per symbol after downsampling.
216// NDD - Parameter used in waveform tapering and related calculations.
217// XXX JZ - Range of symbol offsets considered during decoding. ASTART
218// - Start delay in seconds for decoding. BASESUB - XXX NMAX - Samples in
219// input wave NSTEP - Rough time-sync step size NHSYM - Number of symbol
220// spectra (1/4-sym steps) NDOW - Downsample factor to 32 samples per
221// symbol NQSYMBOL - Downsample factor of a quarter symbol
222
223/* A MODE DECODER */
224
225struct ModeA {
226 // Static constants
227 inline static constexpr int NSUBMODE = 0;
228 inline static constexpr auto NCOSTAS = JS8::Costas::Type::ORIGINAL;
229 inline static constexpr int NSPS = JS8A_SYMBOL_SAMPLES;
230 inline static constexpr int NTXDUR = JS8A_TX_SECONDS;
231 inline static constexpr int NDOWNSPS = 32;
232 inline static constexpr int NDD = 100;
233 inline static constexpr int JZ = 62;
234 inline static constexpr float ASTART = 0.5f;
235 inline static constexpr float BASESUB = 40.0f;
236
237 // Derived parameters
238 inline static constexpr float AZ = (12000.0f / NSPS) * 0.64f;
239 inline static constexpr int NMAX = NTXDUR * JS8_RX_SAMPLE_RATE;
240 inline static constexpr int NFFT1 = NSPS * NFOS;
241 inline static constexpr int NSTEP = NSPS / NSSY;
242 inline static constexpr int NHSYM = NMAX / NSTEP - 3;
243 inline static constexpr int NDOWN = NSPS / NDOWNSPS;
244 inline static constexpr int NQSYMBOL = NDOWNSPS / 4;
245 inline static constexpr int NDFFT1 = NSPS * NDD;
246 inline static constexpr int NDFFT2 = NDFFT1 / NDOWN;
247 inline static constexpr int NP2 = NN * NDOWNSPS;
248 inline static constexpr float TSTEP = NSTEP / 12000.0f;
249 inline static constexpr int JSTRT = ASTART / TSTEP;
250 inline static constexpr float DF = 12000.0f / NFFT1;
251};
252
253/* B MODE DECODER */
254
255struct ModeB {
256 // Static constants
257 inline static constexpr int NSUBMODE = 1;
258 inline static constexpr auto NCOSTAS = JS8::Costas::Type::MODIFIED;
259 inline static constexpr int NSPS = JS8B_SYMBOL_SAMPLES;
260 inline static constexpr int NTXDUR = JS8B_TX_SECONDS;
261 inline static constexpr int NDOWNSPS = 20;
262 inline static constexpr int NDD = 100;
263 inline static constexpr int JZ = 144;
264 inline static constexpr float ASTART = 0.2f;
265 inline static constexpr float BASESUB = 39.0f;
266
267 // Derived parameters
268 inline static constexpr float AZ = (12000.0f / NSPS) * 0.8f;
269 inline static constexpr int NMAX = NTXDUR * JS8_RX_SAMPLE_RATE;
270 inline static constexpr int NFFT1 = NSPS * NFOS;
271 inline static constexpr int NSTEP = NSPS / NSSY;
272 inline static constexpr int NHSYM = NMAX / NSTEP - 3;
273 inline static constexpr int NDOWN = NSPS / NDOWNSPS;
274 inline static constexpr int NQSYMBOL = NDOWNSPS / 4;
275 inline static constexpr int NDFFT1 = NSPS * NDD;
276 inline static constexpr int NDFFT2 = NDFFT1 / NDOWN;
277 inline static constexpr int NP2 = NN * NDOWNSPS;
278 inline static constexpr float TSTEP = NSTEP / 12000.0f;
279 inline static constexpr int JSTRT = ASTART / TSTEP;
280 inline static constexpr float DF = 12000.0f / NFFT1;
281};
282
283/* C MODE DECODER */
284
285struct ModeC {
286 // Static constants
287 inline static constexpr int NSUBMODE = 2;
288 inline static constexpr auto NCOSTAS = JS8::Costas::Type::MODIFIED;
289 inline static constexpr int NSPS = JS8C_SYMBOL_SAMPLES;
290 inline static constexpr int NTXDUR = JS8C_TX_SECONDS;
291 inline static constexpr int NDOWNSPS = 12;
292 inline static constexpr int NDD = 120;
293 inline static constexpr int JZ = 172;
294 inline static constexpr float ASTART = 0.1f;
295 inline static constexpr float BASESUB = 38.0f;
296
297 // Derived parameters
298 inline static constexpr float AZ = (12000.0f / NSPS) * 0.6f;
299 inline static constexpr int NMAX = NTXDUR * JS8_RX_SAMPLE_RATE;
300 inline static constexpr int NFFT1 = NSPS * NFOS;
301 inline static constexpr int NSTEP = NSPS / NSSY;
302 inline static constexpr int NHSYM = NMAX / NSTEP - 3;
303 inline static constexpr int NDOWN = NSPS / NDOWNSPS;
304 inline static constexpr int NQSYMBOL = NDOWNSPS / 4;
305 inline static constexpr int NDFFT1 = NSPS * NDD;
306 inline static constexpr int NDFFT2 = NDFFT1 / NDOWN;
307 inline static constexpr int NP2 = NN * NDOWNSPS;
308 inline static constexpr float TSTEP = NSTEP / 12000.0f;
309 inline static constexpr int JSTRT = ASTART / TSTEP;
310 inline static constexpr float DF = 12000.0f / NFFT1;
311};
312
313/* E MODE DECODER */
314
315// Note that the original used 28 for NTXDUR and 90 for NDD, but the
316// corresponding C++ mainline side used 30 for NTXDUR, so for the
317// moment, we're matching that here, which seems logical at present.
318
319struct ModeE {
320 // Static constants
321 inline static constexpr int NSUBMODE = 4;
322 inline static constexpr auto NCOSTAS = JS8::Costas::Type::MODIFIED;
323 inline static constexpr int NSPS = JS8E_SYMBOL_SAMPLES;
324 inline static constexpr int NTXDUR =
325 JS8E_TX_SECONDS; // XXX was 28 in Fortran
326 inline static constexpr int NDOWNSPS = 32;
327 inline static constexpr int NDD = 94; // XXX was 90 in Fortran
328 inline static constexpr int JZ = 32;
329 inline static constexpr float ASTART = 0.5f;
330 inline static constexpr float BASESUB = 42.0f;
331
332 // Derived parameters
333 inline static constexpr float AZ = (12000.0f / NSPS) * 0.64f;
334 inline static constexpr int NMAX = NTXDUR * JS8_RX_SAMPLE_RATE;
335 inline static constexpr int NFFT1 = NSPS * NFOS;
336 inline static constexpr int NSTEP = NSPS / NSSY;
337 inline static constexpr int NHSYM = NMAX / NSTEP - 3;
338 inline static constexpr int NDOWN = NSPS / NDOWNSPS;
339 inline static constexpr int NQSYMBOL = NDOWNSPS / 4;
340 inline static constexpr int NDFFT1 = NSPS * NDD;
341 inline static constexpr int NDFFT2 = NDFFT1 / NDOWN;
342 inline static constexpr int NP2 = NN * NDOWNSPS;
343 inline static constexpr float TSTEP = NSTEP / 12000.0f;
344 inline static constexpr int JSTRT = ASTART / TSTEP;
345 inline static constexpr float DF = 12000.0f / NFFT1;
346};
347
348/* I MODE DECODER */
349
350struct ModeI {
351 // Static constants
352 inline static constexpr int NSUBMODE = 8;
353 inline static constexpr auto NCOSTAS = JS8::Costas::Type::MODIFIED;
354 inline static constexpr int NSPS = JS8I_SYMBOL_SAMPLES;
355 inline static constexpr int NTXDUR = JS8I_TX_SECONDS;
356 inline static constexpr int NDOWNSPS = 12;
357 inline static constexpr int NDD = 125;
358 inline static constexpr int JZ = 250;
359 inline static constexpr float ASTART = 0.1f;
360 inline static constexpr float BASESUB = 36.0f;
361
362 // Derived parameters
363 inline static constexpr float AZ = (12000.0f / NSPS) * 0.64f;
364 inline static constexpr int NMAX = NTXDUR * JS8_RX_SAMPLE_RATE;
365 inline static constexpr int NFFT1 = NSPS * NFOS;
366 inline static constexpr int NSTEP = NSPS / NSSY;
367 inline static constexpr int NHSYM = NMAX / NSTEP - 3;
368 inline static constexpr int NDOWN = NSPS / NDOWNSPS;
369 inline static constexpr int NQSYMBOL = NDOWNSPS / 4;
370 inline static constexpr int NDFFT1 = NSPS * NDD;
371 inline static constexpr int NDFFT2 = NDFFT1 / NDOWN;
372 inline static constexpr int NP2 = NN * NDOWNSPS;
373 inline static constexpr float TSTEP = NSTEP / 12000.0f;
374 inline static constexpr int JSTRT = ASTART / TSTEP;
375 inline static constexpr float DF = 12000.0f / NFFT1;
376};
377
378// Tunable settings; degree of the polynomial used for the baseline
379// curve fit, and the percentile of the span at which to sample. In
380// general, a 5th degree polynomial and the 10th percentile should
381// be optimal.
382
383constexpr auto BASELINE_DEGREE = 5;
384constexpr auto BASELINE_SAMPLE = 10;
385
386// Define the closed range in Hz that we'll consider to be the window
387// for baseline determination.
388
389constexpr auto BASELINE_MIN = 500;
390constexpr auto BASELINE_MAX = 2500;
391
392// We're going to do a pairwise Estrin's evaluation of the polynomial
393// coefficients, so it's critical that the degree of the polynomial is
394// odd, resulting in an even number of coefficients.
395
396static_assert(BASELINE_DEGREE & 1, "Degree must be odd");
397static_assert(BASELINE_SAMPLE >= 0 && BASELINE_SAMPLE <= 100,
398 "Sample must be a percentage");
399
400// Since we know the degree of the polynomial, and thus the number of
401// nodes that we're going to use, we can do all the trigonometry work
402// required to calculate the Chebyshev nodes in advance, by computing
403// them over the range [0, 1]; we can then scale these at runtime to
404// a span of any size by simple multiplication.
405//
406// Downside to this with C++17 is that std::cos() is not yet constexpr,
407// as it is in C++20, so we must provide our own implementation until
408// then.
409
410constexpr auto BASELINE_NODES = []() {
411 // Down to the actual business of generating Chebyshev nodes
412 // suitable for scaling; once we move to C++20 as the minimum
413 // compiler, we can remove the cos() function above and instead
414 // call std::cos() here, as it's required to be constexpr in
415 // C++20 and above, and presumably it'll be of high quality.
416
417 auto nodes = std::array<double, BASELINE_DEGREE + 1>{};
418 constexpr auto slice = std::numbers::pi / (2.0 * nodes.size());
419
420 for (std::size_t i = 0; i < nodes.size(); ++i) {
421 nodes[i] = 0.5 * (1.0 - cos_approx(slice * (2.0 * i + 1)));
422 }
423
424 return nodes;
425}();
426} // end anonymous namespace
427
428/******************************************************************************/
429// Local Types
430/******************************************************************************/
431
432namespace {
433// Accumulation of rounding errors in IEEE 754 values can be a problem
434// when summing large numbers of small values; a Kahan summation class
435// by which to compensate for them.
436//
437// Fortran, or at least, gfortran, will use this technique under the
438// covers in various scenarios. While it'd be reasonable to expect it
439// to be used in sum(), that's typically not the case.
440//
441// However, for example, it'll use it here for the value that goes into
442// win(i), and naive summation in C++ will as a result not produce the
443// same values without using compensation.
444//
445// subroutine nuttal_window(win,n)
446// real win(n)
447// pi=4.0*atan(1.0)
448// a0=0.3635819
449// a1=-0.4891775;
450// a2=0.1365995;
451// a3=-0.0106411;
452// do i=1,n
453// win(i)=a0+a1*cos(2*pi*(i-1)/(n))+ &
454// a2*cos(4*pi*(i-1)/(n))+ &
455// a3*cos(6*pi*(i-1)/(n))
456// enddo
457// return
458// end subroutine nuttal_window
459
460template <std::floating_point T> class KahanSum {
461 T m_sum; // Accumulated sum
462 T m_compensation; // Compensation for lost low-order bits
463
464 public:
465 KahanSum(T sum = T(0)) : m_sum(sum), m_compensation(T(0)) {}
466
467 KahanSum &operator=(T const sum) {
468 m_sum = sum;
469 m_compensation = T(0);
470
471 return *this;
472 }
473
474 KahanSum &operator+=(T const value) {
475 T const y = value - m_compensation; // Correct the value
476 T const t = m_sum + y; // Perform the sum
477
478 m_compensation = (t - m_sum) - y; // Update compensation
479 m_sum = t; // Update the sum
480
481 return *this;
482 }
483
484 operator T() const { return m_sum; }
485};
486
487// Management of dynamic FFTW plan storage.
488
489class FFTWPlanManager {
490 public:
491 enum class Type { DS, BB, CF, CB, SD, CS, count };
492
493 // Disallow copying and moving
494
495 FFTWPlanManager(FFTWPlanManager const &) = delete;
496 FFTWPlanManager &operator=(FFTWPlanManager const &) = delete;
497 FFTWPlanManager(FFTWPlanManager &&) = delete;
498 FFTWPlanManager &operator=(FFTWPlanManager &&) = delete;
499
500 // Constructor
501
502 FFTWPlanManager() { m_plans.fill(nullptr); }
503
504 // Destructor
505
506 ~FFTWPlanManager() {
507 std::lock_guard<std::mutex> lock(fftw_mutex);
508
509 for (auto &plan : m_plans) {
510 if (plan)
511 fftwf_destroy_plan(plan);
512 }
513 }
514
515 // Accessor
516
517 fftwf_plan const &operator[](Type const type) const noexcept {
518 return m_plans[static_cast<std::size_t>(type)];
519 }
520
521 // Manipulator
522
523 fftwf_plan &operator[](Type const type) noexcept {
524 return m_plans[static_cast<std::size_t>(type)];
525 }
526
527 // Iteration support
528
529 auto begin() noexcept { return m_plans.begin(); }
530 auto end() noexcept { return m_plans.end(); }
531 auto begin() const noexcept { return m_plans.begin(); }
532 auto end() const noexcept { return m_plans.end(); }
533
534 private:
535 // Data members
536
537 std::array<fftwf_plan, static_cast<std::size_t>(Type::count)> m_plans;
538};
539
540// Encapsulates the first-order search results provided by syncjs8().
541
542struct Sync {
543 float freq;
544 float step;
545 float sync;
546
547 // Constructor for convenience.
548
549 Sync(float const freq, float const step, float const sync)
550 : freq(freq), step(step), sync(sync) {}
551};
552
553struct SyncCandidates {
554 std::vector<Sync> normal;
555 std::vector<Sync> deep;
556
557 bool empty() const noexcept { return normal.empty() && deep.empty(); }
558};
559
560// Tag structs so that we can refer to multi index container indices
561// by a descriptive tag instead of by the index of the index. These
562// don't need to be anything but a name.
563
564namespace Tag {
565struct Freq {};
566struct Rank {};
567struct Sync {};
568} // namespace Tag
569
570// Container indexing Sync objects in useful ways, used by syncjs8().
571
572namespace MI = boost::multi_index;
573using SyncIndex = MI::multi_index_container<
574 Sync, MI::indexed_by<
575 MI::ordered_non_unique<MI::tag<Tag::Freq>, MI::key<&Sync::freq>>,
576 MI::ranked_non_unique<MI::tag<Tag::Rank>, MI::key<&Sync::sync>>,
577 MI::ordered_non_unique<MI::tag<Tag::Sync>, MI::key<&Sync::sync>,
578 std::greater<>>>>;
579
580// Represents a decoded message, i.e., the 3-bit message type
581// and the 12 bytes that result from decoding a message.
582
583class Decode {
584 public:
585 int type;
586 std::string data;
587
588 Decode(int type, std::string data) : type(type), data(std::move(data)) {}
589
590 bool operator==(Decode const &) const noexcept = default;
591
592 struct Hash {
593 std::size_t operator()(Decode const &decode) const noexcept {
594 std::size_t const h1 = std::hash<int>{}(decode.type);
595 std::size_t const h2 = std::hash<std::string>{}(decode.data);
596 return h1 ^ (h2 + 0x9e3779b9 + (h1 << 6) + (h1 >> 2));
597 }
598 };
599
600 using Map = std::unordered_map<Decode, int, Hash>;
601};
602
603/******************************************************************************/
604// Belief Propagation Decoder
605/******************************************************************************/
606
607namespace {
608constexpr int BP_MAX_ROWS = 7; // Max rows per column in Nm
609constexpr int BP_MAX_CHECKS = 3; // Max checks per bit in Mn
610constexpr int BP_MAX_ITERATIONS = 30; // Max iterations in normal BP decoder
611constexpr int BP_RESCUE_ITERATIONS = 80; // Extended iterations for near misses
612constexpr int BP_RESCUE_MAX_CHECKS = 12; // Maximum best syndrome for rescue
613constexpr int BP_RESCUE_BUDGET = 4; // Maximum rescued candidates per decode
614constexpr std::array<float, 3> BP_RESCUE_LLR_SCALES = {1.0f, 0.8f, 1.25f};
615
616struct BPOptions {
617 int maxIterations = BP_MAX_ITERATIONS;
618 bool earlyAbort = true;
619 float llrScale = 1.0f;
620 std::function<bool()> const *shouldCancel = nullptr;
621};
622
623struct BPResult {
624 int hardErrors = -1;
625 int iterations = 0;
626 int finalChecks = M;
627 int bestChecks = M + 1;
628 bool earlyAborted = false;
629 bool cancelled = false;
630 // Minimum-syndrome hard word observed during this call (first minimum
631 // wins ties deterministically). Exposed for decoder-aided
632 // re-demodulation WITHOUT changing the normal `cw` output: on failure
633 // `cw` keeps last-iteration semantics while `bestCw` carries the best
634 // word, so ordinary LDPC feedback never depends on it.
635 std::array<int8_t, N> bestCw{};
636 bool bestCwValid = false;
637};
638
639constexpr std::array<std::array<int, BP_MAX_CHECKS>, N> Mn = {
640 {{0, 24, 68}, {1, 4, 72}, {2, 31, 67}, {3, 50, 60}, {5, 62, 69},
641 {6, 32, 78}, {7, 49, 85}, {8, 36, 42}, {9, 40, 64}, {10, 13, 63},
642 {11, 74, 76}, {12, 22, 80}, {14, 15, 81}, {16, 55, 65}, {17, 52, 59},
643 {18, 30, 51}, {19, 66, 83}, {20, 28, 71}, {21, 23, 43}, {25, 34, 75},
644 {26, 35, 37}, {27, 39, 41}, {29, 53, 54}, {33, 48, 86}, {38, 56, 57},
645 {44, 73, 82}, {45, 61, 79}, {46, 47, 84}, {58, 70, 77}, {0, 49, 52},
646 {1, 46, 83}, {2, 24, 78}, {3, 5, 13}, {4, 6, 79}, {7, 33, 54},
647 {8, 35, 68}, {9, 42, 82}, {10, 22, 73}, {11, 16, 43}, {12, 56, 75},
648 {14, 26, 55}, {15, 27, 28}, {17, 18, 58}, {19, 39, 62}, {20, 34, 51},
649 {21, 53, 63}, {23, 61, 77}, {25, 31, 76}, {29, 71, 84}, {30, 64, 86},
650 {32, 38, 50}, {36, 47, 74}, {37, 69, 70}, {40, 41, 67}, {44, 66, 85},
651 {45, 80, 81}, {48, 65, 72}, {57, 59, 65}, {60, 64, 84}, {0, 13, 20},
652 {1, 12, 58}, {2, 66, 81}, {3, 31, 72}, {4, 35, 53}, {5, 42, 45},
653 {6, 27, 74}, {7, 32, 70}, {8, 48, 75}, {9, 57, 63}, {10, 47, 67},
654 {11, 18, 44}, {14, 49, 60}, {15, 21, 25}, {16, 71, 79}, {17, 39, 54},
655 {19, 34, 50}, {22, 24, 33}, {23, 62, 86}, {26, 38, 73}, {28, 77, 82},
656 {29, 69, 76}, {30, 68, 83}, {21, 36, 85}, {37, 40, 80}, {41, 43, 56},
657 {46, 52, 61}, {51, 55, 78}, {59, 74, 80}, {0, 38, 76}, {1, 15, 40},
658 {2, 30, 53}, {3, 35, 77}, {4, 44, 64}, {5, 56, 84}, {6, 13, 48},
659 {7, 20, 45}, {8, 14, 71}, {9, 19, 61}, {10, 16, 70}, {11, 33, 46},
660 {12, 67, 85}, {17, 22, 42}, {18, 63, 72}, {23, 47, 78}, {24, 69, 82},
661 {25, 79, 86}, {26, 31, 39}, {27, 55, 68}, {28, 62, 65}, {29, 41, 49},
662 {32, 36, 81}, {34, 59, 73}, {37, 54, 83}, {43, 51, 60}, {50, 52, 71},
663 {57, 58, 66}, {46, 55, 75}, {0, 18, 36}, {1, 60, 74}, {2, 7, 65},
664 {3, 59, 83}, {4, 33, 38}, {5, 25, 52}, {6, 31, 56}, {8, 51, 66},
665 {9, 11, 14}, {10, 50, 68}, {12, 13, 64}, {15, 30, 42}, {16, 19, 35},
666 {17, 79, 85}, {20, 47, 58}, {21, 39, 45}, {22, 32, 61}, {23, 29, 73},
667 {24, 41, 63}, {26, 48, 84}, {27, 37, 72}, {28, 43, 80}, {34, 67, 69},
668 {40, 62, 75}, {44, 48, 70}, {49, 57, 86}, {47, 53, 82}, {12, 54, 78},
669 {76, 77, 81}, {0, 1, 23}, {2, 5, 74}, {3, 55, 86}, {4, 43, 52},
670 {6, 49, 82}, {7, 9, 27}, {8, 54, 61}, {10, 28, 66}, {11, 32, 39},
671 {13, 15, 19}, {14, 34, 72}, {16, 30, 38}, {17, 35, 56}, {18, 45, 75},
672 {20, 41, 83}, {21, 33, 58}, {22, 25, 60}, {24, 59, 64}, {26, 63, 79},
673 {29, 36, 65}, {31, 44, 71}, {37, 50, 85}, {40, 76, 78}, {42, 55, 67},
674 {46, 73, 81}, {39, 51, 77}, {53, 60, 70}, {45, 57, 68}}};
675
676struct CheckNode {
677 int valid_neighbors;
678 std::array<int, BP_MAX_ROWS> neighbors;
679};
680
681constexpr std::array<CheckNode, M> Nm = {{{6, {0, 29, 59, 88, 117, 146, 0}},
682 {6, {1, 30, 60, 89, 118, 146, 0}},
683 {6, {2, 31, 61, 90, 119, 147, 0}},
684 {6, {3, 32, 62, 91, 120, 148, 0}},
685 {6, {1, 33, 63, 92, 121, 149, 0}},
686 {6, {4, 32, 64, 93, 122, 147, 0}},
687 {6, {5, 33, 65, 94, 123, 150, 0}},
688 {6, {6, 34, 66, 95, 119, 151, 0}},
689 {6, {7, 35, 67, 96, 124, 152, 0}},
690 {6, {8, 36, 68, 97, 125, 151, 0}},
691 {6, {9, 37, 69, 98, 126, 153, 0}},
692 {6, {10, 38, 70, 99, 125, 154, 0}},
693 {6, {11, 39, 60, 100, 127, 144, 0}},
694 {6, {9, 32, 59, 94, 127, 155, 0}},
695 {6, {12, 40, 71, 96, 125, 156, 0}},
696 {6, {12, 41, 72, 89, 128, 155, 0}},
697 {6, {13, 38, 73, 98, 129, 157, 0}},
698 {6, {14, 42, 74, 101, 130, 158, 0}},
699 {6, {15, 42, 70, 102, 117, 159, 0}},
700 {6, {16, 43, 75, 97, 129, 155, 0}},
701 {6, {17, 44, 59, 95, 131, 160, 0}},
702 {6, {18, 45, 72, 82, 132, 161, 0}},
703 {6, {11, 37, 76, 101, 133, 162, 0}},
704 {6, {18, 46, 77, 103, 134, 146, 0}},
705 {6, {0, 31, 76, 104, 135, 163, 0}},
706 {6, {19, 47, 72, 105, 122, 162, 0}},
707 {6, {20, 40, 78, 106, 136, 164, 0}},
708 {6, {21, 41, 65, 107, 137, 151, 0}},
709 {6, {17, 41, 79, 108, 138, 153, 0}},
710 {6, {22, 48, 80, 109, 134, 165, 0}},
711 {6, {15, 49, 81, 90, 128, 157, 0}},
712 {6, {2, 47, 62, 106, 123, 166, 0}},
713 {6, {5, 50, 66, 110, 133, 154, 0}},
714 {6, {23, 34, 76, 99, 121, 161, 0}},
715 {6, {19, 44, 75, 111, 139, 156, 0}},
716 {6, {20, 35, 63, 91, 129, 158, 0}},
717 {6, {7, 51, 82, 110, 117, 165, 0}},
718 {6, {20, 52, 83, 112, 137, 167, 0}},
719 {6, {24, 50, 78, 88, 121, 157, 0}},
720 {7, {21, 43, 74, 106, 132, 154, 171}},
721 {6, {8, 53, 83, 89, 140, 168, 0}},
722 {6, {21, 53, 84, 109, 135, 160, 0}},
723 {6, {7, 36, 64, 101, 128, 169, 0}},
724 {6, {18, 38, 84, 113, 138, 149, 0}},
725 {6, {25, 54, 70, 92, 141, 166, 0}},
726 {7, {26, 55, 64, 95, 132, 159, 173}},
727 {6, {27, 30, 85, 99, 116, 170, 0}},
728 {6, {27, 51, 69, 103, 131, 143, 0}},
729 {6, {23, 56, 67, 94, 136, 141, 0}},
730 {6, {6, 29, 71, 109, 142, 150, 0}},
731 {6, {3, 50, 75, 114, 126, 167, 0}},
732 {6, {15, 44, 86, 113, 124, 171, 0}},
733 {6, {14, 29, 85, 114, 122, 149, 0}},
734 {6, {22, 45, 63, 90, 143, 172, 0}},
735 {6, {22, 34, 74, 112, 144, 152, 0}},
736 {7, {13, 40, 86, 107, 116, 148, 169}},
737 {6, {24, 39, 84, 93, 123, 158, 0}},
738 {6, {24, 57, 68, 115, 142, 173, 0}},
739 {6, {28, 42, 60, 115, 131, 161, 0}},
740 {6, {14, 57, 87, 111, 120, 163, 0}},
741 {7, {3, 58, 71, 113, 118, 162, 172}},
742 {6, {26, 46, 85, 97, 133, 152, 0}},
743 {5, {4, 43, 77, 108, 140, 0, 0}},
744 {6, {9, 45, 68, 102, 135, 164, 0}},
745 {6, {8, 49, 58, 92, 127, 163, 0}},
746 {6, {13, 56, 57, 108, 119, 165, 0}},
747 {6, {16, 54, 61, 115, 124, 153, 0}},
748 {6, {2, 53, 69, 100, 139, 169, 0}},
749 {6, {0, 35, 81, 107, 126, 173, 0}},
750 {5, {4, 52, 80, 104, 139, 0, 0}},
751 {6, {28, 52, 66, 98, 141, 172, 0}},
752 {6, {17, 48, 73, 96, 114, 166, 0}},
753 {6, {1, 56, 62, 102, 137, 156, 0}},
754 {6, {25, 37, 78, 111, 134, 170, 0}},
755 {6, {10, 51, 65, 87, 118, 147, 0}},
756 {6, {19, 39, 67, 116, 140, 159, 0}},
757 {6, {10, 47, 80, 88, 145, 168, 0}},
758 {6, {28, 46, 79, 91, 145, 171, 0}},
759 {6, {5, 31, 86, 103, 144, 168, 0}},
760 {6, {26, 33, 73, 105, 130, 164, 0}},
761 {5, {11, 55, 83, 87, 138, 0, 0}},
762 {6, {12, 55, 61, 110, 145, 170, 0}},
763 {6, {25, 36, 79, 104, 143, 150, 0}},
764 {6, {16, 30, 81, 112, 120, 160, 0}},
765 {5, {27, 48, 58, 93, 136, 0, 0}},
766 {6, {6, 54, 82, 100, 130, 167, 0}},
767 {6, {23, 49, 77, 105, 142, 148, 0}}}};
768
769// Reciprocal positions of each edge in the fixed (174,87) parity graph.
770// Only lookup work is moved out of BP: all message updates keep their
771// original traversal and floating-point operation order.
772struct BPEdgeSlots {
773 std::array<std::array<std::uint8_t, BP_MAX_ROWS>, M> inBit{};
774 std::array<std::array<std::uint8_t, BP_MAX_CHECKS>, N> inCheck{};
775 bool valid = true;
776};
777
778constexpr BPEdgeSlots BP_EDGE_SLOTS = [] {
779 BPEdgeSlots edges;
780 constexpr std::uint8_t missing = 0xff;
781 for (auto &row : edges.inBit)
782 row.fill(missing);
783 for (auto &row : edges.inCheck)
784 row.fill(missing);
785
786 for (int check = 0; check < M; ++check) {
787 if (Nm[check].valid_neighbors < 0 ||
788 Nm[check].valid_neighbors > BP_MAX_ROWS) {
789 edges.valid = false;
790 continue;
791 }
792 for (int edge = 0; edge < Nm[check].valid_neighbors; ++edge) {
793 int const bit = Nm[check].neighbors[edge];
794 if (bit < 0 || bit >= N) {
795 edges.valid = false;
796 continue;
797 }
798 int matches = 0;
799 for (int bitEdge = 0; bitEdge < BP_MAX_CHECKS; ++bitEdge) {
800 if (Mn[bit][bitEdge] != check)
801 continue;
802 ++matches;
803 edges.inBit[check][edge] =
804 static_cast<std::uint8_t>(bitEdge);
805 if (edges.inCheck[bit][bitEdge] != missing)
806 edges.valid = false;
807 edges.inCheck[bit][bitEdge] =
808 static_cast<std::uint8_t>(edge);
809 }
810 if (matches != 1)
811 edges.valid = false;
812 }
813 }
814 for (int bit = 0; bit < N; ++bit)
815 for (int bitEdge = 0; bitEdge < BP_MAX_CHECKS; ++bitEdge)
816 if (Mn[bit][bitEdge] < 0 || Mn[bit][bitEdge] >= M ||
817 edges.inCheck[bit][bitEdge] == missing)
818 edges.valid = false;
819 return edges;
820}();
821static_assert(BP_EDGE_SLOTS.valid,
822 "every BP edge must occur exactly once in both parity tables");
823
827BPResult bpdecode174(std::array<float, N> const &llr,
828 std::array<int8_t, K> &decoded,
829 std::array<int8_t, N> &cw,
830 BPOptions const options = {}) {
831#ifdef JS8_CPU_BENCHMARK
832 BenchmarkScope benchmarkScope{benchmarkBpCalls, benchmarkBpNanos};
833 static thread_local std::uint32_t samplingState = 0xa1d30fc5u;
834 samplingState = samplingState * 1664525u + 1013904223u;
835 bool const samplePhases = (samplingState >> 26) == 0;
836 if (samplePhases)
837 ++benchmarkBpProfiledCalls;
838 auto phaseStarted = samplePhases ? std::chrono::steady_clock::now()
839 : std::chrono::steady_clock::time_point{};
840 auto recordPhase = [&](std::atomic<std::uint64_t> &counter) {
841 if (!samplePhases)
842 return;
843 auto const now = std::chrono::steady_clock::now();
844 counter += std::chrono::duration_cast<std::chrono::nanoseconds>(
845 now - phaseStarted)
846 .count();
847 phaseStarted = now;
848 };
849#endif
850 std::array<float, N> scaledLlr = {};
851 for (int i = 0; i < N; ++i)
852 scaledLlr[i] = js8::bp::channelLlr(llr[i] * options.llrScale);
853
854 // Initialize messages and variables.
855 std::array<std::array<float, BP_MAX_CHECKS>, N> tov = {};
856 std::array<std::array<float, BP_MAX_ROWS>, M> toc = {};
857 std::array<std::array<float, BP_MAX_ROWS>, M> tanhtoc = {};
858 std::array<float, N> zn = {};
859 std::array<int, M> synd = {};
860
861 BPResult result;
862 int ncnt = 0;
863 int nclast = 0;
864
865 // Initialize toc (messages from bits to checks).
866 for (int i = 0; i < M; ++i) {
867 for (int j = 0; j < Nm[i].valid_neighbors; ++j)
868 toc[i][j] = scaledLlr[Nm[i].neighbors[j]];
869 }
870#ifdef JS8_CPU_BENCHMARK
871 if (samplePhases)
872 phaseStarted = std::chrono::steady_clock::now();
873#endif
874
875 // Preserve the legacy inclusive iteration bound for the normal decoder.
876 for (int iter = 0; iter <= options.maxIterations; ++iter) {
877 if (options.shouldCancel && (*options.shouldCancel)()) {
878 result.cancelled = true;
879 return result;
880 }
881 result.iterations = iter;
882
883 // Update bit log likelihood ratios.
884 for (int i = 0; i < N; ++i) {
885 zn[i] = scaledLlr[i] +
886 std::accumulate(tov[i].begin(),
887 tov[i].begin() + BP_MAX_CHECKS, 0.0f);
888 }
889
890 for (int i = 0; i < N; ++i)
891 cw[i] = zn[i] > 0 ? 1 : 0;
892#ifdef JS8_CPU_BENCHMARK
893 recordPhase(benchmarkBpVariableNanos);
894#endif
895
896 int ncheck = 0;
897 for (int i = 0; i < M; ++i) {
898 synd[i] = 0;
899 for (int j = 0; j < Nm[i].valid_neighbors; ++j)
900 synd[i] += cw[Nm[i].neighbors[j]];
901 if (synd[i] % 2 != 0)
902 ++ncheck;
903 }
904
905 result.finalChecks = ncheck;
906 if (ncheck < result.bestChecks) {
907 result.bestChecks = ncheck;
908 result.bestCw = cw;
909 result.bestCwValid = true;
910 }
911#ifdef JS8_CPU_BENCHMARK
912 recordPhase(benchmarkBpSyndromeNanos);
913#endif
914
915 if (ncheck == 0) {
916 std::copy(cw.begin() + M, cw.end(), decoded.begin());
917
918 int nerr = 0;
919 for (int i = 0; i < N; ++i) {
920 if ((2 * cw[i] - 1) * llr[i] < 0.0f)
921 ++nerr;
922 }
923
924 result.hardErrors = nerr;
925 result.bestCw = cw;
926 result.bestCwValid = true;
927 return result;
928 }
929
930 // The normal decoder retains its legacy early stopping behavior. The
931 // bounded rescue decoder disables it so near-converged trapping states
932 // can continue iterating.
933 if (iter > 0) {
934 int const nd = ncheck - nclast;
935 ncnt = (nd < 0) ? 0 : ncnt + 1;
936 if (options.earlyAbort && ncnt >= 5 && iter >= 10 && ncheck > 15) {
937 result.earlyAborted = true;
938 // Deliberately leave `cw` at the last-iteration state: the
939 // minimum-syndrome word is available via `result.bestCw`
940 // without changing normal output semantics.
941 return result;
942 }
943 }
944 nclast = ncheck;
945
946 // Send messages from bits to check nodes.
947 for (int i = 0; i < M; ++i) {
948 for (int j = 0; j < Nm[i].valid_neighbors; ++j) {
949 int const ibj = Nm[i].neighbors[j];
950 toc[i][j] = zn[ibj];
951#ifdef JS8_BENCHMARK_LINEAR_BP_EDGES
952 for (int k = 0; k < BP_MAX_CHECKS; ++k) {
953 if (Mn[ibj][k] == i)
954 toc[i][j] -= tov[ibj][k];
955 }
956#else
957 toc[i][j] -= tov[ibj][BP_EDGE_SLOTS.inBit[i][j]];
958#endif
959 }
960 }
961#ifdef JS8_CPU_BENCHMARK
962 recordPhase(benchmarkBpBitToCheckNanos);
963#endif
964
965 // Send messages from check nodes to variable nodes.
966 for (int i = 0; i < M; ++i) {
967#ifdef JS8_BENCHMARK_FULL_BP_TANH
968 for (int j = 0; j < 7; ++j)
969#else
970 // Padded check-node slots are never read by the message update.
971 for (int j = 0; j < Nm[i].valid_neighbors; ++j)
972#endif
973 tanhtoc[i][j] = std::tanh(-toc[i][j] / 2.0f);
974 }
975#ifdef JS8_CPU_BENCHMARK
976 recordPhase(benchmarkBpTanhNanos);
977#endif
978
979 // Each outgoing message reads only the completed tanhtoc array; no
980 // other outgoing message is an input to this phase. Visit check edges
981 // contiguously while keeping the exact left-to-right product for each
982 // message. The old bit-centric order is available for A/B benchmarks.
983#ifdef JS8_BENCHMARK_ORIGINAL_CHECK_TO_BIT_LOOP
984 for (int i = 0; i < N; ++i) {
985 for (int j = 0; j < BP_MAX_CHECKS; ++j) {
986 int const ichk = Mn[i][j];
987 if (ichk >= 0) {
988 float Tmn = 1.0f;
989 for (int k = 0; k < Nm[ichk].valid_neighbors; ++k) {
990#ifdef JS8_BENCHMARK_MAPPED_BP_CHECK_TO_BIT
991 if (k != BP_EDGE_SLOTS.inCheck[i][j])
992#else
993 if (Nm[ichk].neighbors[k] != i)
994#endif
995 Tmn *= tanhtoc[ichk][k];
996 }
997 tov[i][j] = js8::bp::checkMessage(Tmn);
998 }
999 }
1000 }
1001#else
1002 for (int ichk = 0; ichk < M; ++ichk) {
1003 for (int edge = 0; edge < Nm[ichk].valid_neighbors; ++edge) {
1004 float Tmn = 1.0f;
1005 for (int k = 0; k < Nm[ichk].valid_neighbors; ++k)
1006 if (k != edge)
1007 Tmn *= tanhtoc[ichk][k];
1008 int const bit = Nm[ichk].neighbors[edge];
1009 tov[bit][BP_EDGE_SLOTS.inBit[ichk][edge]] =
1011 }
1012 }
1013#endif
1014#ifdef JS8_CPU_BENCHMARK
1015 recordPhase(benchmarkBpCheckToBitNanos);
1016#endif
1017 }
1018
1019 // Exhausted iterations without converging: `cw` intentionally keeps the
1020 // last-iteration state (legacy semantics for ordinary LDPC feedback).
1021 // Callers needing the closest word use `result.bestCw` instead.
1022 return result;
1023}
1024} // namespace
1025
1026/******************************************************************************/
1027// Local Routines
1028/******************************************************************************/
1029
1030namespace {
1031constexpr std::string_view alphabet =
1032 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-+";
1033
1034static_assert(alphabet.size() == 64);
1035
1036// Function that either translates valid JS8 message characters to their
1037// corresponding 6-bit word value, or throws. This will end up doing a
1038// direct index operation into a 256-byte table, the creation of which
1039// must be constexpr under C++17.
1040
1041constexpr auto alphabetWord = []() {
1042 constexpr std::uint8_t invalid = 0xff;
1043
1044 constexpr auto words = []() {
1045 std::array<std::uint8_t, 256> words{};
1046
1047 for (auto &word : words)
1048 word = invalid;
1049
1050 for (std::size_t i = 0; i < alphabet.size(); ++i) {
1051 words[static_cast<std::uint8_t>(alphabet[i])] =
1052 static_cast<std::uint8_t>(i);
1053 }
1054
1055 return words;
1056 }();
1057
1058 return [words](char const value) {
1059 if (auto const word = words[value]; word != invalid) {
1060 return word;
1061 }
1062
1063 throw std::runtime_error("Invalid character in message");
1064 };
1065}();
1066
1067// Sanity check key bounds of the 6-bit encoding table.
1068
1069static_assert(alphabetWord('0') == 0);
1070static_assert(alphabetWord('A') == 10);
1071static_assert(alphabetWord('a') == 36);
1072static_assert(alphabetWord('-') == 62);
1073static_assert(alphabetWord('+') == 63);
1074
1075template <typename T> std::uint16_t CRC12(T const &range) {
1076 return boost::augmented_crc<12, 0xc06>(range.data(), range.size()) ^ 42;
1077}
1078
1079bool checkCRC12(std::array<std::int8_t, KK> const &decoded) {
1080 std::array<uint8_t, 11> bits = {};
1081
1082 for (std::size_t i = 0; i < decoded.size(); ++i) {
1083 if (decoded[i])
1084 bits[i / 8] |= (1 << (7 - (i % 8)));
1085 }
1086
1087 // Extract the received CRC-12.
1088
1089 uint16_t crc = (static_cast<uint16_t>(bits[9] & 0x1F) << 7) |
1090 (static_cast<uint16_t>(bits[10]) >> 1);
1091
1092 // Clear bits that correspond to the CRC in the last bytes.
1093
1094 bits[9] &= 0xE0;
1095 bits[10] = 0x00;
1096
1097 // Compute CRC and indicate if we have a match.
1098
1099 return crc == CRC12(bits);
1100}
1101
1102std::string extractmessage174(std::array<int8_t, KK> const &decoded) {
1103 std::string message;
1104
1105 // Ensure received CRC matches computed CRC.
1106
1107 if (checkCRC12(decoded)) {
1108 message.reserve(12);
1109
1110 // Decode the message from the 72 data bits
1111
1112 std::array<uint8_t, 12> words;
1113
1114 for (std::size_t i = 0; i < 12; ++i) {
1115 words[i] = (decoded[i * 6 + 0] << 5) | (decoded[i * 6 + 1] << 4) |
1116 (decoded[i * 6 + 2] << 3) | (decoded[i * 6 + 3] << 2) |
1117 (decoded[i * 6 + 4] << 1) | (decoded[i * 6 + 5] << 0);
1118 }
1119
1120 // Map 6-bit words to the alphabet
1121
1122 for (auto const word : words)
1123 message += alphabet[word];
1124 }
1125
1126 return message;
1127}
1128
1129// Parity matrix for JS8 message generation.
1130//
1131// This should be 952 bytes in size; to store an 87x87 matrix of bits,
1132// you need 7569 bits, which requires 119 64-bit values, or 952 bytes.
1133//
1134// Background here is that this is a low-density parity check code (LDPC),
1135// generated using the PEG algorithm. In short, true values in a row i of
1136// the matrix define which of the 87 message bits must be summed, modulo
1137// 2, to produce the ith parity check bit. Decent references on this are:
1138//
1139// 1. https://wsjt.sourceforge.io/FT4_FT8_QEX.pdf
1140// 2. https://inference.org.uk/mackay/PEG_ECC.html
1141// 3. https://github.com/Lcrypto/classic-PEG-
1142//
1143// The data used was harvested from the original 'ldpc_174_87_params.f90',
1144// but you'll note that the rows have been reordered here, because this
1145// isn't Fortran; C++ is row-major, not column-major.
1146
1147constexpr auto parity = []() {
1148 constexpr std::size_t Rows = 87;
1149 constexpr std::size_t Cols = 87;
1150
1151 using ElementType = std::uint64_t;
1152 constexpr std::size_t ElementSize =
1153 std::numeric_limits<ElementType>::digits;
1154
1155 constexpr auto matrix = []() {
1156 constexpr std::array<std::string_view, Rows> Data = {
1157 "23bba830e23b6b6f50982e", "1f8e55da218c5df3309052",
1158 "ca7b3217cd92bd59a5ae20", "56f78313537d0f4382964e",
1159 "6be396b5e2e819e373340c", "293548a138858328af4210",
1160 "cb6c6afcdc28bb3f7c6e86", "3f2a86f5c5bd225c961150",
1161 "849dd2d63673481860f62c", "56cdaec6e7ae14b43feeee",
1162 "04ef5cfa3766ba778f45a4", "c525ae4bd4f627320a3974",
1163 "41fd9520b2e4abeb2f989c", "7fb36c24085a34d8c1dbc4",
1164 "40fc3e44bb7d2bb2756e44", "d38ab0a1d2e52a8ec3bc76",
1165 "3d0f929ef3949bd84d4734", "45d3814f504064f80549ae",
1166 "f14dbf263825d0bd04b05e", "db714f8f64e8ac7af1a76e",
1167 "8d0274de71e7c1a8055eb0", "51f81573dd4049b082de14",
1168 "d8f937f31822e57c562370", "b6537f417e61d1a7085336",
1169 "ecbd7c73b9cd34c3720c8a", "3d188ea477f6fa41317a4e",
1170 "1ac4672b549cd6dba79bcc", "a377253773ea678367c3f6",
1171 "0dbd816fba1543f721dc72", "ca4186dd44c3121565cf5c",
1172 "29c29dba9c545e267762fe", "1616d78018d0b4745ca0f2",
1173 "fe37802941d66dde02b99c", "a9fa8e50bcb032c85e3304",
1174 "83f640f1a48a8ebc0443ea", "3776af54ccfbae916afde6",
1175 "a8fc906976c35669e79ce0", "f08a91fb2e1f78290619a8",
1176 "cc9da55fe046d0cb3a770c", "d36d662a69ae24b74dcbd8",
1177 "40907b01280f03c0323946", "d037db825175d851f3af00",
1178 "1bf1490607c54032660ede", "0af7723161ec223080be86",
1179 "eca9afa0f6b01d92305edc", "7a8dec79a51e8ac5388022",
1180 "9059dfa2bb20ef7ef73ad4", "6abb212d9739dfc02580f2",
1181 "f6ad4824b87c80ebfce466", "d747bfc5fd65ef70fbd9bc",
1182 "612f63acc025b6ab476f7c", "05209a0abb530b9e7e34b0",
1183 "45b7ab6242b77474d9f11a", "6c280d2a0523d9c4bc5946",
1184 "f1627701a2d692fd9449e6", "8d9071b7e7a6a2eed6965e",
1185 "bf4f56e073271f6ab4bf80", "c0fc3ec4fb7d2bb2756644",
1186 "57da6d13cb96a7689b2790", "a9fa2eefa6f8796a355772",
1187 "164cc861bdd803c547f2ac", "cc6de59755420925f90ed2",
1188 "a0c0033a52ab6299802fd2", "b274db8abd3c6f396ea356",
1189 "97d4169cb33e7435718d90", "81cfc6f18c35b1e1f17114",
1190 "481a2a0df8a23583f82d6c", "081c29a10d468ccdbcecb6",
1191 "2c4142bf42b01e71076acc", "a6573f3dc8b16c9d19f746",
1192 "c87af9a5d5206abca532a8", "012dee2198eba82b19a1da",
1193 "b1ca4ea2e3d173bad4379c", "b33ec97be83ce413f9acc8",
1194 "5b0f7742bca86b8012609a", "37d8e0af9258b9e8c5f9b2",
1195 "35ad3fb0faeb5f1b0c30dc", "6114e08483043fd3f38a8a",
1196 "cd921fdf59e882683763f6", "95e45ecd0135aca9d6e6ae",
1197 "2e547dd7a05f6597aac516", "14cd0f642fc0c5fe3a65ca",
1198 "3a0a1dfd7eee29c2e827e0", "c8b5dffc335095dcdcaf2a",
1199 "3dd01a59d86310743ec752", "8abdb889efbe39a510a118",
1200 "3f231f212055371cf3e2a2"};
1201
1202 constexpr std::size_t Total = (Rows * Cols + ElementSize - 1);
1203 constexpr std::size_t Count = Total / ElementSize;
1204 constexpr std::array<std::uint8_t, 4> Masks = {0x8, 0x4, 0x2, 0x1};
1205
1206 std::array<ElementType, Count> data{};
1207
1208 for (std::size_t row = 0; row < Rows; ++row) {
1209 std::size_t col = 0;
1210
1211 for (auto const c : Data[row]) {
1212 std::uint8_t const value =
1213 (c >= '0' && c <= '9') ? c - '0'
1214 : (c >= 'a' && c <= 'f') ? c - 'a' + 10
1215 : (c >= 'A' && c <= 'F') ? c - 'A' + 10
1216 : throw "Invalid hex";
1217
1218 for (auto const mask : Masks) {
1219 if (col >= Cols)
1220 break;
1221 if (value & mask) {
1222 auto const index = row * Cols + col;
1223 data[index / ElementSize] |=
1224 (ElementType(1) << (index % ElementSize));
1225 }
1226 ++col;
1227 }
1228 }
1229 }
1230 return data;
1231 }();
1232
1233 return [matrix](std::size_t const row, std::size_t const col) {
1234 auto const index = row * Cols + col;
1235 return (matrix[index / ElementSize] >> (index % ElementSize)) & 1;
1236 };
1237}();
1238} // namespace
1239
1240/******************************************************************************/
1241// DecodeMode Template Class
1242/******************************************************************************/
1243
1244// Mode-parameterized decode class.
1245
1246namespace {
1247template <typename Mode> class DecodeMode {
1248 // Data members
1249
1250 std::array<float, Mode::NFFT1> nuttal;
1251 using SyncWaveforms =
1252 std::array<std::array<std::array<std::complex<float>, Mode::NDOWNSPS>,
1253 7>,
1254 3>;
1255 SyncWaveforms csyncs;
1256 alignas(64) std::array<std::complex<float>, Mode::NDOWNSPS> csymb;
1257 alignas(64) std::array<std::complex<float>, Mode::NMAX> filter;
1258 alignas(64) std::array<std::complex<float>, Mode::NMAX> cfilt;
1259 alignas(64) std::array<std::complex<float>, Mode::NDFFT1 / 2 + 1> ds_cx;
1260 alignas(64) std::array<std::complex<float>, Mode::NFFT1 / 2 + 1> sd;
1261 alignas(64) std::array<std::complex<float>, NP> cd0;
1262 std::array<float, Mode::NMAX> dd;
1263 std::array<std::array<float, Mode::NHSYM>, Mode::NSPS> s;
1264 std::array<float, Mode::NSPS> savg;
1265 FFTWPlanManager plans;
1266 SyncIndex sync;
1267 js8::SoftCombiner<N> m_softCombiner;
1268 bool m_enableFreqTracking = true;
1269 bool m_enableTimingTracking = true;
1270 bool m_enableDeepSearch = true;
1271 bool m_enableLdpcRescue = true;
1272 bool m_enableCoherentData = true;
1273 bool m_enableAidedRedemod = true;
1274 float m_llrErasureThreshold = js8::llrErasureThreshold();
1275 float m_llrScale = js8::llrGlobalScale();
1276 bool m_normalizeLlrsForBenchmark =
1277 std::getenv("JS8_LLR_FRAME_NORMALIZATION") != nullptr;
1278 bool m_enableLdpcFeedback = js8::ldpcFeedbackEnabled();
1279 int m_maxLdpcPasses = js8::ldpcFeedbackMaxPasses();
1280
1281 using Plan = FFTWPlanManager::Type;
1282
1283 static constexpr auto Costas = JS8::Costas::array(Mode::NCOSTAS);
1284
1285 // Fore and aft tapers to reduce spectral leakage during the
1286 // downsampling process. We can compute these at compile time.
1287
1288 static constexpr auto Taper = [] {
1289 std::array<std::array<float, Mode::NDD + 1>, 2> taper{};
1290
1291 for (size_t i = 0; i <= Mode::NDD; ++i) {
1292 float const value =
1293 0.5f *
1294 (1.0f + cos_approx(i * std::numbers::pi_v<float> / Mode::NDD));
1295
1296 taper[1][i] = value; // TailTaper (original taper)
1297 taper[0][Mode::NDD - i] = value; // HeadTaper (reversed taper)
1298 }
1299
1300 return taper;
1301 }();
1302
1303 // Baseline computation support.
1304
1305 using Points = Eigen::Matrix<double, BASELINE_NODES.size(), 2>;
1306 using Vandermonde =
1307 Eigen::Matrix<double, BASELINE_NODES.size(), BASELINE_NODES.size()>;
1308 using Coefficients = Eigen::Vector<double, BASELINE_NODES.size()>;
1309
1310 Points p;
1311 Vandermonde V;
1312 Coefficients c;
1313
1314 // Polynomial evaluation using Estrin's method, loop is unrolled at
1315 // compile time. A compiler should emit SIMD instructions from what
1316 // it sees here when the optimizer is involved, but even without it,
1317 // we'll likely see fused multiply-add instructions.
1318
1319 inline auto evaluate(float const x) const {
1320 return [this]<Eigen::Index... I>(
1321 float const x, std::integer_sequence<Eigen::Index, I...>) {
1322 auto baseline = 0.0;
1323 auto exponent = 1.0;
1324
1325 ((baseline += (c[I * 2] + c[I * 2 + 1] * x) * exponent,
1326 exponent *= x * x),
1327 ...);
1328
1329 return static_cast<float>(baseline);
1330 }(x, std::make_integer_sequence<Eigen::Index,
1331 Coefficients::SizeAtCompileTime / 2>{});
1332 }
1333
1335 struct ToneBinLlrs {
1336 std::array<float, N> llr0;
1337 std::array<float, N> llr1;
1338 js8::CoherentLikelihoodTelemetry coherentTelemetry;
1339 };
1340
1341 // Shared tone-bin to LLR stack: magnitudes -> winners -> Costas-only
1342 // coherent blend -> whitening -> LLRs -> erasure. Both the first-pass
1343 // demodulation and the decoder-aided re-demodulation call this same
1344 // implementation with their own freshly demodulated bins, so the aided
1345 // pass regenerates likelihoods through the identical processing rather
1346 // than a simplified copy.
1347 ToneBinLlrs processToneBins(
1348 std::array<std::array<float, NN>, NROWS> const &s2,
1349 std::array<std::array<std::complex<float>, NN>, NROWS> const
1350 &complexS2,
1351 std::array<int, NN> const &symbolBaseStarts,
1352 std::array<int, NN> const &symbolTimingShifts,
1353 std::array<float, NN> const &symbolTrackerHz) {
1354#ifdef JS8_CPU_BENCHMARK
1355 BenchmarkScope benchmarkScope{benchmarkToneBinsCalls,
1356 benchmarkToneBinsNanos};
1357#endif
1358 constexpr float FS2 = 12000.0f / Mode::NDOWN;
1359
1360 std::array<std::array<float, ND>, NROWS> s1;
1361
1362 // Fill s1 from s2, excluding the Costas arrays.
1363
1364 for (int row = 0; row < NROWS; ++row) {
1365 std::copy(s2[row].begin() + 7, s2[row].begin() + 36,
1366 s1[row].begin());
1367 std::copy(s2[row].begin() + 43, s2[row].begin() + 72,
1368 s1[row].begin() + 29);
1369 }
1370
1371 // Identify winning tones (max magnitude) for each data symbol.
1372 std::array<int, ND> symbolWinners = {};
1373
1374 for (int j = 0; j < ND; ++j) {
1375 int winner = 0;
1376 float best = s1[0][j];
1377
1378 for (int i = 1; i < NROWS; ++i) {
1379 if (s1[i][j] > best) {
1380 best = s1[i][j];
1381 winner = i;
1382 }
1383 }
1384
1385 symbolWinners[j] = winner;
1386 }
1387
1388 std::optional<js8::CoherentBlend<NROWS, ND>> coherentBlend;
1389 js8::CoherentLikelihoodTelemetry coherentTelemetry;
1390
1391 if (m_enableCoherentData) {
1392 static_assert(NROWS == 8, "coherent path expects 8 FSK tones");
1393 double const downsampledRate =
1394 static_cast<double>(FS2);
1395
1396 // Known Costas pilot observations with full phase metadata.
1397 // Coverage of at least four pilots per Costas block is required
1398 // before trusting a fit.
1399 std::vector<js8::CoherentPilot> pilots;
1400 pilots.reserve(NS);
1401 std::array<int, 3> blockValid{};
1402 for (int block = 0; block < 3; ++block) {
1403 for (int column = 0; column < 7; ++column) {
1404 int const symbolIndex = block * 36 + column;
1405 int const expectedTone = Costas[block][column];
1406 std::complex<float> const bin =
1407 complexS2[expectedTone][symbolIndex];
1408 double const magnitude = std::abs(bin);
1409 if (!std::isfinite(magnitude) || !(magnitude > 0.0f))
1410 continue;
1411 // The helper adds timingShiftSamples/sampleRateHz itself to
1412 // obtain the effective extraction timestamp.
1413 double const startSeconds =
1414 static_cast<double>(
1415 symbolBaseStarts[symbolIndex]) /
1416 downsampledRate;
1417 if (!std::isfinite(startSeconds))
1418 continue;
1419 pilots.push_back(js8::CoherentPilot{
1420 startSeconds,
1421 std::complex<double>{bin.real(), bin.imag()},
1422 expectedTone, symbolIndex,
1423 static_cast<double>(
1424 symbolTimingShifts[symbolIndex]),
1425 static_cast<double>(
1426 symbolTrackerHz[symbolIndex])});
1427 ++blockValid[static_cast<std::size_t>(block)];
1428 }
1429 }
1430
1431 bool const pilotCoverage = blockValid[0] >= 4 &&
1432 blockValid[1] >= 4 &&
1433 blockValid[2] >= 4;
1434 if (pilotCoverage) {
1435 // Data symbols use the same s1 layout as the magnitude path:
1436 // globals 7..35 then 43..71.
1437 std::vector<js8::CoherentDataSymbol> dataSymbols;
1438 dataSymbols.reserve(ND);
1439 bool dataValid = true;
1440 for (int j = 0; j < ND && dataValid; ++j) {
1441 int const symbolIndex = j < 29 ? j + 7 : j + 14;
1442 // As for pilots, retain the nominal start here; the helper
1443 // adds timingShiftSamples/sampleRateHz itself to obtain
1444 // the effective extraction time.
1445 double const startSeconds =
1446 static_cast<double>(
1447 symbolBaseStarts[symbolIndex]) /
1448 downsampledRate;
1449 if (!std::isfinite(startSeconds)) {
1450 dataValid = false;
1451 break;
1452 }
1453 js8::CoherentDataSymbol dataSymbol;
1454 dataSymbol.baseTimeSeconds = startSeconds;
1455 dataSymbol.timingShiftSamples = static_cast<double>(
1456 symbolTimingShifts[symbolIndex]);
1457 dataSymbol.trackerHz = static_cast<double>(
1458 symbolTrackerHz[symbolIndex]);
1459 for (int tone = 0; tone < NROWS; ++tone) {
1460 dataSymbol.bins[static_cast<std::size_t>(tone)] =
1461 complexS2[tone][symbolIndex];
1462 if (!std::isfinite(
1463 dataSymbol.bins[static_cast<std::size_t>(tone)]
1464 .real()) ||
1465 !std::isfinite(
1466 dataSymbol.bins[static_cast<std::size_t>(tone)]
1467 .imag())) {
1468 dataValid = false;
1469 break;
1470 }
1471 }
1472 dataSymbols.push_back(dataSymbol);
1473 }
1474
1475 if (dataValid) {
1476 double const frameSpanSeconds =
1477 (static_cast<double>(symbolBaseStarts[NN - 1]) +
1478 static_cast<double>(symbolTimingShifts[NN - 1]) -
1479 static_cast<double>(symbolBaseStarts[0]) -
1480 static_cast<double>(symbolTimingShifts[0])) /
1481 downsampledRate;
1482 if (std::isfinite(frameSpanSeconds) &&
1483 frameSpanSeconds > 0.0) {
1484#ifdef JS8_CPU_BENCHMARK
1485 auto const coherentStarted =
1486 std::chrono::steady_clock::now();
1487#endif
1488 js8::CoherentToneResult const coherent =
1489 js8::computeCoherentToneScores(
1490 pilots, dataSymbols, 12,
1491 0.5 * frameSpanSeconds, Mode::NDOWNSPS,
1492 static_cast<double>(FS2));
1493#ifdef JS8_CPU_BENCHMARK
1494 ++benchmarkCoherentCalls;
1495 benchmarkCoherentNanos +=
1496 std::chrono::duration_cast<std::chrono::nanoseconds>(
1497 std::chrono::steady_clock::now() -
1498 coherentStarted)
1499 .count();
1500#endif
1501 coherentTelemetry = coherent.telemetry;
1502 if (!coherent.coherentNumerators.empty() &&
1503 coherent.alpha > 0.0) {
1504 js8::CoherentBlend<NROWS, ND> blend;
1505 blend.amplitude = coherent.amplitude;
1506 blend.alpha =
1507 static_cast<float>(coherent.alpha);
1508 for (int tone = 0; tone < NROWS; ++tone)
1509 for (int j = 0; j < ND; ++j)
1510 blend.numerators[static_cast<std::size_t>(tone)]
1511 [static_cast<std::size_t>(j)] =
1512 coherent.coherentNumerators
1513 [static_cast<std::size_t>(j)]
1514 [static_cast<std::size_t>(tone)];
1515 coherentBlend = blend;
1516 }
1517 }
1518 }
1519 }
1520 }
1521
1523 s1, symbolWinners, m_llrErasureThreshold,
1524 decoder_js8().isDebugEnabled(), coherentBlend, m_llrScale,
1525 m_normalizeLlrsForBenchmark
1526 ? js8::WhiteningProcessor<NROWS, ND, N>::Normalization::FrameSigma283
1527 : js8::WhiteningProcessor<NROWS, ND, N>::Normalization::None);
1528
1529 if (decoder_js8().isDebugEnabled()) {
1530 qCDebug(decoder_js8)
1531 << "coherent likelihood"
1532 << "coherentEnabled" << coherentTelemetry.enabled
1533 << "pilotCount" << coherentTelemetry.pilotCount
1534 << "pilotPhaseRmsRad" << coherentTelemetry.phaseRmsRad
1535 << "pilotPhaseRmsDeg" << coherentTelemetry.phaseRmsDeg
1536 << "coherentWeight" << coherentTelemetry.alpha
1537 << "fittedPhaseRad" << coherentTelemetry.phi0
1538 << "fittedResidualHz" << coherentTelemetry.deltaF
1539 << "fittedDriftHzPerSec" << coherentTelemetry.fdot
1540 << "pilotAmplitude" << coherentTelemetry.pilotAmplitude
1541 << "avgCoherentToneMargin"
1542 << coherentTelemetry.avgCoherentToneMargin.value_or(-1.0)
1543 << "avgNoncoherentToneMargin"
1544 << coherentTelemetry.avgNoncoherentToneMargin.value_or(-1.0);
1545 }
1546
1547 auto llr0 = whitening.llr0;
1548 auto llr1 = whitening.llr1;
1549
1550 // Only apply a second erasure threshold pass if whitening didn't
1551 // already zero low-magnitude LLRs using the configured threshold.
1552 if (!whitening.erasureApplied) {
1553 std::size_t erasuresAfterThreshold = 0;
1554 double sumAbsPreErasure = 0.0;
1555 double sumAbsPostErasure = 0.0;
1556
1557 auto const applyErasureThreshold = [&](auto &llr) {
1558 for (auto const value : llr)
1559 sumAbsPreErasure += std::abs(value);
1560
1561 if (m_llrErasureThreshold > 0.0f) {
1562 for (auto &value : llr) {
1563 if (std::abs(value) < m_llrErasureThreshold) {
1564 value = 0.0f;
1565 ++erasuresAfterThreshold;
1566 }
1567
1568 sumAbsPostErasure += std::abs(value);
1569 }
1570 } else {
1571 for (auto const value : llr)
1572 sumAbsPostErasure += std::abs(value);
1573 }
1574 };
1575
1576 applyErasureThreshold(llr0);
1577 applyErasureThreshold(llr1);
1578
1579 if (decoder_js8().isDebugEnabled()) {
1580 auto const total =
1581 static_cast<double>(llr0.size() + llr1.size());
1582 double const avgPre =
1583 total > 0.0 ? sumAbsPreErasure / total : 0.0;
1584 double const avgPost =
1585 total > 0.0 ? sumAbsPostErasure / total : 0.0;
1586
1587 qCDebug(decoder_js8)
1588 << "LLR erasure threshold" << m_llrErasureThreshold
1589 << "erasures:" << erasuresAfterThreshold
1590 << "avg|LLR| pre/post:" << avgPre << avgPost;
1591 }
1592 }
1593
1594 ToneBinLlrs out;
1595 out.llr0 = llr0;
1596 out.llr1 = llr1;
1597 out.coherentTelemetry = coherentTelemetry;
1598 return out;
1599 }
1600
1601 std::optional<Decode> js8dec(bool const syncStats, bool const lsubtract,
1602 float &f1, float &xdt, int &nharderrors,
1603 float &xsnr, int &ldpcRescueBudget,
1604 JS8::Event::Emitter emitEvent,
1605 js8::OptionalWorkBudget *optional,
1606 bool optionalCandidate = false) {
1607#ifdef JS8_CPU_BENCHMARK
1608 BenchmarkScope benchmarkScope{benchmarkDecodeCalls, benchmarkDecodeNanos};
1609#endif
1610 constexpr float FR = 12000.0f / Mode::NFFT1; // Frequency resolution
1611 constexpr float FS2 = 12000.0f / Mode::NDOWN;
1612 constexpr float DT2 = 1.0f / FS2;
1613
1614 float const coarseStartHz = f1;
1615 float const coarseStartDt = xdt;
1616
1617 auto const index =
1618 static_cast<int>(std::round(f1 / FR)); // Closest index
1619 float const scaled_value =
1620 0.1f * (savg[index] - Mode::BASESUB); // Adjust and scale
1621 float const xbase =
1622 std::pow(10.0f, scaled_value); // Convert to linear scale
1623
1624 float delfbest = 0.0f;
1625 int ibest = 0;
1626
1627 // Downsample the signal and prepare for processing.
1628
1629 js8_downsample(f1);
1630
1631 int i0 = static_cast<int>(std::round((xdt + Mode::ASTART) * FS2));
1632 float smax = 0.0f;
1633
1634 for (int idt = i0 - Mode::NQSYMBOL; idt <= i0 + Mode::NQSYMBOL; ++idt) {
1635 float const candidateSync = syncjs8d(idt, 0.0f);
1636 if (candidateSync > smax) {
1637 smax = candidateSync;
1638 ibest = idt;
1639 }
1640 }
1641
1642 // Improved estimate for DT.
1643
1644 float const xdt2 = ibest * DT2;
1645
1646 i0 = static_cast<int>(std::round(xdt2 * FS2));
1647 smax = 0.0f;
1648
1649 for (int ifr = -NFSRCH; ifr <= NFSRCH; ++ifr) {
1650 float const delf = ifr * 0.5f;
1651 float const candidateSync = syncjs8d(i0, delf);
1652
1653 if (candidateSync > smax) {
1654 smax = candidateSync;
1655 delfbest = delf;
1656 }
1657 }
1658
1659 // Frequency tweaking.
1660
1661 float const dphi = -delfbest * ((2.0f * std::numbers::pi_v<float>) /
1662 FS2); // Phase increment
1663 std::complex<float> const wstep =
1664 std::polar(1.0f, dphi); // Step for phase rotation
1665 std::complex<float> w = {1.0f, 0.0f}; // Cumlative phase
1666
1667 for (int i = 0; i < NP2; ++i) {
1668 w *= wstep; // Update cumulative phase
1669 cd0[i] *= w; // Apply phase shift
1670 }
1671
1672 // Adjust the frequency and time offset.
1673
1674 xdt = xdt2;
1675 f1 += delfbest;
1676
1677 float const sync = syncjs8d(i0, 0.0f);
1678
1679 std::array<std::array<float, NN>, NROWS> s2;
1680 // Scaled complex tone bins kept alongside the magnitude matrix so the
1681 // coherent likelihood path can use phases. `s2` is still populated
1682 // exactly as before; `abs(complexS2)` reproduces it up to fp rounding.
1683 std::array<std::array<std::complex<float>, NN>, NROWS> complexS2;
1684 // Per-symbol phase metadata for tracker normalization: nominal
1685 // (pre-tracker-shift) start, effective extraction displacement, and
1686 // the FrequencyTracker estimate applied to that symbol.
1687 std::array<int, NN> symbolBaseStarts;
1688 std::array<int, NN> symbolTimingShifts;
1689 std::array<float, NN> symbolTrackerHz;
1690
1691 js8::FrequencyTracker freqTracker;
1692 if (m_enableFreqTracking) {
1693 freqTracker.reset(0.0, FS2);
1694 } else {
1695 freqTracker.disable();
1696 }
1697
1698 // Scale timing clamp relative to samples per symbol so short-symbol
1699 // modes aren't allowed outsized shifts (e.g., 12-sample JS8 40 formerly "Turbo").
1700 double const timingMaxShift =
1701 std::clamp(0.08 * static_cast<double>(Mode::NDOWNSPS), 0.5, 2.0);
1702
1703 js8::TimingTracker timingTracker;
1704 if (m_enableTimingTracking) {
1705 timingTracker.reset(0.0, 0.15, 0.35, timingMaxShift);
1706 } else {
1707 timingTracker.disable();
1708 }
1709
1710 auto const estimateResidualHz =
1711 [&](int expectedTone) -> std::optional<float> {
1712 if (!freqTracker.enabled())
1713 return std::nullopt;
1714
1715 if (expectedTone < 0 || expectedTone + 1 >= Mode::NDOWNSPS)
1716 return std::nullopt;
1717
1718 float const m0 = std::norm(csymb[expectedTone]);
1719 float const mplus = std::norm(csymb[expectedTone + 1]);
1720 float const mminus =
1721 expectedTone > 0 ? std::norm(csymb[expectedTone - 1]) : 0.0f;
1722
1723 if (m0 <= 0.0f)
1724 return std::nullopt;
1725
1726 float const ratio = m0 / (mplus + mminus + 1e-12f);
1727 if (ratio < 1.5f)
1728 return std::nullopt;
1729
1730 float const denom = mminus - 2.0f * m0 + mplus;
1731 if (std::abs(denom) < 1e-9f)
1732 return std::nullopt;
1733
1734 float delta = 0.5f * (mminus - mplus) / denom;
1735 delta = std::clamp(delta, -0.5f, 0.5f);
1736
1737 return delta * (FS2 / Mode::NDOWNSPS);
1738 };
1739
1740 auto const logTracker = [&](char const *tag) {
1741 if (decoder_js8().isDebugEnabled()) {
1742 if (freqTracker.enabled()) {
1743 qCDebug(decoder_js8)
1744 << "freqTracker" << tag << "coarseHz" << coarseStartHz
1745 << "fineHz" << f1 << "refinedHz"
1746 << f1 + static_cast<float>(freqTracker.currentHz())
1747 << "avgStepHz"
1748 << static_cast<float>(freqTracker.averageStepHz());
1749 }
1750
1751 if (timingTracker.enabled()) {
1752 qCDebug(decoder_js8)
1753 << "timingTracker" << tag << "coarseDt" << coarseStartDt
1754 << "fineDt" << xdt << "refinedDt"
1755 << xdt + static_cast<float>(
1756 timingTracker.currentSamples() * DT2)
1757 << "avgStepSmpl"
1758 << static_cast<float>(
1759 timingTracker.averageStepSamples());
1760 }
1761 }
1762 };
1763
1764 auto const goertzelEnergy =
1765 [&](int start, int expectedTone) -> std::optional<float> {
1766 if (start < 0 || start + Mode::NDOWNSPS > NP2)
1767 return std::nullopt;
1768
1769 std::array<std::complex<float>, Mode::NDOWNSPS> tmp;
1770 std::copy(cd0.begin() + start, cd0.begin() + start + Mode::NDOWNSPS,
1771 tmp.begin());
1772
1773 if (freqTracker.enabled()) {
1774 freqTracker.apply(tmp.data(), Mode::NDOWNSPS);
1775 }
1776
1777 auto const wstep = std::polar(
1778 1.0f, static_cast<float>(-TAU * expectedTone / Mode::NDOWNSPS));
1779 auto phase = std::complex<float>{1.0f, 0.0f};
1780 std::complex<float> acc{0.0f, 0.0f};
1781
1782 for (auto const &sample : tmp) {
1783 acc += sample * std::conj(phase);
1784 phase *= wstep;
1785 }
1786
1787 return std::norm(acc);
1788 };
1789
1790#ifdef JS8_CPU_BENCHMARK
1791 {
1792 BenchmarkScope benchmarkScope{benchmarkDemodCalls,
1793 benchmarkDemodNanos};
1794#endif
1795 for (int k = 0; k < NN; ++k) {
1796 // Calculate the starting index for the current symbol.
1797
1798 int const i1Base = ibest + k * Mode::NDOWNSPS;
1799 int const timingShift = timingTracker.enabled()
1800 ? static_cast<int>(std::round(
1801 timingTracker.currentSamples()))
1802 : 0;
1803 int i1 = i1Base + timingShift;
1804
1805 if (i1 < 0) {
1806 i1 = 0;
1807 } else if (i1 + Mode::NDOWNSPS > NP2) {
1808 i1 = NP2 - Mode::NDOWNSPS;
1809 }
1810
1811 csymb.fill(ZERO);
1812
1813 if (i1 >= 0 && i1 + Mode::NDOWNSPS <= NP2) {
1814 std::copy(cd0.begin() + i1, cd0.begin() + i1 + Mode::NDOWNSPS,
1815 csymb.begin());
1816
1817 if (freqTracker.enabled()) {
1818 freqTracker.apply(csymb.data(), Mode::NDOWNSPS);
1819 }
1820 }
1821
1822 fftwf_execute(plans[Plan::CS]);
1823
1824 // Normalize and take the magnitude of the first 8 points.
1825
1826 for (int i = 0; i < NROWS; ++i) {
1827 s2[i][k] = std::abs(csymb[i]) / 1000.0f;
1828 }
1829
1830 if (m_enableCoherentData) {
1831 for (int i = 0; i < NROWS; ++i)
1832 complexS2[i][k] = csymb[i] / 1000.0f;
1833 }
1834 symbolBaseStarts[k] = i1Base;
1835 symbolTimingShifts[k] = i1 - i1Base;
1836 symbolTrackerHz[k] = freqTracker.enabled()
1837 ? static_cast<float>(freqTracker.currentHz())
1838 : 0.0f;
1839
1840 if (freqTracker.enabled() || timingTracker.enabled()) {
1841 bool const isPilot =
1842 (k < 7) || (k >= 36 && k < 43) || (k >= 72 && k < 79);
1843
1844 if (isPilot) {
1845 int costasBlock = 0;
1846 int costasColumn = k;
1847
1848 if (k >= 36 && k < 43) {
1849 costasBlock = 1;
1850 costasColumn = k - 36;
1851 } else if (k >= 72 && k < 79) {
1852 costasBlock = 2;
1853 costasColumn = k - 72;
1854 }
1855
1856 int const expectedTone = Costas[costasBlock][costasColumn];
1857
1858 if (auto const residual =
1859 estimateResidualHz(expectedTone)) {
1860 freqTracker.update(*residual);
1861 }
1862
1863 if (timingTracker.enabled()) {
1864 auto const e0 = goertzelEnergy(i1, expectedTone);
1865 auto const eEarly =
1866 goertzelEnergy(i1 - 1, expectedTone);
1867 auto const eLate = goertzelEnergy(i1 + 1, expectedTone);
1868
1869 float const toneMag = s2[expectedTone][k];
1870
1871 if (e0 && eEarly && eLate && toneMag > 1e-6f) {
1872 float const denom = *e0 + 1e-6f;
1873 float const grad = (*eLate - *eEarly) / denom;
1874
1875 // Smaller steps; favor stability.
1876 double const weight = std::clamp(
1877 static_cast<double>(toneMag / 5.0f), 0.0, 1.0);
1878 double const errorSamples = std::clamp(
1879 0.25 * static_cast<double>(grad), -1.0, 1.0);
1880
1881 timingTracker.update(errorSamples, weight);
1882 }
1883 }
1884 }
1885 }
1886 }
1887#ifdef JS8_CPU_BENCHMARK
1888 }
1889#endif
1890
1891 // Normal candidates use master's pilot gate; optional deep candidates
1892 // can also qualify on soft pilot power.
1893
1894 int nsync = 0;
1895 double expectedPower = 0.0;
1896 double alternativePower = 0.0;
1897
1898 for (std::size_t costas = 0; costas < Costas.size(); ++costas) {
1899 auto const offset = costas * 36;
1900
1901 for (std::size_t column = 0; column < 7; ++column) {
1902 auto const symbolIndex = offset + column;
1903 int const expectedTone = Costas[costas][column];
1904
1905 auto const max_row = std::distance(
1906 s2.begin(),
1907 std::max_element(s2.begin(), s2.end(),
1908 [symbolIndex](auto const &rowA,
1909 auto const &rowB) {
1910 return rowA[symbolIndex] <
1911 rowB[symbolIndex];
1912 }));
1913
1914 if (expectedTone == max_row)
1915 ++nsync;
1916
1917 for (int tone = 0; tone < NROWS; ++tone) {
1918 double const magnitude = s2[tone][symbolIndex];
1919 double const power = magnitude * magnitude;
1920
1921 if (tone == expectedTone)
1922 expectedPower += power;
1923 else
1924 alternativePower += power;
1925 }
1926 }
1927 }
1928
1929 float const softCostas = static_cast<float>(
1930 expectedPower / (alternativePower / 7.0 + 1e-12));
1931
1932 if (decoder_js8().isDebugEnabled()) {
1933 qCDebug(decoder_js8)
1934 << "symbol sync" << sync << "residualHz" << delfbest
1935 << "nsync" << nsync << "softCostas" << softCostas;
1936 }
1937
1938 if (nsync <= 6 &&
1939 (!optionalCandidate || !std::isfinite(softCostas) ||
1940 softCostas < SOFT_COSTAS_MIN)) {
1941 logTracker("sync_fail");
1942 return std::nullopt;
1943 }
1944
1945 // A deep candidate is optional. Check before touching the combiner or
1946 // starting its full BP sequence, so a pending frame cannot inherit
1947 // partial evidence from an abandoned attempt.
1948 if (optionalCandidate && optional && optional->stop())
1949 return std::nullopt;
1950
1951 if (syncStats)
1952 emitEvent(
1953 JS8::Event::SyncState{JS8::Event::SyncState::Type::CANDIDATE,
1954 Mode::NSUBMODE,
1955 f1,
1956 xdt,
1957 {.candidate = nsync}});
1958
1959 // Shared tone-bin to LLR stack (magnitudes -> winners -> Costas-only
1960 // coherent blend -> whitening -> LLRs -> erasure). The first pass and
1961 // the decoder-aided re-demodulation use this same implementation.
1962 ToneBinLlrs const toneBins = processToneBins(
1963 s2, complexS2, symbolBaseStarts, symbolTimingShifts,
1964 symbolTrackerHz);
1965 auto llr0 = toneBins.llr0;
1966 auto llr1 = toneBins.llr1;
1967
1968 auto const ttl = std::chrono::seconds{Mode::NTXDUR * 2};
1969
1970 m_softCombiner.flush(ttl);
1971
1972 auto const key =
1973 m_softCombiner.makeKey(Mode::NSUBMODE, f1, xdt, llr0, llr1);
1974 auto combined = m_softCombiner.combine(key, llr0, llr1, ttl);
1975
1976 auto llr0Combined = combined.llr0;
1977 auto llr1Combined = combined.llr1;
1978
1979 std::array<int8_t, K> decoded = {};
1980 std::array<int8_t, N> cw = {};
1981 std::array<float, N> bestRescueLlr = {};
1982 // Best tentative hard codeword across LDPC/rescue attempts, kept in
1983 // lockstep with bestRescueChecks so decoder-aided re-demodulation can
1984 // use the actual near-miss word as a waveform hypothesis.
1985 std::array<int8_t, N> bestRescueCw = {};
1986
1987 int totalLdpcPasses = 0;
1988 bool usedFeedbackPass = false;
1989 bool feedbackTurnedSuccess = false;
1990 int feedbackConfident = 0;
1991 int feedbackUncertain = 0;
1992 int bestRescueChecks = M + 1;
1993 int bestRescuePass = 0;
1994 bool rescueAttempted = false;
1995
1996#ifndef JS8_BENCHMARK_DISABLE_BP_CACHE
1997 // Reuse BP only when the fallback input matches a first-pass snapshot.
1998 struct BPSnapshot {
1999 std::array<float, N> input{};
2000 BPOptions options{};
2001 BPResult result{};
2002 std::array<int8_t, N> word{};
2003 std::array<int8_t, K> decoded{};
2004 };
2005 std::array<BPSnapshot, 2> firstPassBP{};
2006 int cachedBP = 0;
2007#endif
2008
2009 auto const rememberRescueInput =
2010 [&](std::array<float, N> const &llrInput, int ipass,
2011 BPResult const &bp) {
2012 if (bp.bestChecks < bestRescueChecks) {
2013 bestRescueChecks = bp.bestChecks;
2014 bestRescuePass = ipass;
2015 bestRescueLlr = llrInput;
2016 // The tentative word is the minimum-syndrome word reported
2017 // by this call (first minimum wins ties
2018 // deterministically), independent of the normal `cw`
2019 // output semantics.
2020 if (bp.bestCwValid)
2021 bestRescueCw = bp.bestCw;
2022 }
2023 };
2024
2025 // Explicit synchronization context for finalizing a successful
2026 // decode. Normal call sites omit it and finalize with the existing
2027 // f1/xdt2 exactly as before; the aided pass supplies its refined
2028 // physical estimate so reporting and SIC subtraction use the sync
2029 // that actually produced the success. Never mutated to trick the
2030 // path: failure behavior is identical with or without it.
2031 struct FinalizeSync {
2032 float frequencyHz;
2033 float xdtSeconds;
2034 };
2035
2036 auto const tryDecode = [&](std::array<float, N> const &llrInput,
2037 int ipass, BPOptions const options,
2038 bool const rememberForRescue,
2039 BPResult *bpOut = nullptr,
2040 std::optional<FinalizeSync> const
2041 &finalize = std::nullopt)
2042 -> std::optional<Decode> {
2043 BPResult bp;
2044 std::array<int8_t, N> savedCw{};
2045 std::array<int8_t, K> savedDecoded{};
2046 if (options.shouldCancel) {
2047 savedCw = cw;
2048 savedDecoded = decoded;
2049 }
2050#ifndef JS8_BENCHMARK_DISABLE_BP_CACHE
2051 bool reused = false;
2052 if (ipass == 2 && rememberForRescue &&
2053 std::isfinite(options.llrScale)) {
2054 for (int slot = 0; slot < cachedBP; ++slot) {
2055 auto const &saved = firstPassBP[slot];
2056 if (options.maxIterations == saved.options.maxIterations &&
2057 options.earlyAbort == saved.options.earlyAbort &&
2058 options.llrScale == saved.options.llrScale &&
2059 std::memcmp(llrInput.data(), saved.input.data(),
2060 sizeof(float) * N) == 0) {
2061 bp = saved.result;
2062 cw = saved.word; // last iterate on a failed BP pass
2063 if (bp.hardErrors >= 0)
2064 decoded = saved.decoded;
2065 reused = true;
2066 break;
2067 }
2068 }
2069 }
2070 if (!reused) {
2071#endif
2072 bp = bpdecode174(llrInput, decoded, cw, options);
2073#ifndef JS8_BENCHMARK_DISABLE_BP_CACHE
2074 if (ipass == 1 && rememberForRescue && cachedBP < 2 &&
2075 std::isfinite(options.llrScale) &&
2076 std::all_of(llrInput.begin(), llrInput.end(),
2077 [](float v) { return std::isfinite(v); })) {
2078 firstPassBP[cachedBP++] =
2079 {llrInput, options, bp, cw, decoded};
2080 }
2081 }
2082#endif
2083 if (bp.cancelled) {
2084 cw = savedCw;
2085 decoded = savedDecoded;
2086 if (bpOut)
2087 *bpOut = bp;
2088 return std::nullopt;
2089 }
2090 if (bpOut != nullptr)
2091 *bpOut = bp;
2092 nharderrors = bp.hardErrors;
2093 xsnr = -99.0f;
2094
2095 if (rememberForRescue)
2096 rememberRescueInput(llrInput, ipass, bp);
2097
2098 if (std::all_of(cw.begin(), cw.end(),
2099 [](int x) { return x == 0; })) {
2100 return std::nullopt;
2101 }
2102
2103 if (nharderrors >= 0 && nharderrors < 60 &&
2104 !(sync < 2.0f && nharderrors > 35) &&
2105 !(ipass > 2 && nharderrors > 39) &&
2106 !(ipass == 4 && nharderrors > 30)) {
2107 if (checkCRC12(decoded)) {
2108 // Success-only sync: normal decodes use f1/xdt2 exactly
2109 // as before; aided decodes use the supplied refined
2110 // estimate for both reporting and SIC seeding.
2111 FinalizeSync const fs =
2112 finalize.value_or(FinalizeSync{f1, xdt2});
2113 if (syncStats)
2114 emitEvent(JS8::Event::SyncState{
2115 JS8::Event::SyncState::Type::DECODED,
2116 Mode::NSUBMODE,
2117 fs.frequencyHz,
2118 fs.xdtSeconds,
2119 {.decoded = sync}});
2120
2121 auto message = extractmessage174(decoded);
2122
2123 int const i3bit =
2124 (decoded[72] << 2) | (decoded[73] << 1) | decoded[74];
2125
2126 std::array<int, NN> itone;
2127
2128 JS8::encode(i3bit, Costas, message.data(), itone.data());
2129
2130 if (lsubtract)
2131 subtractjs8(genjs8refsig(itone, fs.frequencyHz),
2132 fs.xdtSeconds);
2133
2134 float xsig = 0.0f;
2135
2136 for (std::size_t i = 0; i < itone.size(); ++i)
2137 xsig += std::pow(s2[itone[i]][i], 2);
2138
2139 xsnr =
2140 std::max(10.0f * std::log10(std::max(
2141 xsig / xbase - 1.0f, 1.259e-10f)) -
2142 32.0f,
2143 -60.0f); // XXX was -28.0f in Fortran
2144
2145 m_softCombiner.markDecoded(combined.key);
2146
2147 logTracker("decoded");
2148 return std::make_optional<Decode>(i3bit, message);
2149 }
2150 } else {
2151 nharderrors = -1;
2152 }
2153
2154 return std::nullopt;
2155 };
2156
2157 // Run the existing decode and feedback sequence first. Failed BP runs
2158 // leave cw at the last-iteration state; the existing feedback pass
2159 // uses that word with no extra CPU cost.
2160 for (int ipass = 1; ipass <= 4 && totalLdpcPasses < m_maxLdpcPasses;
2161 ++ipass) {
2162 auto &llr = ipass == 2 ? llr1Combined : llr0Combined;
2163
2164 if (ipass == 3)
2165 std::fill(llr0Combined.begin(), llr0Combined.begin() + 24,
2166 0.0f);
2167 else if (ipass == 4)
2168 std::fill(llr0Combined.begin() + 24, llr0Combined.begin() + 48,
2169 0.0f);
2170
2171 std::array<float, N> llrPrimary = llr;
2172 if (auto result =
2173 tryDecode(llrPrimary, ipass, BPOptions{}, true)) {
2174 ++totalLdpcPasses;
2175 return result;
2176 }
2177 ++totalLdpcPasses;
2178
2179 if (m_enableLdpcFeedback && totalLdpcPasses < m_maxLdpcPasses) {
2180 std::array<float, N> llrRefined;
2181 int confident = 0;
2182 int uncertain = 0;
2184 llrPrimary, cw, m_llrErasureThreshold, llrRefined,
2185 confident, uncertain);
2186
2187 if (decoder_js8().isDebugEnabled()) {
2188 qCDebug(decoder_js8)
2189 << "LDPC feedback pass"
2190 << "ipass" << ipass << "confident" << confident
2191 << "uncertain" << uncertain;
2192 }
2193
2194 usedFeedbackPass = true;
2195 feedbackConfident += confident;
2196 feedbackUncertain += uncertain;
2197
2198 if (auto result =
2199 tryDecode(llrRefined, ipass, BPOptions{}, true)) {
2200 ++totalLdpcPasses;
2201 feedbackTurnedSuccess = true;
2202 if (decoder_js8().isDebugEnabled()) {
2203 qCDebug(decoder_js8)
2204 << "LDPC feedback succeeded on second pass"
2205 << "ipass" << ipass << "confident"
2206 << feedbackConfident << "uncertain"
2207 << feedbackUncertain << "passes" << totalLdpcPasses;
2208 }
2209 return result;
2210 }
2211
2212 ++totalLdpcPasses;
2213 }
2214 }
2215
2216 // Spend the bounded rescue budget only on a genuinely close near miss.
2217 // We retry the single best LLR variant with a longer BP run, no early
2218 // abort, and three modest LLR temperatures to escape trapping states.
2219 bool const rescueEligible = m_enableLdpcRescue && ldpcRescueBudget > 0 &&
2220 bestRescuePass > 0 &&
2221 bestRescueChecks <= BP_RESCUE_MAX_CHECKS;
2222 bool const rescueAllowed =
2223 rescueEligible &&
2224 (!optional || optional->allow(js8::OptionalStage::Rescue));
2225 if (rescueEligible && !rescueAllowed)
2226 qCDebug(decoder_js8) << "adaptive optional skip rescue";
2227 if (rescueAllowed) {
2228 auto const rescueStarted = js8::OptionalWorkBudget::Clock::now();
2229 --ldpcRescueBudget;
2230 rescueAttempted = true;
2231 std::function<bool()> const cancelRescue = [optional] {
2232 return optional && optional->stop();
2233 };
2234
2235 if (decoder_js8().isDebugEnabled()) {
2236 qCDebug(decoder_js8)
2237 << "LDPC rescue start"
2238 << "bestChecks" << bestRescueChecks
2239 << "ipass" << bestRescuePass
2240 << "budgetRemaining" << ldpcRescueBudget;
2241 }
2242
2243 for (float const scale : BP_RESCUE_LLR_SCALES) {
2244 if (optional && optional->stop())
2245 break;
2246 BPOptions options;
2247 options.maxIterations = BP_RESCUE_ITERATIONS;
2248 options.earlyAbort = false;
2249 options.llrScale = scale;
2250 options.shouldCancel = optional ? &cancelRescue : nullptr;
2251 BPResult rescueBp;
2252
2253 // Remember rescue attempts as well so bestRescueChecks (and the
2254 // associated bestRescueCw snapshot) reflect the best syndrome
2255 // across all bounded LDPC/rescue attempts. This only updates
2256 // the best-input bookkeeping with the same LLRs; no decode
2257 // behavior changes.
2258 if (auto result = tryDecode(bestRescueLlr, bestRescuePass,
2259 options, true, &rescueBp)) {
2260 if (optional)
2261 optional->observe(js8::OptionalStage::Rescue,
2262 rescueStarted);
2263 if (decoder_js8().isDebugEnabled()) {
2264 qCDebug(decoder_js8)
2265 << "LDPC rescue succeeded"
2266 << "scale" << scale
2267 << "bestChecks" << bestRescueChecks;
2268 }
2269 return result;
2270 }
2271 if (rescueBp.cancelled)
2272 break;
2273 }
2274 if (optional)
2275 optional->observe(js8::OptionalStage::Rescue, rescueStarted);
2276 }
2277
2278 // Decoder-aided re-demodulation. When the normal bounded LDPC/rescue
2279 // sequence fails with a genuinely close near miss (best syndrome in
2280 // (0, 4]), the best tentative codeword becomes a waveform hypothesis:
2281 // its 58 data tones plus the 21 known Costas tones refine
2282 // timing/residual-frequency/drift relative to the ACTUAL first-pass
2283 // tracked extraction (recorded starts plus tracker corrections) using
2284 // this candidate's received samples (cd0, i.e. the current SIC-pass
2285 // buffer after coarse correction), and the refined sync drives ONE
2286 // fresh 8-tone re-demodulation producing new LLRs for a final LDPC
2287 // attempt. Extended rescue scales obey the existing rescue enable and
2288 // budget (one unit per aided group). Only a valid CRC can accept the
2289 // result; any failure falls through to the normal failure path with
2290 // the original outputs restored.
2291 bool const aidedEligible = m_enableAidedRedemod &&
2292 bestRescueChecks > 0 &&
2293 bestRescueChecks <=
2295 bool const aidedAllowed =
2296 aidedEligible &&
2297 (!optional || optional->allow(js8::OptionalStage::Aided));
2298 if (aidedEligible && !aidedAllowed)
2299 qCDebug(decoder_js8) << "adaptive optional skip aided";
2300 if (aidedAllowed) {
2301 auto const aidedStarted = js8::OptionalWorkBudget::Clock::now();
2302 static_assert(js8::aided::kCodeBits == N &&
2305 js8::aided::kTones == NROWS,
2306 "aided helper sizes must match decoder");
2307
2308 // Tentative-word validity: an all-zero word carries no tone
2309 // information, and non-finite LLRs must never steer the fit.
2310 bool tentValid =
2311 !std::all_of(bestRescueCw.begin(), bestRescueCw.end(),
2312 [](int8_t x) { return x == 0; });
2313 for (float v : bestRescueLlr)
2314 tentValid = tentValid && std::isfinite(v);
2315
2316 // Recorded first-pass extraction per symbol: nominal base plus the
2317 // TimingTracker integer shift actually applied, with the
2318 // FrequencyTracker estimate applied to that symbol. The
2319 // refinement baseline replays this tracked extraction exactly;
2320 // search hypotheses refine relative to it.
2321 std::array<js8::aided::SymbolBaseline, NN> aidedBaselines{};
2322 for (int k = 0; k < NN; ++k) {
2323 aidedBaselines[static_cast<std::size_t>(k)].startSamples =
2324 symbolBaseStarts[static_cast<std::size_t>(k)] +
2325 symbolTimingShifts[static_cast<std::size_t>(k)];
2326 aidedBaselines[static_cast<std::size_t>(k)].trackerHz =
2327 symbolTrackerHz[static_cast<std::size_t>(k)];
2328 }
2329
2330 bool const boundsOk =
2331 tentValid && js8::aided::symbolBoundsValid(
2332 aidedBaselines, Mode::NDOWNSPS, NP2,
2333 js8::aided::kTimingDeltaMax);
2334 // Gate reason for telemetry: 0 = searched, 1 = tentative
2335 // word/LLRs unusable, 2 = candidate sample bounds invalid.
2336 int const skipCode =
2337 !tentValid ? 1 : (!boundsOk ? 2 : 0);
2338
2339 std::optional<Decode> aidedResult;
2340 int aidedUsed = 0;
2341 double aidedMeanConf = 0.0;
2342 int aidedDt = 0;
2343 double aidedDf = 0.0;
2344 double aidedDd = 0.0;
2345 double aidedBase =
2346 std::numeric_limits<double>::quiet_NaN();
2347 double aidedRef = std::numeric_limits<double>::quiet_NaN();
2348 int aidedBoundary = 0;
2349 int aidedBestChecks = -1;
2350 int aidedAccepted = 0;
2351 double aidedFinalizeF1 =
2352 std::numeric_limits<double>::quiet_NaN();
2353 double aidedFinalizeXdt =
2354 std::numeric_limits<double>::quiet_NaN();
2355 double aidedPhysResidual =
2356 std::numeric_limits<double>::quiet_NaN();
2357 double aidedMidTime = std::numeric_limits<double>::quiet_NaN();
2358 double aidedTrackerMid =
2359 std::numeric_limits<double>::quiet_NaN();
2360 std::optional<FinalizeSync> aidedFinalizeSync;
2361 int aidedScales = 0;
2362 int const aidedBudgetBefore = ldpcRescueBudget;
2363 int aidedBudgetAfter = ldpcRescueBudget;
2364 double const initLlrNorm = js8::aided::llrNorm(bestRescueLlr);
2365 double aidedLlrNorm = 0.0;
2366
2367 if (boundsOk) {
2368 std::array<int, NN> expectedTones{};
2369 js8::aided::codewordToTones(bestRescueCw, Costas,
2370 expectedTones);
2371 auto const conf =
2372 js8::aided::tentativeConfidences(bestRescueLlr);
2373 std::array<float, NN> symWeights{};
2374 js8::aided::buildSymbolWeights(conf, symWeights);
2375 aidedUsed = conf.used;
2376 aidedMeanConf = conf.mean;
2377
2378#ifdef JS8_CPU_BENCHMARK
2379 auto const refinementStarted =
2380 std::chrono::steady_clock::now();
2381#endif
2382 js8::aided::Refinement const refinement =
2384 cd0.data(), NP2, aidedBaselines, Mode::NDOWNSPS,
2385 static_cast<double>(FS2), expectedTones, symWeights,
2386 [optional] { return optional && optional->stop(); });
2387#ifdef JS8_CPU_BENCHMARK
2388 ++benchmarkRefineCalls;
2389 benchmarkRefineNanos +=
2390 std::chrono::duration_cast<std::chrono::nanoseconds>(
2391 std::chrono::steady_clock::now() - refinementStarted)
2392 .count();
2393#endif
2394 aidedBase = refinement.baselineMetric;
2395 aidedRef = refinement.best.metric;
2396 aidedBoundary = refinement.atBoundary ? 1 : 0;
2397 // Report the best hypothesis found regardless of the gate so
2398 // telemetry shows what the search preferred; the gate outcome
2399 // is conveyed by atBoundary/gainDb/aidedBestChecks.
2400 aidedDt = refinement.best.deltaSamples;
2401 aidedDf = refinement.best.deltaHz;
2402 aidedDd = refinement.best.driftHzPerSec;
2403
2404 if (js8::aided::refinementAccepted(refinement) &&
2405 (!optional || !optional->stop())) {
2406
2407 // Fresh full 79-symbol re-demodulation from cd0: recorded
2408 // first-pass start plus the refined timing delta, exact
2409 // replay of the recorded tracker correction, then the
2410 // refined residual derotation phase(t) = 2*pi*df*t +
2411 // pi*dd*t^2 (negative-exponent convention matches the
2412 // coarse cd0 correction), then the same in-place FFT and
2413 // magnitude scaling as the first pass. The Costas-only
2414 // coherent fit downstream absorbs small leftovers; the
2415 // recorded trackerHz metadata is passed through unchanged
2416 // so its model stays consistent with the first pass.
2417 std::array<std::array<float, NN>, NROWS> s2Aided{};
2418 std::array<std::array<std::complex<float>, NN>, NROWS>
2419 complexAided{};
2420 std::array<int, NN> baseStartsAided{};
2421 std::array<int, NN> shiftsAided{};
2422 std::array<float, NN> trackerHzAided{};
2423 double const rateHz = static_cast<double>(FS2);
2424 for (int k = 0; k < NN; ++k) {
2425 std::size_t const kk = static_cast<std::size_t>(k);
2426 int const firstStart =
2427 aidedBaselines[kk].startSamples;
2428 int i1 = firstStart + aidedDt;
2429 if (i1 < 0) {
2430 i1 = 0;
2431 } else if (i1 + Mode::NDOWNSPS > NP2) {
2432 i1 = NP2 - Mode::NDOWNSPS;
2433 }
2434 baseStartsAided[kk] = symbolBaseStarts[kk];
2435 shiftsAided[kk] = i1 - symbolBaseStarts[kk];
2436 trackerHzAided[kk] = symbolTrackerHz[kk];
2437 for (int n = 0; n < Mode::NDOWNSPS; ++n)
2438 csymb[static_cast<std::size_t>(n)] =
2439 cd0[static_cast<std::size_t>(i1 + n)];
2440 if (!js8::aided::replayTrackerCorrection(
2441 csymb.data(), Mode::NDOWNSPS,
2442 aidedBaselines[kk].trackerHz, rateHz)) {
2443 // Corrupt window: zero-fill so downstream
2444 // finite/magnitude guards handle it
2445 // deterministically.
2446 csymb.fill(ZERO);
2447 }
2448 for (int n = 0; n < Mode::NDOWNSPS; ++n) {
2449 double const t =
2450 static_cast<double>(i1 + n) / rateHz;
2451 double const angle =
2452 2.0 * std::numbers::pi * aidedDf * t +
2453 std::numbers::pi * aidedDd * t * t;
2454 float const ang = static_cast<float>(angle);
2455 csymb[static_cast<std::size_t>(n)] *=
2456 std::polar(1.0f, -ang);
2457 }
2458
2459 fftwf_execute(plans[Plan::CS]);
2460
2461 for (int i = 0; i < NROWS; ++i) {
2462 s2Aided[static_cast<std::size_t>(i)]
2463 [static_cast<std::size_t>(k)] =
2464 std::abs(csymb[static_cast<std::size_t>(
2465 i)]) /
2466 1000.0f;
2467 complexAided[static_cast<std::size_t>(i)]
2468 [static_cast<std::size_t>(k)] =
2469 csymb[static_cast<std::size_t>(
2470 i)] /
2471 1000.0f;
2472 }
2473 }
2474
2475 // Identical downstream stack as the first pass (shared
2476 // helper): Costas-pilots-only coherent fit, whitening,
2477 // LLRs. Tentative data never enters the coherent fit.
2478 ToneBinLlrs const aidedBins = processToneBins(
2479 s2Aided, complexAided, baseStartsAided, shiftsAided,
2480 trackerHzAided);
2481 aidedLlrNorm = js8::aided::llrNorm(aidedBins.llr0);
2482
2483 // Final physical sync if this attempt succeeds: the
2484 // scalar timing seed moves with the global aided delta;
2485 // the scalar frequency seed is f1 plus the Costas-only
2486 // physical residual at the frame midpoint
2487 // (tracker-aware, drift included via aidedDd*tMid).
2488 // Falls back to the normal sync if degenerate; the same
2489 // context feeds reporting, subtraction seeding, and the
2490 // f1/xdt update below.
2491 {
2492 float const xdtCand = js8::aided::aidedFrameXdt(
2493 xdt2, aidedDt, DT2);
2494 std::array<float, NN> costasW{};
2496 js8::aided::MidpointResidual const mid =
2498 aidedDf, aidedDd, aidedBaselines,
2499 Mode::NDOWNSPS, rateHz, costasW);
2500 float aidedF1 = f1;
2501 float aidedXdtOut = xdt2;
2502 if (std::isfinite(xdtCand) && mid.valid) {
2503 aidedXdtOut = xdtCand;
2504 aidedF1 =
2505 f1 + static_cast<float>(mid.residualHz);
2506 aidedFinalizeF1 = aidedF1;
2507 aidedFinalizeXdt = aidedXdtOut;
2508 aidedPhysResidual = mid.residualHz;
2509 aidedMidTime = mid.midpointSeconds;
2510 aidedTrackerMid = mid.trackerHzAtMid;
2511 }
2512 aidedFinalizeSync = FinalizeSync{aidedF1, aidedXdtOut};
2513 }
2514
2515 // The aided LLRs measure the SAME frame, so they must not
2516 // go through SoftCombiner::combine() (that would add one
2517 // frame twice as independent evidence). Run LDPC locally
2518 // on the fresh LLRs; the combiner entry keeps the initial
2519 // observation, and markDecoded() inside tryDecode evicts
2520 // it on success exactly like the normal path.
2521 int const savedNhard = nharderrors;
2522 float const savedXsnr = xsnr;
2523 auto const savedS2 = s2;
2524 s2 = s2Aided; // aided xsnr uses aided magnitudes
2525 int aidedBest = M + 1;
2526 BPResult aidedBp;
2527 std::function<bool()> const cancelAided = [optional] {
2528 return optional && optional->stop();
2529 };
2530 BPOptions aidedOptions;
2531 aidedOptions.shouldCancel = optional ? &cancelAided : nullptr;
2532 if (auto res = tryDecode(aidedBins.llr0, 1, aidedOptions,
2533 false, &aidedBp,
2534 aidedFinalizeSync)) {
2535 aidedBest = aidedBp.bestChecks;
2536 aidedAccepted = 1;
2537 aidedResult = res;
2538 } else if (!aidedBp.cancelled) {
2539 aidedBest = std::min(aidedBest, aidedBp.bestChecks);
2540 // Extended rescue scales stay inside the decoder's
2541 // existing bounded rescue policy: one normal BP is
2542 // always allowed on the fresh LLRs, but the scale
2543 // group runs only with rescue enabled and budget
2544 // remaining, consuming exactly one unit for the whole
2545 // aided group like the normal rescue group.
2546 if (m_enableLdpcRescue && ldpcRescueBudget > 0 &&
2547 (!optional ||
2548 optional->allow(js8::OptionalStage::Rescue))) {
2549 --ldpcRescueBudget;
2550 for (float const scale : BP_RESCUE_LLR_SCALES) {
2551 if (optional && optional->stop())
2552 break;
2553 ++aidedScales;
2554 BPOptions options;
2555 options.maxIterations = BP_RESCUE_ITERATIONS;
2556 options.earlyAbort = false;
2557 options.llrScale = scale;
2558 options.shouldCancel =
2559 optional ? &cancelAided : nullptr;
2560 BPResult retryBp;
2561 if (auto retry =
2562 tryDecode(aidedBins.llr0, 1, options,
2563 false, &retryBp,
2564 aidedFinalizeSync)) {
2565 aidedBest = std::min(aidedBest,
2566 retryBp.bestChecks);
2567 aidedAccepted = 1;
2568 aidedResult = retry;
2569 break;
2570 }
2571 if (retryBp.cancelled)
2572 break;
2573 aidedBest = std::min(aidedBest,
2574 retryBp.bestChecks);
2575 }
2576 }
2577 }
2578 aidedBestChecks = aidedBest <= M ? aidedBest : -1;
2579 aidedBudgetAfter = ldpcRescueBudget;
2580
2581 if (!aidedResult) {
2582 // Failed aided attempts leave no trace: original
2583 // outputs and failure path are preserved.
2584 nharderrors = savedNhard;
2585 xsnr = savedXsnr;
2586 s2 = savedS2;
2587 }
2588 }
2589 }
2590
2591 if (decoder_js8().isDebugEnabled()) {
2592 qCDebug(decoder_js8)
2593 << "Decoder-aided re-demod"
2594 << "initialBestChecks" << bestRescueChecks << "attempted"
2595 << (boundsOk ? 1 : 0) << "skipCode" << skipCode
2596 << "dataUsed" << aidedUsed
2597 << "meanConf" << aidedMeanConf << "dtSmpl" << aidedDt
2598 << "dfHz" << aidedDf << "ddotHz" << aidedDd
2599 << "baseMetric" << aidedBase << "refMetric" << aidedRef
2600 << "gainDb"
2601 << js8::aided::metricGainDb(aidedRef, aidedBase)
2602 << "atBoundary" << aidedBoundary << "aidedBestChecks"
2603 << aidedBestChecks << "crcAccepted" << aidedAccepted
2604 << "aidedScales" << aidedScales << "budgetBefore"
2605 << aidedBudgetBefore << "budgetAfter" << aidedBudgetAfter
2606 << "finalizeF1Hz" << aidedFinalizeF1 << "finalizeXdt"
2607 << aidedFinalizeXdt << "physicalResidualHz"
2608 << aidedPhysResidual << "midpointTime" << aidedMidTime
2609 << "trackerHzMidOrFit" << aidedTrackerMid
2610 << "f1SeedHz" << f1 << "xdt2Seed" << xdt2
2611 << "initLlrNorm" << initLlrNorm << "aidedLlrNorm"
2612 << aidedLlrNorm;
2613 }
2614
2615 if (aidedResult) {
2616 if (optional)
2617 optional->observe(js8::OptionalStage::Aided, aidedStarted);
2618 // The aided sync produced this CRC success: expose it as the
2619 // decode's sync (reporting and SIC seed already used the same
2620 // context inside tryDecode). Only touched after acceptance;
2621 // failures preserve the original f1/xdt exactly.
2622 FinalizeSync const fs = aidedFinalizeSync.value_or(
2623 FinalizeSync{f1, xdt2});
2624 f1 = fs.frequencyHz;
2625 xdt = fs.xdtSeconds;
2626 return aidedResult;
2627 }
2628 if (optional)
2629 optional->observe(js8::OptionalStage::Aided, aidedStarted);
2630 }
2631
2632 if (decoder_js8().isDebugEnabled()) {
2633 qCDebug(decoder_js8)
2634 << "LDPC feedback summary"
2635 << "used" << usedFeedbackPass << "success"
2636 << feedbackTurnedSuccess << "confident" << feedbackConfident
2637 << "uncertain" << feedbackUncertain << "passes"
2638 << totalLdpcPasses << "bestChecks" << bestRescueChecks
2639 << "rescueAttempted" << rescueAttempted;
2640 }
2641
2642 logTracker("fail");
2643 return std::nullopt;
2644 }
2645
2646 // Compute noise baseline. We differ quite a bit from the Fortran
2647 // implementation here.
2648 //
2649 // The Fortran version took `savg` as input; power scaled data from
2650 // `syncjs8`, and produced `sbase`, the noise baseline. To accomplish
2651 // that, it used up to 1000 lower envelope points for the polynomial
2652 // determination, which caused some oddities when the matrix was
2653 // ill-conditioned; we're just looking for a low-order polynomial
2654 // here, and a massively tall matrix isn't in general going to be
2655 // helpful there. Additionally, the methodology seemed to be very
2656 // susceptible to Runge's phenomenon.
2657 //
2658 // This approach instead uses a number of Chebyshev nodes proportional
2659 // to the polynomial degree, and we evaluate 2 kHz of `savg`, centered
2660 // around 1.5 kHz, to determine the polynomial, figuring that that's
2661 // going to be an optimal place to measure the 10% noise floor. We then
2662 // map the [ia, ib] range to the domain of the polynomial to compute
2663 // the baseline. Since `savg` would otherwise no longer be referenced
2664 // beyond this function, we dispense with `sbase` and instead overwrite
2665 // `savg` with the baseline.
2666
2667 void baselinejs8(int const ia, int const ib) {
2668#ifdef JS8_CPU_BENCHMARK
2669 BenchmarkScope benchmarkScope{benchmarkBaselineCalls,
2670 benchmarkBaselineNanos};
2671#endif
2672 // Data referenced in savg is defined by the closed range [bmin, bmax].
2673 // From this we can derive the size of the closed range and the number
2674 // of points in each of the arms on either side of a node. All of these
2675 // values can be computed at compile time.
2676
2677 using boost::math::ccmath::round;
2678
2679 constexpr auto bmin =
2680 static_cast<std::size_t>(round(BASELINE_MIN / Mode::DF));
2681 constexpr auto bmax =
2682 static_cast<std::size_t>(round(BASELINE_MAX / Mode::DF));
2683 constexpr auto size = bmax - bmin + 1;
2684 constexpr auto arm = size / (2 * BASELINE_NODES.size());
2685
2686 // Loop invariants; beginning of the data range, sentinel one past the
2687 // end of the range.
2688
2689 auto const data = savg.begin() + bmin;
2690 auto const end = data + size;
2691
2692 // Convert savg range of interest from power scale to dB scale.
2693
2694 std::transform(data, end, data, [](float const value) {
2695 return 10.0f * std::log10(value);
2696 });
2697
2698 // Collect lower envelope points; use Chebyshev node interpolants
2699 // to reduce Runge's phenomenon oscillations.
2700
2701 for (std::size_t i = 0; i < BASELINE_NODES.size(); ++i) {
2702 auto const node = size * BASELINE_NODES[i];
2703 auto const base = data + static_cast<int>(std::round(node));
2704 auto span = std::vector<float>(std::clamp(base - arm, data, end),
2705 std::clamp(base + arm, data, end));
2706
2707 auto const n = span.size() * BASELINE_SAMPLE / 100;
2708
2709 std::nth_element(span.begin(), span.begin() + n, span.end());
2710
2711 p.row(i) << node, span[n];
2712 }
2713
2714 // Extract x and y values from points and prepare the Vandermonde
2715 // matrix, initializing the first column with 1 (x^0); remaining
2716 // columns are filled with the Schur product.
2717
2718 Eigen::VectorXd x = p.col(0);
2719 Eigen::VectorXd y = p.col(1);
2720
2721 V.col(0).setOnes();
2722 for (Eigen::Index i = 1; i < V.cols(); ++i) {
2723 V.col(i) = V.col(i - 1).cwiseProduct(x);
2724 }
2725
2726 // Solve the least squares problem for polynomial coefficients.
2727
2728 c = V.colPivHouseholderQr().solve(y);
2729
2730 // To map an index i in the range [ia, ib] to the polynomial's
2731 // input domain [0, size - 1]:
2732 //
2733 // i - ia
2734 // x = ------- * (size - 1)
2735 // ib - ia
2736
2737 auto const mapIndex = [ia, ib, last = size - 1](int const i) {
2738 return (i - ia) * last / float(ib - ia);
2739 };
2740
2741 // Replace savg with a computed baseline in the range [ia, ib].
2742 // This might be interpolation, which should be quite accurate,
2743 // or extrapolation, likely somewhat less so the further we get
2744 // from the polynomial fitting domain, but hopefully still good
2745 // enough for our purposes here.
2746
2747 savg.fill(0.0f);
2748
2749 for (int i = ia; i <= ib; ++i) {
2750 savg[i] = evaluate(mapIndex(i)) + 0.65f;
2751 }
2752 }
2753
2754 // Extracted from the downsampling process; this step is part of the
2755 // frequency-domain filtering process for downsampling the JS8 signal.
2756 // After the FFT, the resulting frequency-domain data (ds_cx) can be
2757 // manipulated (e.g., band-pass filtered or shifted). Subsequent inverse
2758 // FFT operations convert the filtered data back into the time domain at
2759 // a lower sample rate, achieving the desired downsampling.
2760
2761 void computeBasebandFFT() {
2762#ifdef JS8_CPU_BENCHMARK
2763 BenchmarkScope benchmarkScope{benchmarkBasebandCalls,
2764 benchmarkBasebandNanos};
2765#endif
2766 // ds_dx is an array of complex<float>; we're going to do an in-place
2767 // FFT, so we'll interpret the first half of the array as if they were
2768 // floats, which they are.
2769
2770 float *fftw_real = reinterpret_cast<float *>(ds_cx.data());
2771
2772 // Copy in data and zero-pad any remainder; not all modes will have
2773 // a remainder.
2774
2775 std::copy(dd.begin(), dd.end(), fftw_real);
2776 std::fill(fftw_real + dd.size(), fftw_real + Mode::NDFFT1, 0.0f);
2777
2778 fftwf_execute(plans[Plan::BB]);
2779 }
2780
2781 // This function extracts a narrow frequency band around the target
2782 // frequency f0, applies tapering to reduce spectral artifacts, aligns the
2783 // signal to the center frequency, performs an inverse FFT to convert the
2784 // data back into the time domain, and normalizes the result for further
2785 // processing in the JS8 decoding pipeline.
2786
2787 void js8_downsample(float const f0) {
2788#ifdef JS8_CPU_BENCHMARK
2789 BenchmarkScope benchmarkScope{benchmarkDownsampleCalls,
2790 benchmarkDownsampleNanos};
2791#endif
2792 // Frequency band extraction; identifies a narrow frequency band around
2793 // the target frequency (f0) based on a predefined range (8.5 baud above
2794 // and 1.5 baud below). The indices of this range in the
2795 // frequency-domain representation (ds_cx) are calculated (ib and it),
2796 // and the relevant frequency-domain samples are extracted into cd0.
2797
2798 constexpr float DF = 12000.0f / Mode::NDFFT1;
2799 constexpr float BAUD = 12000.0f / Mode::NSPS;
2800
2801 float const ft = f0 + 8.5f * BAUD;
2802 float const fb = f0 - 1.5f * BAUD;
2803 int const i0 = static_cast<int>(std::round(f0 / DF));
2804 int const it =
2805 std::min(static_cast<int>(std::round(ft / DF)), Mode::NDFFT1 / 2);
2806 int const ib = std::max(0, static_cast<int>(std::round(fb / DF)));
2807
2808 std::size_t const NDD_SIZE = Mode::NDD + 1;
2809 std::size_t const RANGE_SIZE = it - ib + 1;
2810
2811 std::fill_n(cd0.begin(), Mode::NDFFT2, ZERO);
2812
2813 std::copy(ds_cx.begin() + ib, ds_cx.begin() + ib + RANGE_SIZE,
2814 cd0.begin());
2815
2816 // Tapering is applied to smooth the edges of the frequency band,
2817 // reducing spectral leakage during the inverse FFT. Reversed taper at
2818 // the beginning, normal taper at the end.
2819
2820 auto const head = cd0.begin();
2821 auto const tail = cd0.begin() + RANGE_SIZE;
2822
2823 std::transform(head, head + NDD_SIZE, Taper[0].begin(), head,
2824 std::multiplies<>());
2825 std::transform(tail - NDD_SIZE, tail, Taper[1].begin(), tail - NDD_SIZE,
2826 std::multiplies<>());
2827
2828 // The extracted frequency band is aligned to the center of the
2829 // frequency domain representation (i0 - ib) via a cyclic shift using
2830 // std::rotate. This centers the desired signal.
2831
2832 std::rotate(cd0.begin(), cd0.begin() + (i0 - ib),
2833 cd0.begin() + Mode::NDFFT2);
2834
2835 // An inverse FFT is performed on the frequency-domain data (cd0) to
2836 // transform it back into the time domain, effectively yielding a
2837 // downsampled, time-domain signal focused on the extracted narrow
2838 // frequency band.
2839
2840 fftwf_execute(plans[Plan::DS]);
2841
2842 // The resulting time-domain samples are normalized by a factor derived
2843 // from the input and output FFT sizes (Mode::NDFFT1 and Mode::NDFFT2),
2844 // ensuring consistency in the signal’s amplitude.
2845
2846 float const factor =
2847 1.0f / std::sqrt(static_cast<float>(Mode::NDFFT1) * Mode::NDFFT2);
2848
2849 std::transform(cd0.begin(), cd0.end(), cd0.begin(),
2850 [factor](auto &value) { return value * factor; });
2851 }
2852
2853 // Evaluate the synchronization power of signal segments, ranks potential
2854 // candidates, and extracts the most promising ones for further decoding.
2855 //
2856 // Detailed Steps:
2857 //
2858 // 1. Compute Symbol Spectra:
2859 //
2860 // - The signal is processed in overlapping segments, with each segment
2861 // multiplied by
2862 // a Nuttall window to reduce spectral leakage.
2863 // - An FFT is performed on each windowed segment to obtain the
2864 // frequency-domain
2865 // representation.
2866 // - The power spectrum of each segment is computed, and the average
2867 // spectrum is
2868 // accumulated across segments.
2869 //
2870 // 2. Filter Edge Adjustments:
2871 //
2872 // - Adjusts the frequency bounds (nfa and nfb) to ensure the analysis
2873 // remains
2874 // within valid and meaningful regions of the signal.
2875 //
2876 // 3. Baseline Computation:
2877 //
2878 // - The average spectrum is converted to a dB scale.
2879 // - Baseline is computed to distinguish significant signal components
2880 // from
2881 // background noise.
2882 //
2883 // 4. Synchronization Metric Calculation:
2884 //
2885 // - For each frequency bin in the specified range, evaluates
2886 // synchronization
2887 // power using a Costas waveform.
2888 // - Sync metric is computed over the index range, considering all
2889 // combinations
2890 // of Costas patterns.
2891 // - The maximum sync value and its corresponding offset are recorded
2892 // for each
2893 // frequency bin.
2894 //
2895 // 5. Normalization:
2896 //
2897 // - The sync values are normalized to the 40th percentile value using a
2898 // ranked
2899 // index. This ensures a consistent scaling across different signals
2900 // and noise levels.
2901 //
2902 // 6. Candidate Extraction:
2903 //
2904 // - Candidates with a strong sync metric (above a defined threshold)
2905 // are extracted.
2906 // - Near-duplicate candidates of lesser synchronization power, based on
2907 // frequency
2908 // proximity, are eliminated.
2909 //
2910 // 7. Output:
2911 //
2912 //\t - Returns a vector of the most promising signal candidates, sorted by
2913 // their
2914 // synchronization power. It's expected that these will be re-sorted
2915 // by the caller into a desirable order, but synchronization power
2916 // order facilitates debugging this function.
2917 //
2918 // Note: The Fortran version of this routine would normalize `s` at the end
2919 // of this
2920 // function, but I'm unsure why; nothing beyond this function
2921 // references `s`, so it was effectively a somewhat expensive dead
2922 // store. It's been eliminated in this version.
2923
2924 SyncCandidates syncjs8(int nfa, int nfb) {
2925#ifdef JS8_CPU_BENCHMARK
2926 BenchmarkScope benchmarkScope{benchmarkCandidateGenCalls,
2927 benchmarkCandidateGenNanos};
2928#endif
2929 // Compute symbol spectra
2930
2931 savg.fill(0.0f);
2932
2933#ifdef JS8_CPU_BENCHMARK
2934 {
2935 BenchmarkScope benchmarkScope{benchmarkSpectrumCalls,
2936 benchmarkSpectrumNanos};
2937#endif
2938 for (int j = 0; j < Mode::NHSYM; ++j) {
2939 int const ia = j * Mode::NSTEP;
2940 int const ib = ia + Mode::NFFT1;
2941
2942 if (ib > Mode::NMAX)
2943 break;
2944
2945 std::transform(dd.begin() + ia, dd.begin() + ib, nuttal.begin(),
2946 reinterpret_cast<float *>(sd.data()),
2947 std::multiplies<float>{});
2948
2949 fftwf_execute(plans[Plan::SD]);
2950
2951 // Compute power spectrum
2952
2953 for (int i = 0; i < Mode::NSPS; ++i) {
2954 auto const power = std::norm(sd[i]);
2955 s[i][j] = power;
2956 savg[i] += power;
2957 }
2958 }
2959#ifdef JS8_CPU_BENCHMARK
2960 }
2961#endif
2962
2963 // Filter edge sanity measures
2964
2965 int const nwin = nfb - nfa;
2966
2967 if (nfa < 100) {
2968 nfa = 100;
2969 if (nwin < 100)
2970 nfb = nfa + nwin;
2971 }
2972
2973 if (nfb > 4910) {
2974 nfb = 4910;
2975 if (nwin < 100)
2976 nfa = nfb - nwin;
2977 }
2978
2979 auto const ia =
2980 std::max(0, static_cast<int>(std::round(nfa / Mode::DF)));
2981 auto const ib = static_cast<int>(std::round(nfb / Mode::DF));
2982
2983 // Convert average spectrum from power to db scale and compute
2984 // baseline from it; baseline replaces average spectrum.
2985
2986 baselinejs8(ia, ib);
2987
2988 // Compute and populate the sync index.
2989
2990#ifdef JS8_BENCHMARK_VERIFY_RANK_SCAN
2991 std::uint64_t comparedScores = 0;
2992#endif
2993#ifdef JS8_CPU_BENCHMARK
2994 {
2995 BenchmarkScope benchmarkScope{benchmarkRankScoreCalls,
2996 benchmarkRankScoreNanos};
2997#endif
2998 sync.clear();
2999
3000 for (int i = ia; i <= ib; ++i) {
3001 float max_value = -std::numeric_limits<float>::infinity();
3002 int max_index = -Mode::JZ;
3003
3004#ifdef JS8_BENCHMARK_ORIGINAL_RANK_SCAN
3005 for (int j = -Mode::JZ; j <= Mode::JZ; ++j) {
3006 std::array<std::array<float, 3>, 2> t{};
3007
3008 for (int p = 0; p < 3; ++p) {
3009 for (int n = 0; n < 7; ++n) {
3010 int const offset =
3011 j + Mode::JSTRT + NSSY * n + p * 36 * NSSY;
3012
3013 if (offset >= 0 && offset < Mode::NHSYM) {
3014 // Accumulate Costas pattern contributions.
3015
3016 t[0][p] += s[i + NFOS * Costas[p][n]][offset];
3017
3018 // Accumulate sum over all frequencies for this
3019 // block.
3020
3021 for (int freq = 0; freq < 7; ++freq) {
3022 t[1][p] += s[i + NFOS * freq][offset];
3023 }
3024 }
3025 }
3026 }
3027
3028 // Compute sync metric over the index range. We are at the
3029 // moment maintaining the Fortran summation methodology for
3030 // compatibility testing; there are more efficient ways to do
3031 // this, but IEEE 754 addition is a touchy thing, so we'll need
3032 // to ensure that any changes don't negatively affect result
3033 // precision.
3034
3035 auto const compute_sync = [&t](int start, int end) {
3036 float tx = 0.0f;
3037 float t0 = 0.0f;
3038
3039 for (int i = start; i <= end; ++i) {
3040 tx += t[0][i];
3041 t0 += t[1][i];
3042 }
3043
3044 return tx / ((t0 - tx) / 6.0f);
3045 };
3046
3047 if (auto const sync_value =
3048 std::max({compute_sync(0, 2), compute_sync(0, 1),
3049 compute_sync(1, 2)});
3050 sync_value > max_value) {
3051 max_value = sync_value;
3052 max_index = j;
3053 }
3054 }
3055#else
3056 // Each timing offset has independent accumulators. Visit the
3057 // spectrum by pilot/tone first so adjacent timing samples of a
3058 // frequency row are read together. For EACH timing offset, the
3059 // pilots and seven alternative tones still enter its float sums
3060 // in precisely the original p/n/freq order.
3061 std::array<std::array<std::array<float, 3>, 2>,
3062 2 * Mode::JZ + 1>
3063 byTiming{};
3064 for (int p = 0; p < 3; ++p) {
3065 for (int n = 0; n < 7; ++n) {
3066 int const base = Mode::JSTRT + NSSY * n + p * 36 * NSSY;
3067 int const first = std::max(-Mode::JZ, -base);
3068 int const last =
3069 std::min(Mode::JZ, Mode::NHSYM - 1 - base);
3070 for (int j = first; j <= last; ++j)
3071 byTiming[j + Mode::JZ][0][p] +=
3072 s[i + NFOS * Costas[p][n]][j + base];
3073 for (int freq = 0; freq < 7; ++freq) {
3074 auto const &row = s[i + NFOS * freq];
3075 for (int j = first; j <= last; ++j)
3076 byTiming[j + Mode::JZ][1][p] += row[j + base];
3077 }
3078 }
3079 }
3080 for (int j = -Mode::JZ; j <= Mode::JZ; ++j) {
3081 auto const &t = byTiming[j + Mode::JZ];
3082 auto const compute_sync = [&t](int start, int end) {
3083 float tx = 0.0f;
3084 float t0 = 0.0f;
3085 for (int block = start; block <= end; ++block) {
3086 tx += t[0][block];
3087 t0 += t[1][block];
3088 }
3089 return tx / ((t0 - tx) / 6.0f);
3090 };
3091 float const sync_value =
3092 std::max({compute_sync(0, 2), compute_sync(0, 1),
3093 compute_sync(1, 2)});
3094#ifdef JS8_BENCHMARK_VERIFY_RANK_SCAN
3095 // Verify the entire score surface, including cells that
3096 // never become the winning candidate. This is deliberately
3097 // off in timed builds.
3098 std::array<std::array<float, 3>, 2> original{};
3099 for (int p = 0; p < 3; ++p)
3100 for (int n = 0; n < 7; ++n) {
3101 int const offset =
3102 j + Mode::JSTRT + NSSY * n + p * 36 * NSSY;
3103 if (offset >= 0 && offset < Mode::NHSYM) {
3104 original[0][p] +=
3105 s[i + NFOS * Costas[p][n]][offset];
3106 for (int freq = 0; freq < 7; ++freq)
3107 original[1][p] +=
3108 s[i + NFOS * freq][offset];
3109 }
3110 }
3111 auto const originalSync = [&original](int start, int end) {
3112 float tx = 0.0f;
3113 float t0 = 0.0f;
3114 for (int block = start; block <= end; ++block) {
3115 tx += original[0][block];
3116 t0 += original[1][block];
3117 }
3118 return tx / ((t0 - tx) / 6.0f);
3119 };
3120 float const reference =
3121 std::max({originalSync(0, 2), originalSync(0, 1),
3122 originalSync(1, 2)});
3123 if (std::memcmp(&sync_value, &reference, sizeof(sync_value)))
3124 ++benchmarkRankMismatches;
3125 ++comparedScores;
3126#endif
3127 if (sync_value > max_value) {
3128 max_value = sync_value;
3129 max_index = j;
3130 }
3131 }
3132#endif
3133
3134 sync.emplace(Mode::DF * i, Mode::TSTEP * (max_index + 0.5f),
3135 max_value);
3136 }
3137#ifdef JS8_BENCHMARK_VERIFY_RANK_SCAN
3138 benchmarkRankComparedScores += comparedScores;
3139#endif
3140#ifdef JS8_CPU_BENCHMARK
3141 }
3142 BenchmarkScope benchmarkIndexScope{benchmarkRankIndexCalls,
3143 benchmarkRankIndexNanos};
3144#endif
3145
3146 // If we found nothing, we're done here.
3147
3148 if (sync.empty())
3149 return {};
3150
3151 // Access the sync indices.
3152
3153 auto &freqIndex = sync.get<Tag::Freq>();
3154 auto &rankIndex = sync.get<Tag::Rank>();
3155 auto &syncIndex = sync.get<Tag::Sync>();
3156
3157 // Normalize to the 40th percentile using the frequency index,
3158 // which is stable under sync value mutation. One thing to note
3159 // here is that the Fortran version didn't seem to reliably
3160 // calculate the 40th percentile rank; sometimes high, other
3161 // times low, infrequently actually the 40th percentile value.
3162 // This method should be perfectly accurate in all cases.
3163
3164 auto const normalize =
3165 [sync = rankIndex.nth(rankIndex.size() * 4 / 10)->sync](
3166 Sync &entry) { entry.sync /= sync; };
3167
3168 for (auto it = freqIndex.begin(); it != freqIndex.end(); ++it) {
3169 freqIndex.modify(it, normalize);
3170 }
3171
3172 // Extract normal candidates first, while retaining a small bounded
3173 // fallback band below ASYNCMIN. Because syncIndex is ordered from
3174 // strongest to weakest, normal candidates always win duplicate
3175 // suppression before a deep-search candidate can claim the same
3176 // frequency neighborhood.
3177
3178 SyncCandidates candidates;
3179
3180 for (auto it = syncIndex.begin(); it != syncIndex.end();
3181 it = syncIndex.begin()) {
3182 if (std::isnan(it->sync) || it->sync < ASYNCDEEP)
3183 break;
3184
3185 if (it->sync >= ASYNCMIN) {
3186 if (candidates.normal.size() >= NMAXCAND)
3187 break;
3188
3189 candidates.normal.push_back(*it);
3190 } else {
3191 if (!m_enableDeepSearch || candidates.deep.size() >= NMAXDEEP)
3192 break;
3193
3194 candidates.deep.push_back(*it);
3195 }
3196
3197 // Remove the candidate and any near-duplicates based on
3198 // frequency. This invalidates `it`, so the loop restarts at the
3199 // strongest remaining entry.
3200
3201 freqIndex.erase(freqIndex.lower_bound(it->freq - Mode::AZ),
3202 freqIndex.upper_bound(it->freq + Mode::AZ));
3203 }
3204
3205 return candidates;
3206 }
3207
3208 // Returns the total synchronization power, which is a measure of how well
3209 // the signal aligns with the Costas sequence after accounting for the
3210 // frequency adjustment. Used to identify the best alignment for further
3211 // decoding.
3212
3216 float syncjs8d(int const i0, float const delf) {
3217#ifdef JS8_CPU_BENCHMARK
3218 BenchmarkScope benchmarkScope{benchmarkSyncCalls, benchmarkSyncNanos};
3219#endif
3220 constexpr float BASE_DPHI = TAU * (1.0f / (12000.0f / Mode::NDOWN));
3221 std::array<std::complex<float>, Mode::NDOWNSPS> freqAdjust;
3222 if (delf != 0.0f) {
3223 float const dphi = BASE_DPHI * delf;
3224 float phi = 0.0f;
3225 for (int i = 0; i < Mode::NDOWNSPS; ++i) {
3226 freqAdjust[i] = std::polar(1.0f, phi);
3227 if (phi = std::fmod(phi + dphi, TAU); phi < 0.0f)
3228 phi += TAU;
3229 }
3230 } else {
3231 freqAdjust.fill(std::complex<float>{1.0f, 0.0f});
3232 }
3233
3234 float syncPower = 0.0f;
3235 for (int block = 0; block < 3; ++block) {
3236 for (int symbol = 0; symbol < 7; ++symbol) {
3237 int const offset =
3238 36 * block * Mode::NDOWNSPS + i0 + symbol * Mode::NDOWNSPS;
3239
3240 if (offset >= 0 && offset + Mode::NDOWNSPS <= Mode::NP2) {
3241 syncPower += std::norm(std::transform_reduce(
3242 freqAdjust.begin(), freqAdjust.end(), cd0.begin() + offset,
3243 std::complex<float>{}, std::plus<>{},
3244 [&](auto const &fa, auto const &cd) {
3245 return cd * std::conj(
3246 fa * csyncs[block][symbol][&fa - &freqAdjust[0]]);
3247 }));
3248 }
3249 }
3250 }
3251
3252 return syncPower;
3253 }
3254
3255 // Generate a reference signal, based on the provided tone sequence and
3256 // base frequency. The output is a vector of complex values representing
3257 // the signal in the time domain.
3258
3259 std::vector<std::complex<float>>
3260 genjs8refsig(std::array<int, NN> const &itone, float const f0) {
3261#ifdef JS8_CPU_BENCHMARK
3262 BenchmarkScope benchmarkScope{benchmarkReferenceCalls,
3263 benchmarkReferenceNanos};
3264#endif
3265 // Precompute the base frequency contribution; full circle in
3266 // radians, multipled by the base frequency, multiplied by the
3267 // sampling interval, i.e., the time step between samples, which
3268 // results in the base frequency phase increment. Start the
3269 // phase accumulator off at zero.
3270
3271 float const BFPI = TAU * f0 * (1.0f / 12000.0f);
3272 auto phi = 0.0f;
3273
3274 std::vector<std::complex<float>> cref;
3275 cref.reserve(NN * Mode::NSPS);
3276
3277 for (int i = 0; i < NN; ++i) {
3278 // Compute phase increment for the tone; frequency offset is
3279 // determined by the tone value.
3280
3281 float const dphi =
3282 BFPI + TAU * static_cast<float>(itone[i]) / Mode::NSPS;
3283
3284 // Iterate over the samples per symbol to generate the time
3285 // domain signal.
3286
3287 for (std::size_t is = 0; is < Mode::NSPS; ++is) {
3288 cref.push_back(std::polar(1.0f, phi));
3289 phi = std::fmod(phi + dphi, TAU);
3290 }
3291 }
3292
3293 return cref;
3294 }
3295
3296 // Subtract a JS8 signal
3297 //
3298 // Measured signal : dd(t) = a(t)cos(2*pi*f0*t+theta(t))
3299 // Reference signal : cref(t) = exp( j*(2*pi*f0*t+phi(t)) )
3300 // Complex amp : cfilt(t) = LPF[ dd(t)*CONJG(cref(t)) ]
3301 // Subtract : dd(t) = dd(t) - 2*REAL{cref*cfilt}
3302 //
3303 // Important to note that dt can be negative here.
3304
3305 void subtractjs8(std::vector<std::complex<float>> const &cref,
3306 float const dt) {
3307#ifdef JS8_CPU_BENCHMARK
3308 BenchmarkScope benchmarkScope{benchmarkSicCalls, benchmarkSicNanos};
3309#endif
3310 auto const nstart = js8::sicStartSample(dt);
3311 std::size_t const cref_start =
3312 (nstart < 0) ? static_cast<std::size_t>(-nstart) : 0;
3313 std::size_t const dd_start =
3314 (nstart > 0) ? static_cast<std::size_t>(nstart) : 0;
3315
3316 if (cref_start >= cref.size() || dd_start >= dd.size())
3317 return;
3318
3319 auto const size =
3320 std::min(cref.size() - cref_start, dd.size() - dd_start);
3321
3322 if (size == 0)
3323 return;
3324
3325 // Mixed (demodulated) envelope shared by both channel candidates.
3326 // mixed(i) = dd(i) * conj(cref(i)) is the complex signal we estimate.
3327 auto const mixed = [&](std::size_t i) -> std::complex<float> {
3328 return dd[dd_start + i] * std::conj(cref[cref_start + i]);
3329 };
3330
3331 // Candidate A: the established FFT low-pass filtered channel estimate.
3332 // Its #5a architecture (mixed -> FFT -> filter -> IFFT) is unchanged.
3333 for (std::size_t i = 0; i < size; ++i) {
3334 cfilt[i] = mixed(i);
3335 }
3336 // Zero-fill the remainder, then low-pass the complex channel estimate.
3337 std::fill(cfilt.begin() + size, cfilt.end(), ZERO);
3338 fftwf_execute(plans[Plan::CF]);
3339 std::transform(cfilt.begin(), cfilt.end(), filter.begin(),
3340 cfilt.begin(), std::multiplies<>());
3341 fftwf_execute(plans[Plan::CB]);
3342
3343 // Candidate B: a constrained, slowly varying segmented channel. One
3344 // complex coefficient per multi-symbol window, smoothed across windows
3345 // and interpolated back to the sample grid. This can track slow fading
3346 // the fixed LPF cannot, but it carries many loosely constrained
3347 // parameters, so we only adopt it when it measurably beats the LPF
3348 // candidate on the identical correlation metric.
3349 std::vector<std::complex<float>> mixedVec(size);
3350 for (std::size_t i = 0; i < size; ++i)
3351 mixedVec[i] = mixed(i);
3352
3353 std::size_t const windowSamples =
3354 std::clamp<std::size_t>(2 * Mode::NSPS, Mode::NSPS, 4 * Mode::NSPS);
3355 std::size_t const windowCount =
3356 std::max<std::size_t>(1, (size + windowSamples - 1) / windowSamples);
3357
3358 // Per-window complex coefficient (mean of the mixed signal). Windowing
3359 // across several symbols keeps a competing weak signal from being
3360 // trivially fitted as a single coefficient.
3361 std::vector<std::complex<float>> coeff(windowCount, ZERO);
3362 std::vector<double> centers(windowCount, 0.0);
3363 for (std::size_t w = 0; w < windowCount; ++w) {
3364 std::size_t const wBegin = w * windowSamples;
3365 std::size_t const wEnd = std::min(wBegin + windowSamples, size);
3366 std::complex<double> acc{};
3367 for (std::size_t i = wBegin; i < wEnd; ++i)
3368 acc += std::complex<double>{mixedVec[i].real(),
3369 mixedVec[i].imag()};
3370 std::size_t const span = wEnd - wBegin;
3371 double const inv = 1.0 / static_cast<double>(span);
3372 coeff[w] = std::complex<float>{static_cast<float>(acc.real() * inv),
3373 static_cast<float>(acc.imag() * inv)};
3374 centers[w] = static_cast<double>(wBegin) +
3375 0.5 * (static_cast<double>(span) - 1.0);
3376 }
3377
3378 // Triangular smoothing across neighboring window coefficients.
3379 std::vector<std::complex<float>> smoothed(windowCount, ZERO);
3380 for (std::size_t w = 0; w < windowCount; ++w) {
3381 std::complex<double> acc{};
3382 double wt = 0.0;
3383 for (int dw = -2; dw <= 2; ++dw) {
3384 long long const j = static_cast<long long>(w) + dw;
3385 if (j < 0 || j >= static_cast<long long>(windowCount))
3386 continue;
3387 double const weight = 1.0 - std::abs(dw) * 0.25;
3388 auto const coefficient =
3389 coeff[static_cast<std::size_t>(j)];
3390 acc += std::complex<double>{coefficient.real(),
3391 coefficient.imag()} *
3392 weight;
3393 wt += weight;
3394 }
3395 smoothed[w] = std::complex<float>{static_cast<float>(acc.real() / wt),
3396 static_cast<float>(acc.imag() / wt)};
3397 }
3398
3399 // Interpolate the smoothed coefficients at the actual center sample of
3400 // each measurement window, including a shorter final window. Samples
3401 // outside the first and last centers reuse the nearest coefficient, so
3402 // the channel remains continuous without stretching the trajectory.
3403 std::vector<std::complex<float>> segmented(size, ZERO);
3404 std::size_t segment = 0;
3405 for (std::size_t i = 0; i < size; ++i) {
3406 double const sample = static_cast<double>(i);
3407 while (segment + 1 < windowCount &&
3408 sample > centers[segment + 1])
3409 ++segment;
3410 if (segment + 1 >= windowCount || sample <= centers[segment]) {
3411 segmented[i] = smoothed[segment];
3412 continue;
3413 }
3414
3415 double const fraction =
3416 (sample - centers[segment]) /
3417 (centers[segment + 1] - centers[segment]);
3418 segmented[i] = std::complex<float>{
3419 static_cast<float>(smoothed[segment].real() * (1.0 - fraction) +
3420 smoothed[segment + 1].real() * fraction),
3421 static_cast<float>(smoothed[segment].imag() * (1.0 - fraction) +
3422 smoothed[segment + 1].imag() * fraction)};
3423 }
3424
3425 // Per-symbol matched-correlation residual, identical for both
3426 // candidates, so the selection reflects genuine cancellation quality.
3427 auto afterMetricOf = [&](auto const &channel) {
3428 std::array<std::complex<double>, NN> after{};
3429 for (std::size_t i = 0; i < size; ++i) {
3430 std::size_t const crefIndex = cref_start + i;
3431 std::size_t const symbolIndex = crefIndex / Mode::NSPS;
3432 auto const reference = std::complex<double>{cref[crefIndex].real(),
3433 cref[crefIndex].imag()};
3434 float const reconstructed =
3435 2.0f * std::real(channel[i] * cref[crefIndex]);
3436 float const residual = dd[dd_start + i] - reconstructed;
3437 after[symbolIndex] +=
3438 static_cast<double>(residual) * std::conj(reference);
3439 }
3440 return std::accumulate(after.begin(), after.end(), 0.0,
3441 [](double const t, auto const &v) {
3442 return t + std::norm(v);
3443 });
3444 };
3445
3446 // Matched correlation of the untouched signal and of the LPF
3447 // reconstruction, using the identical per-symbol metric.
3448 std::array<std::complex<double>, NN> beforeCorrelation{};
3449 for (std::size_t i = 0; i < size; ++i) {
3450 std::size_t const crefIndex = cref_start + i;
3451 std::size_t const symbolIndex = crefIndex / Mode::NSPS;
3452 auto const reference = std::complex<double>{cref[crefIndex].real(),
3453 cref[crefIndex].imag()};
3454 beforeCorrelation[symbolIndex] +=
3455 static_cast<double>(dd[dd_start + i]) * std::conj(reference);
3456 }
3457 auto const correlationPower = [](auto const &correlation) {
3458 return std::accumulate(
3459 correlation.begin(), correlation.end(), 0.0,
3460 [](double const total, auto const &value) {
3461 return total + std::norm(value);
3462 });
3463 };
3464
3465 double const beforeMetric = correlationPower(beforeCorrelation);
3466 double const afterMetricLpf = afterMetricOf(cfilt);
3467 double const afterMetricAdaptive = afterMetricOf(segmented);
3468
3469 // ~0.1% margin before adopting the more complex segmented model; keeps
3470 // us from switching on floating-point noise alone.
3471 double const adaptiveMargin = 0.001;
3472 bool const lpfValid = std::isfinite(afterMetricLpf) &&
3473 afterMetricLpf > 0.0;
3474 bool const adaptiveValid = std::isfinite(afterMetricAdaptive) &&
3475 afterMetricAdaptive > 0.0;
3476 bool const useAdaptive = adaptiveValid && lpfValid &&
3477 afterMetricAdaptive <
3478 afterMetricLpf * (1.0 - adaptiveMargin);
3479 std::string_view channelModel =
3480 useAdaptive ? std::string_view{"segmented"}
3481 : std::string_view{"lpf"};
3482 double const selectedAfterMetric =
3483 useAdaptive ? afterMetricAdaptive : afterMetricLpf;
3484
3485 // Unchanged #5a acceptance: subtract only if the selected candidate
3486 // reduces the decoded waveform's correlation relative to the untouched
3487 // signal. NaN/Inf metrics never pass, so no subtraction occurs.
3488 bool const accepted =
3489 std::isfinite(beforeMetric) &&
3490 beforeMetric > std::numeric_limits<double>::epsilon() &&
3491 std::isfinite(selectedAfterMetric) &&
3492 selectedAfterMetric < beforeMetric;
3493 double const suppressionDb = accepted
3494 ? 10.0 * std::log10(beforeMetric /
3495 std::max(selectedAfterMetric,
3496 std::numeric_limits<double>::min()))
3497 : 0.0;
3498
3499 if (decoder_js8().isDebugEnabled()) {
3500 qCDebug(decoder_js8)
3501 << "SIC subtraction"
3502 << "beforeMetric" << beforeMetric
3503 << "lpfAfterMetric" << afterMetricLpf
3504 << "adaptiveAfterMetric" << afterMetricAdaptive
3505 << "selectedAfterMetric" << selectedAfterMetric
3506 << "channelModel" << channelModel
3507 << "suppressionDb" << suppressionDb
3508 << "accepted" << accepted;
3509 }
3510
3511 // Do not damage the receive buffer when the selected reconstruction does
3512 // not actually reduce the decoded waveform's matched-correlation power.
3513 if (!accepted)
3514 return;
3515
3516 if (useAdaptive) {
3517 for (std::size_t i = 0; i < size; ++i) {
3518 dd[dd_start + i] -=
3519 2.0f * std::real(segmented[i] * cref[cref_start + i]);
3520 }
3521 } else {
3522 for (std::size_t i = 0; i < size; ++i) {
3523 dd[dd_start + i] -=
3524 2.0f * std::real(cfilt[i] * cref[cref_start + i]);
3525 }
3526 }
3527 }
3528
3529 public:
3530 // Constructor
3531
3532 DecodeMode() {
3533 m_enableFreqTracking =
3534 std::getenv("JS8_DISABLE_FREQ_TRACKING") == nullptr;
3535 m_enableTimingTracking =
3536 std::getenv("JS8_DISABLE_TIMING_TRACKING") == nullptr;
3537 m_enableDeepSearch =
3538 std::getenv("JS8_DISABLE_DEEP_SEARCH") == nullptr;
3539 m_enableLdpcRescue =
3540 std::getenv("JS8_DISABLE_LDPC_RESCUE") == nullptr;
3541 m_enableCoherentData =
3542 std::getenv("JS8_DISABLE_COHERENT_DATA") == nullptr;
3543 m_enableAidedRedemod =
3544 std::getenv("JS8_DISABLE_REDEMOD") == nullptr;
3545
3546 // Intialize the Nuttal window. In theory, we can do this as a
3547 // constexpr function at compile time, but doing so yield results
3548 // slightly different than the Fortran version did, so for sanity
3549 // while testing, we'll opt for consistency. IEEE 754 is always a
3550 // bit brittle.
3551
3552 constexpr float a0 = 0.3635819f;
3553 constexpr float a1 = -0.4891775f;
3554 constexpr float a2 = 0.1365995f;
3555 constexpr float a3 = -0.0106411f;
3556
3557 // Computed Pi constant to match the Fortran version; we could
3558 // probably use std::numbers::pi_v<float> here, but for the
3559 // moment, matching Fortran exactly.
3560
3561 float const pi = 4.0f * std::atan(1.0f);
3562 float sum = 0.0f;
3563
3564 for (std::size_t i = 0; i < nuttal.size(); ++i) {
3565 // Naive summation here will exhibit substantial precision loss
3566 // relative to the Fortran version; we use Kahan summation to
3567 // compensate, which should yield results identical to Fortran.
3568
3569 KahanSum value = a0;
3570
3571 value += a1 * std::cos(2 * pi * i / nuttal.size());
3572 value += a2 * std::cos(4 * pi * i / nuttal.size());
3573 value += a3 * std::cos(6 * pi * i / nuttal.size());
3574
3575 nuttal[i] = value;
3576 sum += value;
3577 }
3578
3579 // Normalize the Nuttal window.
3580
3581 for (auto &value : nuttal)
3582 value = value / sum * nuttal.size() / 300.0f;
3583
3584 // Initialize Costas waveforms.
3585
3586 for (int i = 0; i < 7; ++i) {
3587 float const dphia = TAU * Costas[0][i] / Mode::NDOWNSPS;
3588 float const dphib = TAU * Costas[1][i] / Mode::NDOWNSPS;
3589 float const dphic = TAU * Costas[2][i] / Mode::NDOWNSPS;
3590
3591 float phia = 0.0f;
3592 float phib = 0.0f;
3593 float phic = 0.0f;
3594
3595 for (int j = 0; j < Mode::NDOWNSPS; ++j) {
3596 csyncs[0][i][j] = std::polar(1.0f, phia);
3597 csyncs[1][i][j] = std::polar(1.0f, phib);
3598 csyncs[2][i][j] = std::polar(1.0f, phic);
3599
3600 phia = std::fmod(phia + dphia, TAU);
3601 phib = std::fmod(phib + dphib, TAU);
3602 phic = std::fmod(phic + dphic, TAU);
3603 }
3604 }
3605
3606 // Construct the subtraction LPF as a zero-phase circular-convolution
3607 // kernel. Positive-time taps live at the beginning of the FFT buffer
3608 // and negative-time taps wrap to its end, matching the original
3609 // Fortran layout.
3610
3611 sum = 0.0f;
3612 for (int j = -NFILT / 2; j <= NFILT / 2; ++j)
3613 sum += std::pow(std::cos(pi * j / NFILT), 2);
3614
3615 filter.fill(ZERO);
3616 for (int j = -NFILT / 2; j <= NFILT / 2; ++j) {
3617 float const value =
3618 std::pow(std::cos(pi * j / NFILT), 2) / sum;
3619 std::size_t const index =
3620 j >= 0 ? static_cast<std::size_t>(j)
3621 : filter.size() - static_cast<std::size_t>(-j);
3622 filter[index] = std::complex<float>(value, 0.0f);
3623 }
3624
3625 // Transform the filter into the frequency domain.
3626
3627 fftwf_plan fftw_plan;
3628 {
3629 std::lock_guard<std::mutex> lock(fftw_mutex);
3630
3631 fftw_plan = fftwf_plan_dft_1d(
3632 Mode::NMAX, reinterpret_cast<fftwf_complex *>(filter.data()),
3633 reinterpret_cast<fftwf_complex *>(filter.data()), FFTW_FORWARD,
3634 FFTW_ESTIMATE_PATIENT);
3635
3636 if (!fftw_plan) {
3637 throw std::runtime_error("Failed to create FFT plan");
3638 }
3639 }
3640
3641 fftwf_execute(fftw_plan);
3642
3643 {
3644 std::lock_guard<std::mutex> lock(fftw_mutex);
3645 fftwf_destroy_plan(fftw_plan);
3646 }
3647
3648 // Normalize the frequency domain representation.
3649
3650 std::transform(filter.begin(), filter.end(), filter.begin(),
3651 [factor = 1.0f / Mode::NMAX](auto value) {
3652 return value * factor;
3653 });
3654
3655 // The rest of our FFT plans are always the same size and operate on the
3656 // same data, so we can reuse them as long as we're alive.
3657
3658 std::lock_guard<std::mutex> lock(fftw_mutex);
3659
3660 plans[Plan::DS] = fftwf_plan_dft_1d(
3661 Mode::NDFFT2, reinterpret_cast<fftwf_complex *>(cd0.data()),
3662 reinterpret_cast<fftwf_complex *>(cd0.data()), FFTW_BACKWARD,
3663 FFTW_ESTIMATE_PATIENT);
3664
3665 plans[Plan::BB] = fftwf_plan_dft_r2c_1d(
3666 Mode::NDFFT1, reinterpret_cast<float *>(ds_cx.data()),
3667 reinterpret_cast<fftwf_complex *>(ds_cx.data()),
3668 FFTW_ESTIMATE_PATIENT);
3669
3670 plans[Plan::CF] = fftwf_plan_dft_1d(
3671 Mode::NMAX, reinterpret_cast<fftwf_complex *>(cfilt.data()),
3672 reinterpret_cast<fftwf_complex *>(cfilt.data()), FFTW_FORWARD,
3673 FFTW_ESTIMATE_PATIENT);
3674
3675 plans[Plan::CB] = fftwf_plan_dft_1d(
3676 Mode::NMAX, reinterpret_cast<fftwf_complex *>(cfilt.data()),
3677 reinterpret_cast<fftwf_complex *>(cfilt.data()), FFTW_BACKWARD,
3678 FFTW_ESTIMATE_PATIENT);
3679
3680 plans[Plan::SD] = fftwf_plan_dft_r2c_1d(
3681 Mode::NFFT1, reinterpret_cast<float *>(sd.data()),
3682 reinterpret_cast<fftwf_complex *>(sd.data()),
3683 FFTW_ESTIMATE_PATIENT);
3684
3685 plans[Plan::CS] = fftwf_plan_dft_1d(
3686 Mode::NDOWNSPS, reinterpret_cast<fftwf_complex *>(csymb.data()),
3687 reinterpret_cast<fftwf_complex *>(csymb.data()), FFTW_FORWARD,
3688 FFTW_ESTIMATE_PATIENT);
3689
3690 for (auto plan : plans) {
3691 if (!plan)
3692 throw std::runtime_error("Failed to create FFT plan");
3693 }
3694 }
3695
3696 // Decode entry point.
3697
3698 std::size_t operator()(struct dec_data const &data, int const kpos,
3699 int const ksz, JS8::Event::Emitter emitEvent,
3700 js8::OptionalWorkBudget *optional = nullptr) {
3701 // Copy the relevant frames for decoding
3702
3703 auto const pos = std::max(0, kpos);
3704 auto const sz = std::max(0, ksz);
3705
3706 assert(sz <= Mode::NMAX);
3707
3708 if (data.params.syncStats)
3709 emitEvent(JS8::Event::SyncStart{pos, sz});
3710
3711 auto const ddCopy = [](auto const begin, auto const end,
3712 auto const to) {
3713 std::transform(begin, end, to, [](auto const value) {
3714 return static_cast<float>(value);
3715 });
3716 };
3717
3718 dd.fill(0.0f);
3719
3720 if ((JS8_RX_SAMPLE_SIZE - pos) < sz) {
3721 // Wrap case; split into two parts.
3722
3723 int const firstsize = JS8_RX_SAMPLE_SIZE - pos;
3724 int const secondsize = sz - firstsize;
3725
3726 ddCopy(std::begin(data.d2) + pos,
3727 std::begin(data.d2) + pos + firstsize, dd.begin());
3728 ddCopy(std::begin(data.d2), std::begin(data.d2) + secondsize,
3729 dd.begin() + firstsize);
3730 } else {
3731 // Non-wrapping case; copy directly.
3732
3733 ddCopy(std::begin(data.d2) + pos, std::begin(data.d2) + pos + sz,
3734 dd.begin());
3735 }
3736
3737 Decode::Map decodes;
3738 auto const ttl = std::chrono::seconds{Mode::NTXDUR * 2};
3739 m_softCombiner.flush(ttl);
3740
3741 int ldpcRescueBudget = BP_RESCUE_BUDGET;
3742
3743 for (int ipass = 1; ipass <= 3; ++ipass) {
3744 // Determine if there's anything worth considering in the signal.
3745 // If not, then we can just bail completely; more passes will not
3746 // yield more results. If we do have some candidates, sort them
3747 // by frequency, but put any that are close to nfqso up front.
3748
3749 auto candidates = syncjs8(data.params.nfa, data.params.nfb);
3750
3751 if (candidates.empty())
3752 break;
3753
3754 auto const sortCandidates =
3755 [nfqso = data.params.nfqso](auto &candidateList) {
3756 std::sort(
3757 candidateList.begin(), candidateList.end(),
3758 [nfqso](auto const &a, auto const &b) {
3759 auto const a_dist = std::abs(a.freq - nfqso);
3760 auto const b_dist = std::abs(b.freq - nfqso);
3761
3762 if (a_dist < 10.0f && b_dist >= 10.0f)
3763 return true;
3764 if (b_dist < 10.0f && a_dist >= 10.0f)
3765 return false;
3766
3767 return std::tie(a_dist, a.freq) <
3768 std::tie(b_dist, b.freq);
3769 });
3770 };
3771
3772 sortCandidates(candidates.normal);
3773 sortCandidates(candidates.deep);
3774
3775 // Recompute the baseband signal; subtraction during the last
3776 // pass might have changed the landscape.
3777
3778 computeBasebandFFT();
3779
3780 bool const subtract = ipass < 3;
3781 bool improved = false;
3782
3783 auto const tryCandidates = [&](auto const &candidateList,
3784 bool deep) {
3785 for (auto [f1, xdt, sync] : candidateList) {
3786 if (deep && optional &&
3787 !optional->allow(js8::OptionalStage::Deep)) {
3788 qCDebug(decoder_js8) << "adaptive optional skip deep";
3789 break;
3790 }
3791 auto const optionalStarted =
3792 js8::OptionalWorkBudget::Clock::now();
3793 float xsnr = 0.0f;
3794 int nharderrors = -1;
3795
3796 auto decode = js8dec(data.params.syncStats, subtract, f1,
3797 xdt, nharderrors, xsnr,
3798 ldpcRescueBudget, emitEvent, optional,
3799 deep);
3800 if (deep && optional)
3801 optional->observe(js8::OptionalStage::Deep,
3802 optionalStarted);
3803 if (decode) {
3804 // We don't need to be emitting duplicate events for
3805 // something that's effectively the same SNR as a
3806 // previous event.
3807
3808 auto const snr = static_cast<int>(std::round(xsnr));
3809
3810 // If this decode is new, or it's a duplicate with a
3811 // better SNR than what we had before, then our situation
3812 // has improved and we must announce that we've had some
3813 // success.
3814
3815 if (auto [it, inserted] =
3816 decodes.try_emplace(std::move(*decode), snr);
3817 inserted || it->second < snr) {
3818 improved = true;
3819
3820 if (!inserted)
3821 it->second = snr;
3822
3823 emitEvent(JS8::Event::Decoded{
3824 data.params.nutc, snr, xdt - Mode::ASTART, f1,
3825 it->first.data, it->first.type,
3826 1.0f - nharderrors / 60.0f,
3827 Mode::NSUBMODE});
3828 }
3829 }
3830 }
3831 };
3832
3833 // Preserve the existing fast path: normal candidates always get
3834 // first shot. The lower coarse-sync band is only sent through the
3835 // expensive coherent/fine decoder when the normal set produced no
3836 // improvement, or on the final subtraction pass so weak independent
3837 // signals are not permanently starved by stronger traffic.
3838
3839 tryCandidates(candidates.normal, false);
3840
3841 bool const tryDeep =
3842 m_enableDeepSearch && !candidates.deep.empty() &&
3843 (!improved || ipass == 3);
3844
3845 if (tryDeep) {
3846 if (decoder_js8().isDebugEnabled()) {
3847 qCDebug(decoder_js8)
3848 << "deep sync fallback"
3849 << "pass" << ipass << "candidates"
3850 << candidates.deep.size();
3851 }
3852
3853 tryCandidates(candidates.deep, true);
3854 }
3855
3856 // If nothing from this pass improved our situation, there's no
3857 // point in trying any remaining passes.
3858
3859 if (!improved)
3860 break;
3861 }
3862
3863 // Let the caller know how many unique decodes we discovered, if any.
3864
3865 return decodes.size();
3866 }
3867};
3868
3869// Explicit template class instantiations; avoids compiler complaints
3870// about unused variables.
3871
3872template class DecodeMode<ModeA>;
3873template class DecodeMode<ModeB>;
3874template class DecodeMode<ModeC>;
3875template class DecodeMode<ModeE>;
3876template class DecodeMode<ModeI>;
3877} // namespace
3878} // namespace
3879
3880/******************************************************************************/
3881// Worker
3882/******************************************************************************/
3883
3884namespace JS8 {
3885class Worker : public QObject {
3886 Q_OBJECT
3887
3888 // Initialization of the decoders, in that they're heavy with
3889 // FFT plan creations, is non-trivial, so a handle-body class
3890 // to avoid initializing them on the main thread.
3891
3892 class Impl {
3893 // To avoid data races, decode data is referenced here but is
3894 // actually located in the Worker that instantiates us, as it
3895 // must be possible to copy data for us before we're ready to
3896 // process it.
3897
3898 struct dec_data &m_data;
3899 js8::OptionalWorkSignal const *m_optionalSignal;
3900 std::array<js8::OptionalWorkBudget::Duration, 5> m_modeCost{};
3901 std::array<std::array<js8::OptionalWorkBudget::Duration,
3902 js8::OptionalWorkBudget::stages>, 5>
3903 m_stageCost{};
3904 std::array<bool, 5> m_modeObserved{};
3905
3906 // Mode-specific decode strategy; we'll instantiate one of
3907 // these for each of the 5 modes; this class is an aggregate
3908 // of the 5 modes.
3909
3910 struct DecodeEntry {
3911 std::variant<DecodeMode<ModeA>, DecodeMode<ModeB>,
3912 DecodeMode<ModeC>, DecodeMode<ModeE>,
3913 DecodeMode<ModeI>>
3914 decode;
3915 int mode;
3916 int &kpos;
3917 int &ksz;
3918
3919 template <typename DecodeModeType>
3920 DecodeEntry(std::in_place_type_t<DecodeModeType>, int mode,
3921 int &kpos, int &ksz)
3922 : decode(std::in_place_type<DecodeModeType>), mode(mode),
3923 kpos(kpos), ksz(ksz) {}
3924 };
3925
3926 // Since a strategy can be neither moved nor copied, we must
3927 // instantiate them in-place. Note that with the advent of the
3928 // multi-decoder, mode identifiers became a bitset instead of
3929 // integral values. The order defined here is the order that the
3930 // decode loop will run in; we're matching the Fortran version here
3931 // in terms of faster modes first.
3932
3933 template <typename ModeType>
3934 DecodeEntry makeDecodeEntry(int shift, int &kpos, int &ksz) {
3935 return DecodeEntry(std::in_place_type<DecodeMode<ModeType>>,
3936 1 << shift, kpos, ksz);
3937 }
3938
3939 std::array<DecodeEntry, 5> m_decodes = {
3940 {makeDecodeEntry<ModeI>(4, m_data.params.kposI, m_data.params.kszI),
3941 makeDecodeEntry<ModeE>(3, m_data.params.kposE, m_data.params.kszE),
3942 makeDecodeEntry<ModeC>(2, m_data.params.kposC, m_data.params.kszC),
3943 makeDecodeEntry<ModeB>(1, m_data.params.kposB, m_data.params.kszB),
3944 makeDecodeEntry<ModeA>(0, m_data.params.kposA,
3945 m_data.params.kszA)}};
3946
3947 public:
3948 // Constructor
3949
3950 explicit Impl(struct dec_data &data,
3951 js8::OptionalWorkSignal const *signal)
3952 : m_data(data), m_optionalSignal(signal) {}
3953
3954 // Execute a decoding pass, using the supplied event emitter to
3955 // emit events as they occur.
3956
3957 void operator()(::JS8::Event::Emitter emitEvent) {
3958 // The multi-decoder can provide data for multiple modes at
3959 // the same time; specific decodes to be performed for this
3960 // pass are in the `nsubmodes` bitset.
3961
3962 auto const set = m_data.params.nsubmodes;
3963 std::size_t sum = 0;
3964
3965 // Let any interested parties know that we've started a run
3966 // for the set of modes requested.
3967
3968 emitEvent(::JS8::Event::DecodeStarted{set});
3969
3970 // Iterate through all the modes we're aware of, performing
3971 // a mode-specific decode pass if the mode is scheduled for
3972 // decoding during this pass.
3973
3974 for (std::size_t index = 0; index < m_decodes.size(); ++index) {
3975 auto &entry = m_decodes[index];
3976 if ((set & entry.mode) == entry.mode) {
3977 js8::OptionalWorkBudget::Duration reserve{0};
3978 bool unknownMandatory = false;
3979 for (std::size_t later = index + 1; later < m_decodes.size();
3980 ++later) {
3981 if (!(set & m_decodes[later].mode))
3982 continue;
3983 if (!m_modeObserved[later])
3984 unknownMandatory = true;
3985 else
3986 reserve += m_modeCost[later];
3987 }
3989 m_optionalSignal, reserve, m_stageCost[index],
3990 unknownMandatory};
3991 auto const started =
3992 js8::OptionalWorkBudget::Clock::now();
3993 std::visit(
3994 [&](auto &&decode) {
3995 sum += decode(m_data, entry.kpos, entry.ksz,
3996 emitEvent, &budget);
3997 },
3998 entry.decode);
3999 auto const duration =
4000 std::chrono::duration_cast<
4001 js8::OptionalWorkBudget::Duration>(
4002 js8::OptionalWorkBudget::Clock::now() - started);
4003 m_modeCost[index] =
4004 std::max(m_modeCost[index] * 9 / 10,
4005 duration + duration / 4);
4006 m_modeObserved[index] = true;
4007 }
4008 }
4009
4010 // Let any interested parties know the total number of decodes
4011 // performed during this run.
4012
4013 emitEvent(::JS8::Event::DecodeFinished{sum});
4014 }
4015 };
4016
4017 // Data members
4018
4019 QSemaphore *m_semaphore;
4020 js8::OptionalWorkSignal const *m_optionalSignal;
4021 std::atomic<bool> m_quit = false;
4022 struct dec_data m_data;
4023
4024 public:
4025 // Constructor
4026
4027 explicit Worker(QSemaphore *semaphore,
4028 js8::OptionalWorkSignal const *optionalSignal,
4029 QObject *parent = nullptr)
4030 : QObject(parent), m_semaphore(semaphore),
4031 m_optionalSignal(optionalSignal) {}
4032
4033 // Used to inform the worker that it's time to quit; the next
4034 // time it wakes up due to the semaphore being released, it
4035 // will exit the runloop.
4036
4037 void stop() { m_quit = true; }
4038
4039 // Called by the owning Decoder to refresh the copy of the
4040 // decode data that the Worker implementation references.
4041
4042 void copy() { m_data = dec_data; };
4043
4044 signals:
4045
4046 // Signal used to indicate that something of interest has
4047 // occurred during a decoding pass.
4048
4049 void decodeEvent(::JS8::Event::Variant const &);
4050
4051 public slots:
4052
4053 // Runloop for the thread that the worker is scheduled on; this
4054 // is started by the Decoder when it's informed that the thread
4055 // has started. Performs decoding runs each time the semaphore
4056 // is released, until it's informed that it should quit.
4057
4058 void run() {
4059 // Our thread has started, and we're now running on it, so
4060 // we're good to now allocate our implementation; we didn't
4061 // want that to happen on the main thread, as the FFT plans
4062 // can take a while. We only need the implementation while
4063 // we're running.
4064
4065 std::unique_ptr<Impl> impl = std::make_unique<Impl>(
4066 m_data, std::getenv("JS8_DISABLE_ADAPTIVE_OPTIONAL")
4067 ? nullptr : m_optionalSignal);
4068
4069 // Wait until there's something that requires our attention,
4070 // which is going to either be needing to quit or needing to
4071 // perform a decoding pass.
4072
4073 while (true) {
4074 m_semaphore->acquire();
4075
4076 if (m_quit)
4077 break;
4078
4079 (*impl)([this](::JS8::Event::Variant const &event) {
4080 emit decodeEvent(event);
4081 });
4082 }
4083 }
4084};
4085} // namespace JS8
4086
4087/******************************************************************************/
4088// Public Interface - Decoding
4089/******************************************************************************/
4090
4091#include "JS8.moc"
4092
4094 : QObject(parent), m_semaphore(0),
4095 m_worker(new JS8::Worker(&m_semaphore, &m_optionalPressure)) {
4096 m_worker->moveToThread(&m_thread);
4097
4098 connect(&m_thread, &QThread::started, m_worker, &JS8::Worker::run);
4099 connect(&m_thread, &QThread::finished, m_worker, &QObject::deleteLater);
4100 connect(m_worker, &JS8::Worker::decodeEvent, this, &Decoder::decodeEvent);
4101}
4102
4103void JS8::Decoder::start(QThread::Priority priority) {
4104 m_thread.start(priority);
4105}
4106
4108 m_worker->stop();
4109 m_semaphore.release();
4110 m_thread.quit();
4111 m_thread.wait();
4112}
4113
4115 m_worker->copy();
4116 m_semaphore.release();
4117}
4118
4119void JS8::Decoder::pendingDecode(bool pending) noexcept {
4120 m_optionalPressure.pending(pending);
4121}
4122
4123void JS8::Decoder::nextDecodeReady(
4124 std::chrono::steady_clock::time_point when) noexcept {
4125 m_optionalPressure.nextReady(when);
4126}
4127
4128/******************************************************************************/
4129// Public Interface - Encoding
4130/******************************************************************************/
4131
4132namespace JS8 {
4133// Port of the Fortran `genjs8` subroutine; from the 12 bytes of `message`,
4134// construct an 87-bit JS8 message and encode it into tones. Costas array
4135// to use supplied by the caller, as is the type of message, indicated by
4136// the lower 3 bits of `type`.
4137
4138void encode(int const type, Costas::Array const &costas,
4139 const char *const message, int *const tones) {
4140 // Our initial goal here is an 87-bit JS8 message, for which a std::bitset
4141 // would be the obvious choice, but we've got to compute a checksum of
4142 // the first 75 bits; thus, an array instead.
4143 //
4144 // Message structure:
4145 //
4146 // +----------+----------+----------+
4147 // | | | 72 bits | 12 6-bit words
4148 // | | +==========+
4149 // | | 87 bits | 3 bits | Frame type
4150 // | 11 bytes | +==========+
4151 // | | | 12 bits | 12-bit BE checksum
4152 // | |----------+==========+
4153 // | | 1 bit | 1 bit | Leftover bit in array
4154 // +----------+----------+==========+
4155
4156 std::array<std::uint8_t, 11> bytes = {};
4157
4158 // Convert the 12 characters we've been handed to 6-bit words and pack
4159 // them into the byte array, 4 characters, 24 bits at a time, into the
4160 // 9 bytes [0,8], 72 bits total. Throws if handed an invalid character.
4161
4162 for (int i = 0, j = 0; i < 12; i += 4, j += 3) {
4163 std::uint32_t words = (alphabetWord(message[i]) << 18) |
4164 (alphabetWord(message[i + 1]) << 12) |
4165 (alphabetWord(message[i + 2]) << 6) |
4166 alphabetWord(message[i + 3]);
4167
4168 bytes[j] = words >> 16;
4169 bytes[j + 1] = words >> 8;
4170 bytes[j + 2] = words;
4171 }
4172
4173 // The bottom 3 bits of type are the frame type; these go into the
4174 // next 3 bits in the byte array, i.e., the first 3 bits of byte 9,
4175 // after which we'll be at 75 bits in total.
4176
4177 bytes[9] = (type & 0b111) << 5;
4178
4179 // We now need to compute the augmented CRC-12 of the complete
4180 // byte array, including the trailing zero bits that we've not
4181 // set yet.
4182
4183 auto const crc = CRC12(bytes);
4184
4185 // That CRC needs to occupy the next 12 bits of the array, i.e.,
4186 // the final 5 bits of byte 9, and the first 7 bits of byte 10.
4187
4188 bytes[9] |= (crc >> 7) & 0x1F;
4189 bytes[10] = (crc & 0x7F) << 1;
4190
4191 // That's it for our 87-bit message; we're now going to turn it
4192 // into two blocks of 29 3-bit words, which will in turn become
4193 // tones, the first block being parity for the second, bracketed
4194 // by the Costas arrays.
4195 //
4196 // Output structure:
4197 //
4198 // +----------+----------+
4199 // | | 7 bytes | Costas array A
4200 // | +==========+
4201 // | | 29 bytes | Parity data
4202 // | +==========+
4203 // | 79 bytes | 7 bytes | Costas array B
4204 // | +==========+
4205 // | | 29 bytes | Output data
4206 // | +==========+
4207 // | | 7 bytes | Costas array C
4208 // +----------+==========+
4209
4210 auto costasData = tones;
4211 auto parityData = tones + 7;
4212 auto outputData = tones + 43;
4213
4214 // Output the 3 Costas arrays at offsets 0, 36, and 72.
4215
4216 for (auto const &array : costas) {
4217 std::copy(array.begin(), array.end(), costasData);
4218 costasData += 36;
4219 }
4220
4221 // Our 87 bits are going to be morphed into two sets of 29 3-bit
4222 // words, the first one parity for the second; we're going to do
4223 // this in parallel.
4224
4225 std::size_t outputBits = 0;
4226 std::size_t outputByte = 0;
4227 std::uint8_t outputMask = 0x80;
4228 std::uint8_t outputWord = 0;
4229 std::uint8_t parityWord = 0;
4230
4231 for (std::size_t i = 0; i < 87; ++i) {
4232 // Compute parity for the current bit; inputs for parity computation
4233 // are the corresponding parity matrix row and each bit in the message;
4234 // the parity matrix row, referenced by `i`, contains 87 boolean values.
4235 // Each `true` value defines a message bit that must be summed, modulo
4236 // 2, to produce the parity check bit for the bit we're working on now.
4237 //
4238 // In short, if the parity matrix bit `(i, j)` and the message bit `j`
4239 // are both set, then we add 1 to the parity bits accumulator. If, after
4240 // processing all message bits the accumulated result is odd, then the
4241 // parity bit should be set for the current bit.
4242
4243 std::size_t parityBits = 0;
4244 std::size_t parityByte = 0;
4245 std::uint8_t parityMask = 0x80;
4246
4247 for (std::size_t j = 0; j < 87; ++j) {
4248 parityBits += parity(i, j) && (bytes[parityByte] & parityMask);
4249 parityMask =
4250 (parityMask == 1) ? (++parityByte, 0x80) : (parityMask >> 1);
4251 }
4252
4253 // Accumulate the parity and output bits; this is the point at which
4254 // we perform the modulo 2 operation on the summed parity bits.
4255
4256 parityWord = (parityWord << 1) | (parityBits & 1);
4257 outputWord =
4258 (outputWord << 1) | ((bytes[outputByte] & outputMask) != 0);
4259 outputMask =
4260 (outputMask == 1) ? (++outputByte, 0x80) : (outputMask >> 1);
4261
4262 // If we're at a 3-bit boundary, output the words and reset.
4263
4264 if (++outputBits == 3) {
4265 *parityData++ = parityWord;
4266 *outputData++ = outputWord;
4267 parityWord = 0;
4268 outputWord = 0;
4269 outputBits = 0;
4270 }
4271 }
4272}
4273} // namespace JS8
4274
4275/******************************************************************************/
Trackers for residual frequency and timing offsets used by the decoder.
void encode(int const type, Costas::Array const &costas, const char *const message, int *const tones)
Encode a NUL-terminated message into tone indices using a Costas array.
Definition JS8.cpp:4138
Core JS8 namespace types, Costas arrays and decoder event payloads.
std::function< void(Variant const &)> Emitter
Definition JS8.h:125
std::array< std::array< int, 7 >, 3 > Array
Definition JS8.h:36
constexpr auto array
Return the Costas array for the requested Type.
Definition JS8.h:43
std::variant< DecodeStarted, SyncStart, SyncState, Decoded, DecodeFinished > Variant
Definition JS8.h:121
QMultiMap< quint32, QString > candidates(QString word, bool includeTwoEdits)
Generate candidate words that are one or two edit distances away.
Definition JSC_checker.cpp:239
Bounded confidence and finite check-node messages for LDPC decoding.
void quit()
Definition JS8.cpp:4107
void pendingDecode(bool pending) noexcept
Definition JS8.cpp:4119
void start(QThread::Priority priority)
Definition JS8.cpp:4103
Decoder(QObject *parent=nullptr)
Definition JS8.cpp:4093
void decodeEvent(Event::Variant const &)
void decode()
Definition JS8.cpp:4114
Definition JS8.cpp:3885
double currentHz() const noexcept
Current estimated residual frequency.
Definition FrequencyTracker.cpp:56
void reset(double initial_hz, double sample_rate_hz, double alpha=0.15, double max_step_hz=0.3, double max_error_hz=5.0)
Initialize or reconfigure the tracker.
Definition FrequencyTracker.cpp:24
double averageStepHz() const noexcept
Average step size applied by the tracker (Hz).
Definition FrequencyTracker.cpp:63
void update(double residual_hz, double weight=1.0)
Update the tracker estimate using a measured residual.
Definition FrequencyTracker.cpp:93
bool enabled() const noexcept
Whether the tracker is enabled.
Definition FrequencyTracker.cpp:49
void disable()
Disable the tracker (subsequent apply() calls become no-ops).
Definition FrequencyTracker.cpp:41
void apply(std::complex< float > *data, int count) const
Rotate an array of complex samples by the tracked frequency.
Definition FrequencyTracker.cpp:73
Definition optional_work.h:58
Definition optional_work.h:15
void markDecoded(Key const &key)
Remove cached repeats for a candidate that has been decoded.
Definition soft_combiner.h:157
void flush(std::chrono::seconds ttl)
Remove cached entries older than ttl.
Definition soft_combiner.h:182
Combined combine(Key const &key, std::array< float, N > const &llr0, std::array< float, N > const &llr1, std::chrono::seconds ttl)
Attempt to combine incoming LLRs with cached repeats.
Definition soft_combiner.h:121
Key makeKey(int mode, float f1, float dt, std::array< float, N > const &llr0, std::array< float, N > const &llr1) const
Create a Key for a candidate from its parameters and LLRs.
Definition soft_combiner.h:106
void reset(double initial_samples, double alpha=0.15, double max_step=0.35, double max_total_error=2.0)
Tracks residual timing (sample) offset between the symbol clock and the signal.
Definition FrequencyTracker.cpp:118
double averageStepSamples() const noexcept
Average timing step applied per update (samples).
Definition FrequencyTracker.cpp:155
double currentSamples() const noexcept
Current estimated residual timing offset in samples.
Definition FrequencyTracker.cpp:148
void disable()
Disable the TimingTracker.
Definition FrequencyTracker.cpp:133
bool enabled() const noexcept
Whether the timing tracker is enabled.
Definition FrequencyTracker.cpp:141
void update(double residual_samples, double weight=1.0)
Update timing estimate using a measured residual (samples).
Definition FrequencyTracker.cpp:165
static Result process(std::array< std::array< float, ND >, NROWS > const &s1, std::array< int, ND > const &symbolWinners, float erasureThreshold, bool debug, std::optional< CoherentBlend< NROWS, ND > > const &coherentBlend=std::nullopt, float llrScale=1.0f, Normalization normalization=Normalization::None)
Compute primary and noncoherent fallback LLRs for a candidate frame.
Definition whitening_processor.h:87
Conservative coherent 8-FSK likelihood support for the JS8 decoder.
Common definitions and constants used throughout the JS8Call-improved project.
#define JS8_RX_SAMPLE_RATE
Definition commons.h:20
Decoder-aided re-demodulation helpers for JS8 near-miss rescue.
constexpr int kDataSymbols
Definition decoder_aided_redemod.h:51
constexpr int kCodeBits
Definition decoder_aided_redemod.h:49
Refinement 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.
Definition decoder_aided_redemod.h:463
void buildSymbolWeights(ConfidenceSummary const &conf, std::array< float, kTotalSymbols > &weights)
Expand 58 data confidences to 79 per-symbol weights.
Definition decoder_aided_redemod.h:196
void buildCostasWeights(std::array< float, kTotalSymbols > &weights)
Expand confidences to Costas-only weights (1.0 on pilots, else 0).
Definition decoder_aided_redemod.h:220
double llrNorm(std::array< float, NBlades > const &llr)
Definition decoder_aided_redemod.h:710
MidpointResidual 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.
Definition decoder_aided_redemod.h:288
float aidedFrameXdt(float xdt2, int aidedDt, float dtSecondsPerSample)
Scalar frame timing seed from an aided timing delta.
Definition decoder_aided_redemod.h:236
ConfidenceSummary tentativeConfidences(std::array< float, kCodeBits > const &llr)
Confidence weight per tentative data symbol from its 3 bit LLRs.
Definition decoder_aided_redemod.h:155
bool symbolBoundsValid(std::array< SymbolBaseline, kTotalSymbols > const &baselines, int window, int numSamples, int maxAbsDelta)
Validate candidate sample bounds for the aided search/extraction.
Definition decoder_aided_redemod.h:354
constexpr int kTotalSymbols
Definition decoder_aided_redemod.h:53
constexpr int kMaxSyndrome
Definition decoder_aided_redemod.h:58
constexpr int kTones
Definition decoder_aided_redemod.h:55
void 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.
Definition decoder_aided_redemod.h:121
LDPC erasure threshold configuration and feedback helpers.
Costas::Type costas(int const submode)
Get the Costas array type of the submode.
Definition JS8Submode.cpp:258
constexpr char16_t normalize(char16_t const u) noexcept
Converts a lowercase character code point to uppercase if applicable.
Definition Maidenhead.h:35
constexpr auto valid(QStringView const view) noexcept
Assesses whether a complete string view matches acceptable grid lengths and constraints.
Definition Maidenhead.h:119
float channelLlr(float value)
Limits channel confidence so a contaminated strong symbol is correctable.
Definition bp_math.h:17
float checkMessage(float product)
Converts a check-node product to a finite extrinsic LLR.
Definition bp_math.h:25
int sicStartSample(float seconds)
Converts SIC timing to the nearest 12-kHz sample for fit and subtraction.
Definition sic_refinement.h:164
float llrGlobalScale()
Definition ldpc_feedback.h:41
void refineLlrsWithLdpcFeedback(std::array< float, N > const &llrIn, std::array< int8_t, N > const &cw, float erasureThreshold, std::array< float, N > &llrOut, int &confidentCount, int &uncertainCount)
Refine LLRs using a decoded LDPC codeword as feedback.
Definition ldpc_feedback.h:156
int ldpcFeedbackMaxPasses()
Maximum LDPC feedback passes to attempt.
Definition ldpc_feedback.h:118
bool ldpcFeedbackEnabled()
Whether LDPC feedback is enabled.
Definition ldpc_feedback.h:103
float llrErasureThreshold()
Read configured LLR erasure threshold.
Definition ldpc_feedback.h:74
Hardware-independent pressure signal for optional JS8 decode work.
Soft combiner for accumulating repeated LLR frames.
Definition decoder_cpu_benchmark.cpp:103
Definition JS8.h:116
Emitted when the decode process starts with the configured submodes.
Definition JS8.h:72
Global data structure used by the decoder.
Definition commons.h:63
int nfa
Definition commons.h:70
int nfb
Definition commons.h:71
int nfqso
Definition commons.h:68
bool syncStats
Definition commons.h:72
std::int16_t d2[JS8_RX_SAMPLE_SIZE]
Definition commons.h:64
int nutc
Definition commons.h:67
double trackerHz
FrequencyTracker estimate applied.
Definition coherent_likelihood.h:68
double timingShiftSamples
Effective extraction displacement.
Definition coherent_likelihood.h:67
double baseTimeSeconds
Nominal symbol-start time in seconds.
Definition coherent_likelihood.h:66
bool enabled
Coherent scores actually blended.
Definition coherent_likelihood.h:87
double alpha
Blend weight in [0,1].
Definition coherent_likelihood.h:92
int pilotCount
Valid pilot observations.
Definition coherent_likelihood.h:89
std::array< float, N > llr0
Combined LLR0 values.
Definition soft_combiner.h:68
double driftHzPerSec
Linear drift correction (Hz/s).
Definition decoder_aided_redemod.h:428
double deltaHz
Residual frequency correction (Hz).
Definition decoder_aided_redemod.h:427
int deltaSamples
Timing offset (downsampled samples).
Definition decoder_aided_redemod.h:426
Hypothesis best
Best hypothesis (baseline unless beaten strictly).
Definition decoder_aided_redemod.h:434
bool atBoundary
Best sits on the search box boundary.
Definition decoder_aided_redemod.h:439
Noise whitening and soft likelihoods used by the JS8 decoder.