20#include <QLoggingCategory>
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>
40#include <initializer_list>
50#include <unordered_map>
53#include <vendor/Eigen/Dense>
55Q_DECLARE_LOGGING_CATEGORY(decoder_js8);
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;
116 constexpr auto poly = [](
double const x) {
117 constexpr std::array coefficients = {
119 -0.49999999999999994,
120 0.041666666666666664,
121 -0.001388888888888889,
122 0.000024801587301587,
123 -0.00000027557319223986,
124 0.00000000208767569878681,
125 -0.00000000001147074513875176,
126 0.0000000000000477947733238733
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;
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;
146 x -=
static_cast<long long>(x / RAD_360) * RAD_360;
156 return x > RAD_90 ? -poly(RAD_180 - x) : poly(x);
187constexpr int N = 174;
189constexpr int M = N - K;
190constexpr int KK = 87;
191constexpr int ND = 58;
192constexpr int NS = 21;
193constexpr int NN = NS + ND;
194constexpr float ASYNCMIN = 1.5f;
195constexpr float ASYNCDEEP = 1.20f;
196constexpr float SOFT_COSTAS_MIN = 1.5f;
197constexpr int NFSRCH = 5;
198constexpr std::size_t NMAXCAND = 300;
199constexpr std::size_t NMAXDEEP = 24;
200constexpr int NFILT = 1400;
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};
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;
238 inline static constexpr float AZ = (12000.0f / NSPS) * 0.64f;
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;
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;
268 inline static constexpr float AZ = (12000.0f / NSPS) * 0.8f;
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;
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;
298 inline static constexpr float AZ = (12000.0f / NSPS) * 0.6f;
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;
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 =
326 inline static constexpr int NDOWNSPS = 32;
327 inline static constexpr int NDD = 94;
328 inline static constexpr int JZ = 32;
329 inline static constexpr float ASTART = 0.5f;
330 inline static constexpr float BASESUB = 42.0f;
333 inline static constexpr float AZ = (12000.0f / NSPS) * 0.64f;
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;
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;
363 inline static constexpr float AZ = (12000.0f / NSPS) * 0.64f;
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;
383constexpr auto BASELINE_DEGREE = 5;
384constexpr auto BASELINE_SAMPLE = 10;
389constexpr auto BASELINE_MIN = 500;
390constexpr auto BASELINE_MAX = 2500;
396static_assert(BASELINE_DEGREE & 1,
"Degree must be odd");
397static_assert(BASELINE_SAMPLE >= 0 && BASELINE_SAMPLE <= 100,
398 "Sample must be a percentage");
410constexpr auto BASELINE_NODES = []() {
417 auto nodes = std::array<double, BASELINE_DEGREE + 1>{};
418 constexpr auto slice = std::numbers::pi / (2.0 * nodes.size());
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)));
460template <std::
floating_po
int T>
class KahanSum {
465 KahanSum(T sum = T(0)) : m_sum(sum), m_compensation(T(0)) {}
467 KahanSum &operator=(T
const sum) {
469 m_compensation = T(0);
474 KahanSum &operator+=(T
const value) {
475 T
const y = value - m_compensation;
476 T
const t = m_sum + y;
478 m_compensation = (t - m_sum) - y;
484 operator T()
const {
return m_sum; }
489class FFTWPlanManager {
491 enum class Type { DS, BB, CF, CB, SD, CS, count };
495 FFTWPlanManager(FFTWPlanManager
const &) =
delete;
496 FFTWPlanManager &operator=(FFTWPlanManager
const &) =
delete;
497 FFTWPlanManager(FFTWPlanManager &&) =
delete;
498 FFTWPlanManager &operator=(FFTWPlanManager &&) =
delete;
502 FFTWPlanManager() { m_plans.fill(
nullptr); }
507 std::lock_guard<std::mutex> lock(fftw_mutex);
509 for (
auto &plan : m_plans) {
511 fftwf_destroy_plan(plan);
517 fftwf_plan
const &operator[](Type
const type)
const noexcept {
518 return m_plans[
static_cast<std::size_t
>(type)];
523 fftwf_plan &operator[](Type
const type)
noexcept {
524 return m_plans[
static_cast<std::size_t
>(type)];
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(); }
537 std::array<fftwf_plan, static_cast<std::size_t>(Type::count)> m_plans;
549 Sync(
float const freq,
float const step,
float const sync)
550 : freq(freq), step(step), sync(sync) {}
553struct SyncCandidates {
554 std::vector<Sync> normal;
555 std::vector<Sync> deep;
557 bool empty() const noexcept {
return normal.empty() && deep.empty(); }
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>,
588 Decode(
int type, std::string data) : type(type), data(std::move(data)) {}
590 bool operator==(Decode
const &)
const noexcept =
default;
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));
600 using Map = std::unordered_map<Decode, int, Hash>;
608constexpr int BP_MAX_ROWS = 7;
609constexpr int BP_MAX_CHECKS = 3;
610constexpr int BP_MAX_ITERATIONS = 30;
611constexpr int BP_RESCUE_ITERATIONS = 80;
612constexpr int BP_RESCUE_MAX_CHECKS = 12;
613constexpr int BP_RESCUE_BUDGET = 4;
614constexpr std::array<float, 3> BP_RESCUE_LLR_SCALES = {1.0f, 0.8f, 1.25f};
617 int maxIterations = BP_MAX_ITERATIONS;
618 bool earlyAbort =
true;
619 float llrScale = 1.0f;
620 std::function<bool()>
const *shouldCancel =
nullptr;
627 int bestChecks = M + 1;
628 bool earlyAborted =
false;
629 bool cancelled =
false;
635 std::array<int8_t, N> bestCw{};
636 bool bestCwValid =
false;
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}}};
678 std::array<int, BP_MAX_ROWS> neighbors;
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}}}};
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{};
778constexpr BPEdgeSlots BP_EDGE_SLOTS = [] {
780 constexpr std::uint8_t missing = 0xff;
781 for (
auto &row : edges.inBit)
783 for (
auto &row : edges.inCheck)
786 for (
int check = 0; check < M; ++check) {
787 if (Nm[check].valid_neighbors < 0 ||
788 Nm[check].valid_neighbors > BP_MAX_ROWS) {
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) {
799 for (
int bitEdge = 0; bitEdge < BP_MAX_CHECKS; ++bitEdge) {
800 if (Mn[bit][bitEdge] != check)
803 edges.inBit[check][edge] =
804 static_cast<std::uint8_t
>(bitEdge);
805 if (edges.inCheck[bit][bitEdge] != missing)
807 edges.inCheck[bit][bitEdge] =
808 static_cast<std::uint8_t
>(edge);
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)
821static_assert(BP_EDGE_SLOTS.valid,
822 "every BP edge must occur exactly once in both parity tables");
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;
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) {
843 auto const now = std::chrono::steady_clock::now();
844 counter += std::chrono::duration_cast<std::chrono::nanoseconds>(
850 std::array<float, N> scaledLlr = {};
851 for (
int i = 0; i < N; ++i)
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 = {};
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]];
870#ifdef JS8_CPU_BENCHMARK
872 phaseStarted = std::chrono::steady_clock::now();
876 for (
int iter = 0; iter <= options.maxIterations; ++iter) {
877 if (options.shouldCancel && (*options.shouldCancel)()) {
878 result.cancelled =
true;
881 result.iterations = iter;
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);
890 for (
int i = 0; i < N; ++i)
891 cw[i] = zn[i] > 0 ? 1 : 0;
892#ifdef JS8_CPU_BENCHMARK
893 recordPhase(benchmarkBpVariableNanos);
897 for (
int i = 0; i < M; ++i) {
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)
905 result.finalChecks = ncheck;
906 if (ncheck < result.bestChecks) {
907 result.bestChecks = ncheck;
909 result.bestCwValid =
true;
911#ifdef JS8_CPU_BENCHMARK
912 recordPhase(benchmarkBpSyndromeNanos);
916 std::copy(cw.begin() + M, cw.end(), decoded.begin());
919 for (
int i = 0; i < N; ++i) {
920 if ((2 * cw[i] - 1) * llr[i] < 0.0f)
924 result.hardErrors = nerr;
926 result.bestCwValid =
true;
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;
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];
951#ifdef JS8_BENCHMARK_LINEAR_BP_EDGES
952 for (
int k = 0; k < BP_MAX_CHECKS; ++k) {
954 toc[i][j] -= tov[ibj][k];
957 toc[i][j] -= tov[ibj][BP_EDGE_SLOTS.inBit[i][j]];
961#ifdef JS8_CPU_BENCHMARK
962 recordPhase(benchmarkBpBitToCheckNanos);
966 for (
int i = 0; i < M; ++i) {
967#ifdef JS8_BENCHMARK_FULL_BP_TANH
968 for (
int j = 0; j < 7; ++j)
971 for (
int j = 0; j < Nm[i].valid_neighbors; ++j)
973 tanhtoc[i][j] = std::tanh(-toc[i][j] / 2.0f);
975#ifdef JS8_CPU_BENCHMARK
976 recordPhase(benchmarkBpTanhNanos);
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];
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])
993 if (Nm[ichk].neighbors[k] != i)
995 Tmn *= tanhtoc[ichk][k];
1002 for (
int ichk = 0; ichk < M; ++ichk) {
1003 for (
int edge = 0; edge < Nm[ichk].valid_neighbors; ++edge) {
1005 for (
int k = 0; k < Nm[ichk].valid_neighbors; ++k)
1007 Tmn *= tanhtoc[ichk][k];
1008 int const bit = Nm[ichk].neighbors[edge];
1009 tov[bit][BP_EDGE_SLOTS.inBit[ichk][edge]] =
1014#ifdef JS8_CPU_BENCHMARK
1015 recordPhase(benchmarkBpCheckToBitNanos);
1031constexpr std::string_view alphabet =
1032 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-+";
1034static_assert(alphabet.size() == 64);
1041constexpr auto alphabetWord = []() {
1042 constexpr std::uint8_t invalid = 0xff;
1044 constexpr auto words = []() {
1045 std::array<std::uint8_t, 256> words{};
1047 for (
auto &word : words)
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);
1058 return [words](
char const value) {
1059 if (
auto const word = words[value]; word != invalid) {
1063 throw std::runtime_error(
"Invalid character in message");
1069static_assert(alphabetWord(
'0') == 0);
1070static_assert(alphabetWord(
'A') == 10);
1071static_assert(alphabetWord(
'a') == 36);
1072static_assert(alphabetWord(
'-') == 62);
1073static_assert(alphabetWord(
'+') == 63);
1075template <
typename T> std::uint16_t CRC12(T
const &range) {
1076 return boost::augmented_crc<12, 0xc06>(range.data(), range.size()) ^ 42;
1079bool checkCRC12(std::array<std::int8_t, KK>
const &decoded) {
1080 std::array<uint8_t, 11> bits = {};
1082 for (std::size_t i = 0; i < decoded.size(); ++i) {
1084 bits[i / 8] |= (1 << (7 - (i % 8)));
1089 uint16_t crc = (
static_cast<uint16_t
>(bits[9] & 0x1F) << 7) |
1090 (
static_cast<uint16_t
>(bits[10]) >> 1);
1099 return crc == CRC12(bits);
1102std::string extractmessage174(std::array<int8_t, KK>
const &decoded) {
1103 std::string message;
1107 if (checkCRC12(decoded)) {
1108 message.reserve(12);
1112 std::array<uint8_t, 12> words;
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);
1122 for (
auto const word : words)
1123 message += alphabet[word];
1147constexpr auto parity = []() {
1148 constexpr std::size_t Rows = 87;
1149 constexpr std::size_t Cols = 87;
1151 using ElementType = std::uint64_t;
1152 constexpr std::size_t ElementSize =
1153 std::numeric_limits<ElementType>::digits;
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"};
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};
1206 std::array<ElementType, Count> data{};
1208 for (std::size_t row = 0; row < Rows; ++row) {
1209 std::size_t col = 0;
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";
1218 for (
auto const mask : Masks) {
1222 auto const index = row * Cols + col;
1223 data[index / ElementSize] |=
1224 (ElementType(1) << (index % ElementSize));
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;
1247template <
typename Mode>
class DecodeMode {
1250 std::array<float, Mode::NFFT1> nuttal;
1251 using SyncWaveforms =
1252 std::array<std::array<std::array<std::complex<float>, Mode::NDOWNSPS>,
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;
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;
1276 bool m_normalizeLlrsForBenchmark =
1277 std::getenv(
"JS8_LLR_FRAME_NORMALIZATION") !=
nullptr;
1281 using Plan = FFTWPlanManager::Type;
1288 static constexpr auto Taper = [] {
1289 std::array<std::array<float, Mode::NDD + 1>, 2> taper{};
1291 for (
size_t i = 0; i <= Mode::NDD; ++i) {
1294 (1.0f + cos_approx(i * std::numbers::pi_v<float> / Mode::NDD));
1296 taper[1][i] = value;
1297 taper[0][Mode::NDD - i] = value;
1305 using Points = Eigen::Matrix<double, BASELINE_NODES.size(), 2>;
1307 Eigen::Matrix<double, BASELINE_NODES.size(), BASELINE_NODES.size()>;
1308 using Coefficients = Eigen::Vector<double, BASELINE_NODES.size()>;
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;
1325 ((baseline += (c[I * 2] + c[I * 2 + 1] * x) * exponent,
1329 return static_cast<float>(baseline);
1330 }(x, std::make_integer_sequence<Eigen::Index,
1331 Coefficients::SizeAtCompileTime / 2>{});
1335 struct ToneBinLlrs {
1336 std::array<float, N> llr0;
1337 std::array<float, N> llr1;
1338 js8::CoherentLikelihoodTelemetry coherentTelemetry;
1347 ToneBinLlrs processToneBins(
1348 std::array<std::array<float, NN>, NROWS>
const &s2,
1349 std::array<std::array<std::complex<float>, NN>, NROWS>
const
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};
1358 constexpr float FS2 = 12000.0f / Mode::NDOWN;
1360 std::array<std::array<float, ND>, NROWS> s1;
1364 for (
int row = 0; row < NROWS; ++row) {
1365 std::copy(s2[row].begin() + 7, s2[row].begin() + 36,
1367 std::copy(s2[row].begin() + 43, s2[row].begin() + 72,
1368 s1[row].begin() + 29);
1372 std::array<int, ND> symbolWinners = {};
1374 for (
int j = 0; j < ND; ++j) {
1376 float best = s1[0][j];
1378 for (
int i = 1; i < NROWS; ++i) {
1379 if (s1[i][j] > best) {
1385 symbolWinners[j] = winner;
1388 std::optional<js8::CoherentBlend<NROWS, ND>> coherentBlend;
1389 js8::CoherentLikelihoodTelemetry coherentTelemetry;
1391 if (m_enableCoherentData) {
1392 static_assert(NROWS == 8,
"coherent path expects 8 FSK tones");
1393 double const downsampledRate =
1394 static_cast<double>(FS2);
1399 std::vector<js8::CoherentPilot> pilots;
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))
1413 double const startSeconds =
1414 static_cast<double>(
1415 symbolBaseStarts[symbolIndex]) /
1417 if (!std::isfinite(startSeconds))
1419 pilots.push_back(js8::CoherentPilot{
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)];
1431 bool const pilotCoverage = blockValid[0] >= 4 &&
1432 blockValid[1] >= 4 &&
1434 if (pilotCoverage) {
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;
1445 double const startSeconds =
1446 static_cast<double>(
1447 symbolBaseStarts[symbolIndex]) /
1449 if (!std::isfinite(startSeconds)) {
1453 js8::CoherentDataSymbol dataSymbol;
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];
1463 dataSymbol.bins[
static_cast<std::size_t
>(tone)]
1466 dataSymbol.bins[
static_cast<std::size_t
>(tone)]
1472 dataSymbols.push_back(dataSymbol);
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])) /
1482 if (std::isfinite(frameSpanSeconds) &&
1483 frameSpanSeconds > 0.0) {
1484#ifdef JS8_CPU_BENCHMARK
1485 auto const coherentStarted =
1486 std::chrono::steady_clock::now();
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() -
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;
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;
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);
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);
1547 auto llr0 = whitening.llr0;
1548 auto llr1 = whitening.llr1;
1552 if (!whitening.erasureApplied) {
1553 std::size_t erasuresAfterThreshold = 0;
1554 double sumAbsPreErasure = 0.0;
1555 double sumAbsPostErasure = 0.0;
1557 auto const applyErasureThreshold = [&](
auto &llr) {
1558 for (
auto const value : llr)
1559 sumAbsPreErasure += std::abs(value);
1561 if (m_llrErasureThreshold > 0.0f) {
1562 for (
auto &value : llr) {
1563 if (std::abs(value) < m_llrErasureThreshold) {
1565 ++erasuresAfterThreshold;
1568 sumAbsPostErasure += std::abs(value);
1571 for (
auto const value : llr)
1572 sumAbsPostErasure += std::abs(value);
1576 applyErasureThreshold(llr0);
1577 applyErasureThreshold(llr1);
1579 if (decoder_js8().isDebugEnabled()) {
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;
1587 qCDebug(decoder_js8)
1588 <<
"LLR erasure threshold" << m_llrErasureThreshold
1589 <<
"erasures:" << erasuresAfterThreshold
1590 <<
"avg|LLR| pre/post:" << avgPre << avgPost;
1597 out.coherentTelemetry = coherentTelemetry;
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};
1610 constexpr float FR = 12000.0f / Mode::NFFT1;
1611 constexpr float FS2 = 12000.0f / Mode::NDOWN;
1612 constexpr float DT2 = 1.0f / FS2;
1614 float const coarseStartHz = f1;
1615 float const coarseStartDt = xdt;
1618 static_cast<int>(std::round(f1 / FR));
1619 float const scaled_value =
1620 0.1f * (savg[index] - Mode::BASESUB);
1622 std::pow(10.0f, scaled_value);
1624 float delfbest = 0.0f;
1631 int i0 =
static_cast<int>(std::round((xdt + Mode::ASTART) * FS2));
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;
1644 float const xdt2 = ibest * DT2;
1646 i0 =
static_cast<int>(std::round(xdt2 * FS2));
1649 for (
int ifr = -NFSRCH; ifr <= NFSRCH; ++ifr) {
1650 float const delf = ifr * 0.5f;
1651 float const candidateSync = syncjs8d(i0, delf);
1653 if (candidateSync > smax) {
1654 smax = candidateSync;
1661 float const dphi = -delfbest * ((2.0f * std::numbers::pi_v<float>) /
1663 std::complex<float>
const wstep =
1664 std::polar(1.0f, dphi);
1665 std::complex<float> w = {1.0f, 0.0f};
1667 for (
int i = 0; i < NP2; ++i) {
1677 float const sync = syncjs8d(i0, 0.0f);
1679 std::array<std::array<float, NN>, NROWS> s2;
1683 std::array<std::array<std::complex<float>, NN>, NROWS> complexS2;
1687 std::array<int, NN> symbolBaseStarts;
1688 std::array<int, NN> symbolTimingShifts;
1689 std::array<float, NN> symbolTrackerHz;
1691 js8::FrequencyTracker freqTracker;
1692 if (m_enableFreqTracking) {
1693 freqTracker.
reset(0.0, FS2);
1700 double const timingMaxShift =
1701 std::clamp(0.08 *
static_cast<double>(Mode::NDOWNSPS), 0.5, 2.0);
1703 js8::TimingTracker timingTracker;
1704 if (m_enableTimingTracking) {
1705 timingTracker.
reset(0.0, 0.15, 0.35, timingMaxShift);
1710 auto const estimateResidualHz =
1711 [&](
int expectedTone) -> std::optional<float> {
1713 return std::nullopt;
1715 if (expectedTone < 0 || expectedTone + 1 >= Mode::NDOWNSPS)
1716 return std::nullopt;
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;
1724 return std::nullopt;
1726 float const ratio = m0 / (mplus + mminus + 1e-12f);
1728 return std::nullopt;
1730 float const denom = mminus - 2.0f * m0 + mplus;
1731 if (std::abs(denom) < 1e-9f)
1732 return std::nullopt;
1734 float delta = 0.5f * (mminus - mplus) / denom;
1735 delta = std::clamp(delta, -0.5f, 0.5f);
1737 return delta * (FS2 / Mode::NDOWNSPS);
1740 auto const logTracker = [&](
char const *tag) {
1741 if (decoder_js8().isDebugEnabled()) {
1743 qCDebug(decoder_js8)
1744 <<
"freqTracker" << tag <<
"coarseHz" << coarseStartHz
1745 <<
"fineHz" << f1 <<
"refinedHz"
1746 << f1 +
static_cast<float>(freqTracker.
currentHz())
1751 if (timingTracker.
enabled()) {
1752 qCDebug(decoder_js8)
1753 <<
"timingTracker" << tag <<
"coarseDt" << coarseStartDt
1754 <<
"fineDt" << xdt <<
"refinedDt"
1755 << xdt +
static_cast<float>(
1758 <<
static_cast<float>(
1764 auto const goertzelEnergy =
1765 [&](
int start,
int expectedTone) -> std::optional<float> {
1766 if (start < 0 || start + Mode::NDOWNSPS > NP2)
1767 return std::nullopt;
1769 std::array<std::complex<float>, Mode::NDOWNSPS> tmp;
1770 std::copy(cd0.begin() + start, cd0.begin() + start + Mode::NDOWNSPS,
1774 freqTracker.
apply(tmp.data(), Mode::NDOWNSPS);
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};
1782 for (
auto const &sample : tmp) {
1783 acc += sample * std::conj(phase);
1787 return std::norm(acc);
1790#ifdef JS8_CPU_BENCHMARK
1792 BenchmarkScope benchmarkScope{benchmarkDemodCalls,
1793 benchmarkDemodNanos};
1795 for (
int k = 0; k < NN; ++k) {
1798 int const i1Base = ibest + k * Mode::NDOWNSPS;
1799 int const timingShift = timingTracker.
enabled()
1800 ?
static_cast<int>(std::round(
1803 int i1 = i1Base + timingShift;
1807 }
else if (i1 + Mode::NDOWNSPS > NP2) {
1808 i1 = NP2 - Mode::NDOWNSPS;
1813 if (i1 >= 0 && i1 + Mode::NDOWNSPS <= NP2) {
1814 std::copy(cd0.begin() + i1, cd0.begin() + i1 + Mode::NDOWNSPS,
1818 freqTracker.
apply(csymb.data(), Mode::NDOWNSPS);
1822 fftwf_execute(plans[Plan::CS]);
1826 for (
int i = 0; i < NROWS; ++i) {
1827 s2[i][k] = std::abs(csymb[i]) / 1000.0f;
1830 if (m_enableCoherentData) {
1831 for (
int i = 0; i < NROWS; ++i)
1832 complexS2[i][k] = csymb[i] / 1000.0f;
1834 symbolBaseStarts[k] = i1Base;
1835 symbolTimingShifts[k] = i1 - i1Base;
1836 symbolTrackerHz[k] = freqTracker.
enabled()
1837 ?
static_cast<float>(freqTracker.
currentHz())
1841 bool const isPilot =
1842 (k < 7) || (k >= 36 && k < 43) || (k >= 72 && k < 79);
1845 int costasBlock = 0;
1846 int costasColumn = k;
1848 if (k >= 36 && k < 43) {
1850 costasColumn = k - 36;
1851 }
else if (k >= 72 && k < 79) {
1853 costasColumn = k - 72;
1856 int const expectedTone = Costas[costasBlock][costasColumn];
1858 if (
auto const residual =
1859 estimateResidualHz(expectedTone)) {
1860 freqTracker.
update(*residual);
1863 if (timingTracker.
enabled()) {
1864 auto const e0 = goertzelEnergy(i1, expectedTone);
1866 goertzelEnergy(i1 - 1, expectedTone);
1867 auto const eLate = goertzelEnergy(i1 + 1, expectedTone);
1869 float const toneMag = s2[expectedTone][k];
1871 if (e0 && eEarly && eLate && toneMag > 1e-6f) {
1872 float const denom = *e0 + 1e-6f;
1873 float const grad = (*eLate - *eEarly) / denom;
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);
1881 timingTracker.
update(errorSamples, weight);
1887#ifdef JS8_CPU_BENCHMARK
1895 double expectedPower = 0.0;
1896 double alternativePower = 0.0;
1898 for (std::size_t costas = 0;
costas < Costas.size(); ++
costas) {
1899 auto const offset =
costas * 36;
1901 for (std::size_t column = 0; column < 7; ++column) {
1902 auto const symbolIndex = offset + column;
1903 int const expectedTone = Costas[
costas][column];
1905 auto const max_row = std::distance(
1907 std::max_element(s2.begin(), s2.end(),
1908 [symbolIndex](
auto const &rowA,
1910 return rowA[symbolIndex] <
1914 if (expectedTone == max_row)
1917 for (
int tone = 0; tone < NROWS; ++tone) {
1918 double const magnitude = s2[tone][symbolIndex];
1919 double const power = magnitude * magnitude;
1921 if (tone == expectedTone)
1922 expectedPower += power;
1924 alternativePower += power;
1929 float const softCostas =
static_cast<float>(
1930 expectedPower / (alternativePower / 7.0 + 1e-12));
1932 if (decoder_js8().isDebugEnabled()) {
1933 qCDebug(decoder_js8)
1934 <<
"symbol sync" << sync <<
"residualHz" << delfbest
1935 <<
"nsync" << nsync <<
"softCostas" << softCostas;
1939 (!optionalCandidate || !std::isfinite(softCostas) ||
1940 softCostas < SOFT_COSTAS_MIN)) {
1941 logTracker(
"sync_fail");
1942 return std::nullopt;
1948 if (optionalCandidate && optional && optional->stop())
1949 return std::nullopt;
1953 JS8::Event::SyncState{JS8::Event::SyncState::Type::CANDIDATE,
1957 {.candidate = nsync}});
1962 ToneBinLlrs
const toneBins = processToneBins(
1963 s2, complexS2, symbolBaseStarts, symbolTimingShifts,
1965 auto llr0 = toneBins.llr0;
1966 auto llr1 = toneBins.llr1;
1968 auto const ttl = std::chrono::seconds{Mode::NTXDUR * 2};
1970 m_softCombiner.
flush(ttl);
1973 m_softCombiner.
makeKey(Mode::NSUBMODE, f1, xdt, llr0, llr1);
1974 auto combined = m_softCombiner.
combine(key, llr0, llr1, ttl);
1976 auto llr0Combined = combined.
llr0;
1977 auto llr1Combined = combined.llr1;
1979 std::array<int8_t, K> decoded = {};
1980 std::array<int8_t, N> cw = {};
1981 std::array<float, N> bestRescueLlr = {};
1985 std::array<int8_t, N> bestRescueCw = {};
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;
1996#ifndef JS8_BENCHMARK_DISABLE_BP_CACHE
1999 std::array<float, N> input{};
2000 BPOptions options{};
2002 std::array<int8_t, N> word{};
2003 std::array<int8_t, K> decoded{};
2005 std::array<BPSnapshot, 2> firstPassBP{};
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;
2021 bestRescueCw = bp.bestCw;
2031 struct FinalizeSync {
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> {
2044 std::array<int8_t, N> savedCw{};
2045 std::array<int8_t, K> savedDecoded{};
2046 if (options.shouldCancel) {
2048 savedDecoded = decoded;
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) {
2063 if (bp.hardErrors >= 0)
2064 decoded = saved.decoded;
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};
2085 decoded = savedDecoded;
2088 return std::nullopt;
2090 if (bpOut !=
nullptr)
2092 nharderrors = bp.hardErrors;
2095 if (rememberForRescue)
2096 rememberRescueInput(llrInput, ipass, bp);
2098 if (std::all_of(cw.begin(), cw.end(),
2099 [](
int x) { return x == 0; })) {
2100 return std::nullopt;
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)) {
2111 FinalizeSync
const fs =
2112 finalize.value_or(FinalizeSync{f1, xdt2});
2114 emitEvent(JS8::Event::SyncState{
2115 JS8::Event::SyncState::Type::DECODED,
2119 {.decoded = sync}});
2121 auto message = extractmessage174(decoded);
2124 (decoded[72] << 2) | (decoded[73] << 1) | decoded[74];
2126 std::array<int, NN> itone;
2128 JS8::encode(i3bit, Costas, message.data(), itone.data());
2131 subtractjs8(genjs8refsig(itone, fs.frequencyHz),
2136 for (std::size_t i = 0; i < itone.size(); ++i)
2137 xsig += std::pow(s2[itone[i]][i], 2);
2140 std::max(10.0f * std::log10(std::max(
2141 xsig / xbase - 1.0f, 1.259e-10f)) -
2147 logTracker(
"decoded");
2148 return std::make_optional<Decode>(i3bit, message);
2154 return std::nullopt;
2160 for (
int ipass = 1; ipass <= 4 && totalLdpcPasses < m_maxLdpcPasses;
2162 auto &llr = ipass == 2 ? llr1Combined : llr0Combined;
2165 std::fill(llr0Combined.begin(), llr0Combined.begin() + 24,
2167 else if (ipass == 4)
2168 std::fill(llr0Combined.begin() + 24, llr0Combined.begin() + 48,
2171 std::array<float, N> llrPrimary = llr;
2173 tryDecode(llrPrimary, ipass, BPOptions{},
true)) {
2179 if (m_enableLdpcFeedback && totalLdpcPasses < m_maxLdpcPasses) {
2180 std::array<float, N> llrRefined;
2184 llrPrimary, cw, m_llrErasureThreshold, llrRefined,
2185 confident, uncertain);
2187 if (decoder_js8().isDebugEnabled()) {
2188 qCDebug(decoder_js8)
2189 <<
"LDPC feedback pass"
2190 <<
"ipass" << ipass <<
"confident" << confident
2191 <<
"uncertain" << uncertain;
2194 usedFeedbackPass =
true;
2195 feedbackConfident += confident;
2196 feedbackUncertain += uncertain;
2199 tryDecode(llrRefined, ipass, BPOptions{},
true)) {
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;
2219 bool const rescueEligible = m_enableLdpcRescue && ldpcRescueBudget > 0 &&
2220 bestRescuePass > 0 &&
2221 bestRescueChecks <= BP_RESCUE_MAX_CHECKS;
2222 bool const rescueAllowed =
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();
2230 rescueAttempted =
true;
2231 std::function<bool()>
const cancelRescue = [optional] {
2232 return optional && optional->stop();
2235 if (decoder_js8().isDebugEnabled()) {
2236 qCDebug(decoder_js8)
2237 <<
"LDPC rescue start"
2238 <<
"bestChecks" << bestRescueChecks
2239 <<
"ipass" << bestRescuePass
2240 <<
"budgetRemaining" << ldpcRescueBudget;
2243 for (
float const scale : BP_RESCUE_LLR_SCALES) {
2244 if (optional && optional->stop())
2247 options.maxIterations = BP_RESCUE_ITERATIONS;
2248 options.earlyAbort =
false;
2249 options.llrScale = scale;
2250 options.shouldCancel = optional ? &cancelRescue :
nullptr;
2258 if (
auto result = tryDecode(bestRescueLlr, bestRescuePass,
2259 options,
true, &rescueBp)) {
2261 optional->observe(js8::OptionalStage::Rescue,
2263 if (decoder_js8().isDebugEnabled()) {
2264 qCDebug(decoder_js8)
2265 <<
"LDPC rescue succeeded"
2267 <<
"bestChecks" << bestRescueChecks;
2271 if (rescueBp.cancelled)
2275 optional->observe(js8::OptionalStage::Rescue, rescueStarted);
2291 bool const aidedEligible = m_enableAidedRedemod &&
2292 bestRescueChecks > 0 &&
2295 bool const aidedAllowed =
2297 (!optional || optional->allow(js8::OptionalStage::Aided));
2298 if (aidedEligible && !aidedAllowed)
2299 qCDebug(decoder_js8) <<
"adaptive optional skip aided";
2301 auto const aidedStarted = js8::OptionalWorkBudget::Clock::now();
2306 "aided helper sizes must match decoder");
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);
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)];
2330 bool const boundsOk =
2332 aidedBaselines, Mode::NDOWNSPS, NP2,
2333 js8::aided::kTimingDeltaMax);
2336 int const skipCode =
2337 !tentValid ? 1 : (!boundsOk ? 2 : 0);
2339 std::optional<Decode> aidedResult;
2341 double aidedMeanConf = 0.0;
2343 double aidedDf = 0.0;
2344 double aidedDd = 0.0;
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;
2365 double aidedLlrNorm = 0.0;
2368 std::array<int, NN> expectedTones{};
2373 std::array<float, NN> symWeights{};
2375 aidedUsed = conf.used;
2376 aidedMeanConf = conf.mean;
2378#ifdef JS8_CPU_BENCHMARK
2379 auto const refinementStarted =
2380 std::chrono::steady_clock::now();
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)
2394 aidedBase = refinement.baselineMetric;
2395 aidedRef = refinement.
best.metric;
2396 aidedBoundary = refinement.
atBoundary ? 1 : 0;
2404 if (js8::aided::refinementAccepted(refinement) &&
2405 (!optional || !optional->stop())) {
2417 std::array<std::array<float, NN>, NROWS> s2Aided{};
2418 std::array<std::array<std::complex<float>, NN>, NROWS>
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;
2431 }
else if (i1 + Mode::NDOWNSPS > NP2) {
2432 i1 = NP2 - Mode::NDOWNSPS;
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)) {
2448 for (
int n = 0; n < Mode::NDOWNSPS; ++n) {
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);
2459 fftwf_execute(plans[Plan::CS]);
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
>(
2467 complexAided[
static_cast<std::size_t
>(i)]
2468 [
static_cast<std::size_t
>(k)] =
2469 csymb[
static_cast<std::size_t
>(
2478 ToneBinLlrs
const aidedBins = processToneBins(
2479 s2Aided, complexAided, baseStartsAided, shiftsAided,
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);
2501 float aidedXdtOut = xdt2;
2502 if (std::isfinite(xdtCand) && mid.valid) {
2503 aidedXdtOut = xdtCand;
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;
2512 aidedFinalizeSync = FinalizeSync{aidedF1, aidedXdtOut};
2521 int const savedNhard = nharderrors;
2522 float const savedXsnr = xsnr;
2523 auto const savedS2 = s2;
2525 int aidedBest = M + 1;
2527 std::function<bool()>
const cancelAided = [optional] {
2528 return optional && optional->stop();
2530 BPOptions aidedOptions;
2531 aidedOptions.shouldCancel = optional ? &cancelAided :
nullptr;
2532 if (
auto res = tryDecode(aidedBins.llr0, 1, aidedOptions,
2534 aidedFinalizeSync)) {
2535 aidedBest = aidedBp.bestChecks;
2538 }
else if (!aidedBp.cancelled) {
2539 aidedBest = std::min(aidedBest, aidedBp.bestChecks);
2546 if (m_enableLdpcRescue && ldpcRescueBudget > 0 &&
2548 optional->allow(js8::OptionalStage::Rescue))) {
2550 for (
float const scale : BP_RESCUE_LLR_SCALES) {
2551 if (optional && optional->stop())
2555 options.maxIterations = BP_RESCUE_ITERATIONS;
2556 options.earlyAbort =
false;
2557 options.llrScale = scale;
2558 options.shouldCancel =
2559 optional ? &cancelAided :
nullptr;
2562 tryDecode(aidedBins.llr0, 1, options,
2564 aidedFinalizeSync)) {
2565 aidedBest = std::min(aidedBest,
2566 retryBp.bestChecks);
2568 aidedResult = retry;
2571 if (retryBp.cancelled)
2573 aidedBest = std::min(aidedBest,
2574 retryBp.bestChecks);
2578 aidedBestChecks = aidedBest <= M ? aidedBest : -1;
2579 aidedBudgetAfter = ldpcRescueBudget;
2584 nharderrors = savedNhard;
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
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"
2617 optional->observe(js8::OptionalStage::Aided, aidedStarted);
2622 FinalizeSync
const fs = aidedFinalizeSync.value_or(
2623 FinalizeSync{f1, xdt2});
2624 f1 = fs.frequencyHz;
2625 xdt = fs.xdtSeconds;
2629 optional->observe(js8::OptionalStage::Aided, aidedStarted);
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;
2643 return std::nullopt;
2667 void baselinejs8(
int const ia,
int const ib) {
2668#ifdef JS8_CPU_BENCHMARK
2669 BenchmarkScope benchmarkScope{benchmarkBaselineCalls,
2670 benchmarkBaselineNanos};
2677 using boost::math::ccmath::round;
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());
2689 auto const data = savg.begin() + bmin;
2690 auto const end = data + size;
2694 std::transform(data, end, data, [](
float const value) {
2695 return 10.0f * std::log10(value);
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));
2707 auto const n = span.size() * BASELINE_SAMPLE / 100;
2709 std::nth_element(span.begin(), span.begin() + n, span.end());
2711 p.row(i) << node, span[n];
2718 Eigen::VectorXd x = p.col(0);
2719 Eigen::VectorXd y = p.col(1);
2722 for (Eigen::Index i = 1; i < V.cols(); ++i) {
2723 V.col(i) = V.col(i - 1).cwiseProduct(x);
2728 c = V.colPivHouseholderQr().solve(y);
2737 auto const mapIndex = [ia, ib, last = size - 1](
int const i) {
2738 return (i - ia) * last / float(ib - ia);
2749 for (
int i = ia; i <= ib; ++i) {
2750 savg[i] = evaluate(mapIndex(i)) + 0.65f;
2761 void computeBasebandFFT() {
2762#ifdef JS8_CPU_BENCHMARK
2763 BenchmarkScope benchmarkScope{benchmarkBasebandCalls,
2764 benchmarkBasebandNanos};
2770 float *fftw_real =
reinterpret_cast<float *
>(ds_cx.data());
2775 std::copy(dd.begin(), dd.end(), fftw_real);
2776 std::fill(fftw_real + dd.size(), fftw_real + Mode::NDFFT1, 0.0f);
2778 fftwf_execute(plans[Plan::BB]);
2787 void js8_downsample(
float const f0) {
2788#ifdef JS8_CPU_BENCHMARK
2789 BenchmarkScope benchmarkScope{benchmarkDownsampleCalls,
2790 benchmarkDownsampleNanos};
2798 constexpr float DF = 12000.0f / Mode::NDFFT1;
2799 constexpr float BAUD = 12000.0f / Mode::NSPS;
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));
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)));
2808 std::size_t
const NDD_SIZE = Mode::NDD + 1;
2809 std::size_t
const RANGE_SIZE = it - ib + 1;
2811 std::fill_n(cd0.begin(), Mode::NDFFT2, ZERO);
2813 std::copy(ds_cx.begin() + ib, ds_cx.begin() + ib + RANGE_SIZE,
2820 auto const head = cd0.begin();
2821 auto const tail = cd0.begin() + RANGE_SIZE;
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<>());
2832 std::rotate(cd0.begin(), cd0.begin() + (i0 - ib),
2833 cd0.begin() + Mode::NDFFT2);
2840 fftwf_execute(plans[Plan::DS]);
2846 float const factor =
2847 1.0f / std::sqrt(
static_cast<float>(Mode::NDFFT1) * Mode::NDFFT2);
2849 std::transform(cd0.begin(), cd0.end(), cd0.begin(),
2850 [factor](
auto &value) { return value * factor; });
2924 SyncCandidates syncjs8(
int nfa,
int nfb) {
2925#ifdef JS8_CPU_BENCHMARK
2926 BenchmarkScope benchmarkScope{benchmarkCandidateGenCalls,
2927 benchmarkCandidateGenNanos};
2933#ifdef JS8_CPU_BENCHMARK
2935 BenchmarkScope benchmarkScope{benchmarkSpectrumCalls,
2936 benchmarkSpectrumNanos};
2938 for (
int j = 0; j < Mode::NHSYM; ++j) {
2939 int const ia = j * Mode::NSTEP;
2940 int const ib = ia + Mode::NFFT1;
2942 if (ib > Mode::NMAX)
2945 std::transform(dd.begin() + ia, dd.begin() + ib, nuttal.begin(),
2946 reinterpret_cast<float *
>(sd.data()),
2947 std::multiplies<float>{});
2949 fftwf_execute(plans[Plan::SD]);
2953 for (
int i = 0; i < Mode::NSPS; ++i) {
2954 auto const power = std::norm(sd[i]);
2959#ifdef JS8_CPU_BENCHMARK
2965 int const nwin = nfb - nfa;
2980 std::max(0,
static_cast<int>(std::round(nfa / Mode::DF)));
2981 auto const ib =
static_cast<int>(std::round(nfb / Mode::DF));
2986 baselinejs8(ia, ib);
2990#ifdef JS8_BENCHMARK_VERIFY_RANK_SCAN
2991 std::uint64_t comparedScores = 0;
2993#ifdef JS8_CPU_BENCHMARK
2995 BenchmarkScope benchmarkScope{benchmarkRankScoreCalls,
2996 benchmarkRankScoreNanos};
3000 for (
int i = ia; i <= ib; ++i) {
3001 float max_value = -std::numeric_limits<float>::infinity();
3002 int max_index = -Mode::JZ;
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{};
3008 for (
int p = 0; p < 3; ++p) {
3009 for (
int n = 0; n < 7; ++n) {
3011 j + Mode::JSTRT + NSSY * n + p * 36 * NSSY;
3013 if (offset >= 0 && offset < Mode::NHSYM) {
3016 t[0][p] += s[i + NFOS * Costas[p][n]][offset];
3021 for (
int freq = 0; freq < 7; ++freq) {
3022 t[1][p] += s[i + NFOS * freq][offset];
3035 auto const compute_sync = [&t](
int start,
int end) {
3039 for (
int i = start; i <= end; ++i) {
3044 return tx / ((t0 - tx) / 6.0f);
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;
3061 std::array<std::array<std::array<float, 3>, 2>,
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);
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];
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) {
3085 for (
int block = start; block <= end; ++block) {
3089 return tx / ((t0 - tx) / 6.0f);
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
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) {
3102 j + Mode::JSTRT + NSSY * n + p * 36 * NSSY;
3103 if (offset >= 0 && offset < Mode::NHSYM) {
3105 s[i + NFOS * Costas[p][n]][offset];
3106 for (
int freq = 0; freq < 7; ++freq)
3108 s[i + NFOS * freq][offset];
3111 auto const originalSync = [&original](
int start,
int end) {
3114 for (
int block = start; block <= end; ++block) {
3115 tx += original[0][block];
3116 t0 += original[1][block];
3118 return tx / ((t0 - tx) / 6.0f);
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;
3127 if (sync_value > max_value) {
3128 max_value = sync_value;
3134 sync.emplace(Mode::DF * i, Mode::TSTEP * (max_index + 0.5f),
3137#ifdef JS8_BENCHMARK_VERIFY_RANK_SCAN
3138 benchmarkRankComparedScores += comparedScores;
3140#ifdef JS8_CPU_BENCHMARK
3142 BenchmarkScope benchmarkIndexScope{benchmarkRankIndexCalls,
3143 benchmarkRankIndexNanos};
3153 auto &freqIndex = sync.get<Tag::Freq>();
3154 auto &rankIndex = sync.get<Tag::Rank>();
3155 auto &syncIndex = sync.get<Tag::Sync>();
3165 [sync = rankIndex.nth(rankIndex.size() * 4 / 10)->sync](
3166 Sync &entry) { entry.sync /= sync; };
3168 for (
auto it = freqIndex.begin(); it != freqIndex.end(); ++it) {
3169 freqIndex.modify(it, normalize);
3180 for (
auto it = syncIndex.begin(); it != syncIndex.end();
3181 it = syncIndex.begin()) {
3182 if (std::isnan(it->sync) || it->sync < ASYNCDEEP)
3185 if (it->sync >= ASYNCMIN) {
3191 if (!m_enableDeepSearch ||
candidates.deep.size() >= NMAXDEEP)
3201 freqIndex.erase(freqIndex.lower_bound(it->freq - Mode::AZ),
3202 freqIndex.upper_bound(it->freq + Mode::AZ));
3216 float syncjs8d(
int const i0,
float const delf) {
3217#ifdef JS8_CPU_BENCHMARK
3218 BenchmarkScope benchmarkScope{benchmarkSyncCalls, benchmarkSyncNanos};
3220 constexpr float BASE_DPHI = TAU * (1.0f / (12000.0f / Mode::NDOWN));
3221 std::array<std::complex<float>, Mode::NDOWNSPS> freqAdjust;
3223 float const dphi = BASE_DPHI * delf;
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)
3231 freqAdjust.fill(std::complex<float>{1.0f, 0.0f});
3234 float syncPower = 0.0f;
3235 for (
int block = 0; block < 3; ++block) {
3236 for (
int symbol = 0; symbol < 7; ++symbol) {
3238 36 * block * Mode::NDOWNSPS + i0 + symbol * Mode::NDOWNSPS;
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]]);
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};
3271 float const BFPI = TAU * f0 * (1.0f / 12000.0f);
3274 std::vector<std::complex<float>> cref;
3275 cref.reserve(NN * Mode::NSPS);
3277 for (
int i = 0; i < NN; ++i) {
3282 BFPI + TAU *
static_cast<float>(itone[i]) / Mode::NSPS;
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);
3305 void subtractjs8(std::vector<std::complex<float>>
const &cref,
3307#ifdef JS8_CPU_BENCHMARK
3308 BenchmarkScope benchmarkScope{benchmarkSicCalls, benchmarkSicNanos};
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;
3316 if (cref_start >= cref.size() || dd_start >= dd.size())
3320 std::min(cref.size() - cref_start, dd.size() - dd_start);
3327 auto const mixed = [&](std::size_t i) -> std::complex<float> {
3328 return dd[dd_start + i] * std::conj(cref[cref_start + i]);
3333 for (std::size_t i = 0; i < size; ++i) {
3334 cfilt[i] = mixed(i);
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]);
3349 std::vector<std::complex<float>> mixedVec(size);
3350 for (std::size_t i = 0; i < size; ++i)
3351 mixedVec[i] = mixed(i);
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);
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);
3379 std::vector<std::complex<float>> smoothed(windowCount, ZERO);
3380 for (std::size_t w = 0; w < windowCount; ++w) {
3381 std::complex<double> acc{};
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))
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()} *
3395 smoothed[w] = std::complex<float>{
static_cast<float>(acc.real() / wt),
3396 static_cast<float>(acc.imag() / wt)};
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])
3410 if (segment + 1 >= windowCount || sample <= centers[segment]) {
3411 segmented[i] = smoothed[segment];
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)};
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);
3440 return std::accumulate(after.begin(), after.end(), 0.0,
3441 [](
double const t,
auto const &v) {
3442 return t + std::norm(v);
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);
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);
3465 double const beforeMetric = correlationPower(beforeCorrelation);
3466 double const afterMetricLpf = afterMetricOf(cfilt);
3467 double const afterMetricAdaptive = afterMetricOf(segmented);
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;
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()))
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;
3517 for (std::size_t i = 0; i < size; ++i) {
3519 2.0f * std::real(segmented[i] * cref[cref_start + i]);
3522 for (std::size_t i = 0; i < size; ++i) {
3524 2.0f * std::real(cfilt[i] * cref[cref_start + i]);
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;
3552 constexpr float a0 = 0.3635819f;
3553 constexpr float a1 = -0.4891775f;
3554 constexpr float a2 = 0.1365995f;
3555 constexpr float a3 = -0.0106411f;
3561 float const pi = 4.0f * std::atan(1.0f);
3564 for (std::size_t i = 0; i < nuttal.size(); ++i) {
3569 KahanSum value = a0;
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());
3581 for (
auto &value : nuttal)
3582 value = value / sum * nuttal.size() / 300.0f;
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;
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);
3600 phia = std::fmod(phia + dphia, TAU);
3601 phib = std::fmod(phib + dphib, TAU);
3602 phic = std::fmod(phic + dphic, TAU);
3612 for (
int j = -NFILT / 2; j <= NFILT / 2; ++j)
3613 sum += std::pow(std::cos(pi * j / NFILT), 2);
3616 for (
int j = -NFILT / 2; j <= NFILT / 2; ++j) {
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);
3627 fftwf_plan fftw_plan;
3629 std::lock_guard<std::mutex> lock(fftw_mutex);
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);
3637 throw std::runtime_error(
"Failed to create FFT plan");
3641 fftwf_execute(fftw_plan);
3644 std::lock_guard<std::mutex> lock(fftw_mutex);
3645 fftwf_destroy_plan(fftw_plan);
3650 std::transform(filter.begin(), filter.end(), filter.begin(),
3651 [factor = 1.0f / Mode::NMAX](
auto value) {
3652 return value * factor;
3658 std::lock_guard<std::mutex> lock(fftw_mutex);
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);
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);
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);
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);
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);
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);
3690 for (
auto plan : plans) {
3692 throw std::runtime_error(
"Failed to create FFT plan");
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) {
3703 auto const pos = std::max(0, kpos);
3704 auto const sz = std::max(0, ksz);
3706 assert(sz <= Mode::NMAX);
3709 emitEvent(JS8::Event::SyncStart{pos, sz});
3711 auto const ddCopy = [](
auto const begin,
auto const end,
3713 std::transform(begin, end, to, [](
auto const value) {
3714 return static_cast<float>(value);
3720 if ((JS8_RX_SAMPLE_SIZE - pos) < sz) {
3723 int const firstsize = JS8_RX_SAMPLE_SIZE - pos;
3724 int const secondsize = sz - firstsize;
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);
3733 ddCopy(std::begin(data.
d2) + pos, std::begin(data.
d2) + pos + sz,
3737 Decode::Map decodes;
3738 auto const ttl = std::chrono::seconds{Mode::NTXDUR * 2};
3739 m_softCombiner.
flush(ttl);
3741 int ldpcRescueBudget = BP_RESCUE_BUDGET;
3743 for (
int ipass = 1; ipass <= 3; ++ipass) {
3754 auto const sortCandidates =
3755 [nfqso = data.params.
nfqso](
auto &candidateList) {
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);
3762 if (a_dist < 10.0f && b_dist >= 10.0f)
3764 if (b_dist < 10.0f && a_dist >= 10.0f)
3767 return std::tie(a_dist, a.freq) <
3768 std::tie(b_dist, b.freq);
3778 computeBasebandFFT();
3780 bool const subtract = ipass < 3;
3781 bool improved =
false;
3783 auto const tryCandidates = [&](
auto const &candidateList,
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";
3791 auto const optionalStarted =
3792 js8::OptionalWorkBudget::Clock::now();
3794 int nharderrors = -1;
3796 auto decode = js8dec(data.params.
syncStats, subtract, f1,
3797 xdt, nharderrors, xsnr,
3798 ldpcRescueBudget, emitEvent, optional,
3800 if (deep && optional)
3801 optional->observe(js8::OptionalStage::Deep,
3808 auto const snr =
static_cast<int>(std::round(xsnr));
3815 if (
auto [it, inserted] =
3816 decodes.try_emplace(std::move(*decode), snr);
3817 inserted || it->second < snr) {
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,
3841 bool const tryDeep =
3842 m_enableDeepSearch && !
candidates.deep.empty() &&
3843 (!improved || ipass == 3);
3846 if (decoder_js8().isDebugEnabled()) {
3847 qCDebug(decoder_js8)
3848 <<
"deep sync fallback"
3849 <<
"pass" << ipass <<
"candidates"
3865 return decodes.size();
3872template class DecodeMode<ModeA>;
3873template class DecodeMode<ModeB>;
3874template class DecodeMode<ModeC>;
3875template class DecodeMode<ModeE>;
3876template class DecodeMode<ModeI>;
3885class Worker :
public QObject {
3900 std::array<js8::OptionalWorkBudget::Duration, 5> m_modeCost{};
3901 std::array<std::array<js8::OptionalWorkBudget::Duration,
3902 js8::OptionalWorkBudget::stages>, 5>
3904 std::array<bool, 5> m_modeObserved{};
3910 struct DecodeEntry {
3911 std::variant<DecodeMode<ModeA>, DecodeMode<ModeB>,
3912 DecodeMode<ModeC>, DecodeMode<ModeE>,
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) {}
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);
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)}};
3950 explicit Impl(
struct dec_data &data,
3952 : m_data(data), m_optionalSignal(signal) {}
3962 auto const set = m_data.params.nsubmodes;
3963 std::size_t sum = 0;
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();
3981 if (!(set & m_decodes[later].mode))
3983 if (!m_modeObserved[later])
3984 unknownMandatory =
true;
3986 reserve += m_modeCost[later];
3989 m_optionalSignal, reserve, m_stageCost[index],
3991 auto const started =
3992 js8::OptionalWorkBudget::Clock::now();
3994 [&](
auto &&decode) {
3995 sum += decode(m_data, entry.kpos, entry.ksz,
3996 emitEvent, &budget);
3999 auto const duration =
4000 std::chrono::duration_cast<
4001 js8::OptionalWorkBudget::Duration>(
4002 js8::OptionalWorkBudget::Clock::now() - started);
4004 std::max(m_modeCost[index] * 9 / 10,
4005 duration + duration / 4);
4006 m_modeObserved[index] =
true;
4019 QSemaphore *m_semaphore;
4021 std::atomic<bool> m_quit =
false;
4027 explicit Worker(QSemaphore *semaphore,
4029 QObject *parent =
nullptr)
4030 : QObject(parent), m_semaphore(semaphore),
4031 m_optionalSignal(optionalSignal) {}
4037 void stop() { m_quit =
true; }
4042 void copy() { m_data =
dec_data; };
4065 std::unique_ptr<Impl> impl = std::make_unique<Impl>(
4066 m_data, std::getenv(
"JS8_DISABLE_ADAPTIVE_OPTIONAL")
4067 ?
nullptr : m_optionalSignal);
4074 m_semaphore->acquire();
4080 emit decodeEvent(event);
4094 : QObject(parent), m_semaphore(0),
4095 m_worker(new JS8::
Worker(&m_semaphore, &m_optionalPressure)) {
4096 m_worker->moveToThread(&m_thread);
4098 connect(&m_thread, &QThread::started, m_worker, &JS8::Worker::run);
4099 connect(&m_thread, &QThread::finished, m_worker, &QObject::deleteLater);
4104 m_thread.start(priority);
4109 m_semaphore.release();
4116 m_semaphore.release();
4120 m_optionalPressure.pending(pending);
4123void JS8::Decoder::nextDecodeReady(
4124 std::chrono::steady_clock::time_point when)
noexcept {
4125 m_optionalPressure.nextReady(when);
4139 const char *
const message,
int *
const tones) {
4156 std::array<std::uint8_t, 11> bytes = {};
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]);
4168 bytes[j] = words >> 16;
4169 bytes[j + 1] = words >> 8;
4170 bytes[j + 2] = words;
4177 bytes[9] = (type & 0b111) << 5;
4183 auto const crc = CRC12(bytes);
4188 bytes[9] |= (crc >> 7) & 0x1F;
4189 bytes[10] = (crc & 0x7F) << 1;
4210 auto costasData = tones;
4211 auto parityData = tones + 7;
4212 auto outputData = tones + 43;
4216 for (
auto const &array : costas) {
4217 std::copy(array.begin(), array.end(), costasData);
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;
4231 for (std::size_t i = 0; i < 87; ++i) {
4243 std::size_t parityBits = 0;
4244 std::size_t parityByte = 0;
4245 std::uint8_t parityMask = 0x80;
4247 for (std::size_t j = 0; j < 87; ++j) {
4248 parityBits += parity(i, j) && (bytes[parityByte] & parityMask);
4250 (parityMask == 1) ? (++parityByte, 0x80) : (parityMask >> 1);
4256 parityWord = (parityWord << 1) | (parityBits & 1);
4258 (outputWord << 1) | ((bytes[outputByte] & outputMask) != 0);
4260 (outputMask == 1) ? (++outputByte, 0x80) : (outputMask >> 1);
4264 if (++outputBits == 3) {
4265 *parityData++ = parityWord;
4266 *outputData++ = outputWord;
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
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
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.