diff --git a/plugins/channelrx/demodacars/acarsdemodgui.cpp b/plugins/channelrx/demodacars/acarsdemodgui.cpp index 2f37c99dc..7539705f7 100644 --- a/plugins/channelrx/demodacars/acarsdemodgui.cpp +++ b/plugins/channelrx/demodacars/acarsdemodgui.cpp @@ -70,14 +70,11 @@ -// Decode text conventions: the full decode is plain multi-line text with -// "Label: value" lines. The Message Decode COLUMN shows it flattened to one -// semicolon-separated line so more fits; the decode VIEW and Map popups show it -// multi-line, with the label before each colon bolded. - -static QString decodeToColumn(const QString& decode) { return acarsDecodeToColumn(decode); } -static QString decodeToPlain(const QString& decode) { return acarsDecodeToPlain(decode); } -static QString decodeToHtml(const QString& plain) { return acarsDecodeToHtml(plain); } +// Decode text conventions, as acarsDecodeToColumn, acarsDecodeToPlain and +// acarsDecodeToHtml in util/acarstextformat.h apply them: the full decode is plain +// multi-line text with "Label: value" lines. The Message Decode COLUMN shows it +// flattened to one semicolon-separated line so more fits; the decode VIEW and Map +// popups show it multi-line, with the label before each colon bolded. // ARINC 620-8 DATALINK GROUND SYSTEM STANDAR AND INTERFACE SPECIFICATION diff --git a/plugins/channelrx/demodacars/acarsdemodsink.cpp b/plugins/channelrx/demodacars/acarsdemodsink.cpp index b8b4845a7..cc307a12f 100644 --- a/plugins/channelrx/demodacars/acarsdemodsink.cpp +++ b/plugins/channelrx/demodacars/acarsdemodsink.cpp @@ -263,6 +263,7 @@ void AcarsDemodSink::processOneSample(Complex &ci) if (channels != m_iridiumChannels) { + m_iridiumScanner.setTransform(&m_iridiumTransform); m_iridiumScanner.configure(channels); m_iridiumChannels = channels; m_iridiumCarrierCount = 0; diff --git a/plugins/channelrx/demodacars/acarsdemodsink.h b/plugins/channelrx/demodacars/acarsdemodsink.h index dd841aaf1..97ab728d0 100644 --- a/plugins/channelrx/demodacars/acarsdemodsink.h +++ b/plugins/channelrx/demodacars/acarsdemodsink.h @@ -36,6 +36,7 @@ #include "acarsaero.h" #include "acarsiridium.h" #include "acarsiridiumscanner.h" +#include "acarsiridiumfftengine.h" #define ACARSDEMOD_CHANNEL_SAMPLE_RATE ACARSOQPSK_CHANNEL_SAMPLE_RATE @@ -142,6 +143,9 @@ private: AcarsHfdlReceiver m_hfdlReceiver; AcarsAeroReceiver m_aeroReceiver; AcarsIridiumScanner m_iridiumScanner; + //!< SDRangel's FFT behind the channelizer, which is much faster than the one the + //!< scanner carries for the sake of the offline harnesses + AcarsIridiumFftEngine m_iridiumTransform; int m_iridiumChannels; //!< What the scanner is currently configured for //!< Scanning the whole band decodes a dozen frames a second, so none of them are diff --git a/plugins/channelrx/demodacars/acarsiridium.h b/plugins/channelrx/demodacars/acarsiridium.h index f168c36b5..781262bfc 100644 --- a/plugins/channelrx/demodacars/acarsiridium.h +++ b/plugins/channelrx/demodacars/acarsiridium.h @@ -29,6 +29,7 @@ #include #include "acarsiridiumfft.h" +#include "acarsiridiumdetector.h" // Iridium L band burst receiver, physical layer. // @@ -140,6 +141,16 @@ public: std::vector m_frameBits; }; + // Detection thresholds, as ratios against the noise floor. The end one is lower than + // the start one so a fade within a burst does not chop it in two. Public because + // AcarsIridiumDetectorBank applies the same test across a bank of channels and has + // to be given the same numbers + static constexpr double StartThreshold = 8.0; + static constexpr double EndThreshold = 3.0; + static const int StartSamples = 8; + static const int EndSamples = 16; + static const int PreTriggerLength = 16; + AcarsIridiumReceiver() { designRrc(); @@ -156,7 +167,7 @@ public: m_belowCount = 0; m_aboveCount = 0; m_smoothedPower = 0.0; - m_preTrigger.assign(m_preTriggerLength, Cd(0.0, 0.0)); + m_preTrigger.assign(PreTriggerLength, Cd(0.0, 0.0)); m_preTriggerWrite = 0; m_preTriggerCount = 0; m_burstSamples.clear(); @@ -204,11 +215,11 @@ public: m_noiseFloor += (m_smoothedPower - m_noiseFloor) * 0.0001; } - if (m_smoothedPower > (m_noiseFloor * m_startThreshold)) + if (m_smoothedPower > (m_noiseFloor * StartThreshold)) { m_aboveCount++; - if (m_aboveCount >= m_startSamples) + if (m_aboveCount >= StartSamples) { m_inBurst = true; m_belowCount = 0; @@ -220,8 +231,8 @@ public: // Oldest first, which with a ring is wherever the next write would go for (int i = 0; i < m_preTriggerCount; i++) { - const int index = (m_preTriggerWrite + m_preTriggerLength - m_preTriggerCount + i) - % m_preTriggerLength; + const int index = (m_preTriggerWrite + PreTriggerLength - m_preTriggerCount + i) + % PreTriggerLength; m_burstSamples.push_back(m_preTrigger[index]); } @@ -236,11 +247,11 @@ public: { m_burstSamples.push_back(sample); - if (m_smoothedPower < (m_noiseFloor * m_endThreshold)) + if (m_smoothedPower < (m_noiseFloor * EndThreshold)) { m_belowCount++; - if (m_belowCount >= m_endSamples) + if (m_belowCount >= EndSamples) { endBurst(); m_inBurst = false; @@ -265,9 +276,9 @@ public: } m_preTrigger[m_preTriggerWrite] = sample; - m_preTriggerWrite = (m_preTriggerWrite + 1) % m_preTriggerLength; + m_preTriggerWrite = (m_preTriggerWrite + 1) % PreTriggerLength; - if (m_preTriggerCount < m_preTriggerLength) { + if (m_preTriggerCount < PreTriggerLength) { m_preTriggerCount++; } @@ -276,6 +287,47 @@ public: return !m_bursts.empty(); } + // Burst handling driven by AcarsIridiumDetectorBank, which holds the detection + // state for a whole bank of channels instead of one receiver at a time. These do the + // same things, in the same order, as the branches of processSample() above - that + // path stays for a receiver watching a single channel, and for the tests + + //! Begins a burst. The caller then seeds burstSamples() with the pre-trigger history + void beginBurst(qint64 burstStart) + { + m_burstStart = burstStart; + m_burstSamples.clear(); + } + + //! The samples this burst is made of, so the bank can seed it with the history it + //! holds rather than this keeping a ring of its own + std::vector& burstSamples() { return m_burstSamples; } + + //! Takes one more sample. Returns true when the burst has outgrown anything a burst + //! can be, which means something is transmitting continuously rather than in bursts + bool appendBurst(const Cd& sample) + { + m_burstSamples.push_back(sample); + + if ((int) m_burstSamples.size() > (ACARSIRIDIUM_MAX_BURST_SYMBOLS * ACARSIRIDIUM_SAMPLES_PER_SYMBOL)) + { + m_burstSamples.clear(); + m_rejectedCount++; + + return true; + } + + return false; + } + + //! Decodes what has been collected. The noise floor comes from the bank, because + //! that is what tracked it, and the burst's signal to noise is measured against it + void finishBurst(double noiseFloor) + { + m_noiseFloor = noiseFloor; + endBurst(); + } + bool hasBurst() const { return !m_bursts.empty(); } Burst popBurst() @@ -816,13 +868,6 @@ private: m_burstSamples.clear(); } - // Detection thresholds, as ratios against the noise floor. The end one is lower than - // the start one so a fade within a burst does not chop it in two - const double m_startThreshold = 8.0; - const double m_endThreshold = 3.0; - const int m_startSamples = 8; - const int m_endSamples = 16; - const int m_preTriggerLength = 16; std::vector m_rrc; AcarsIridiumFft m_fft; diff --git a/plugins/channelrx/demodacars/acarsiridiumchannelizer.h b/plugins/channelrx/demodacars/acarsiridiumchannelizer.h index 7dda58b95..1e6c47cec 100644 --- a/plugins/channelrx/demodacars/acarsiridiumchannelizer.h +++ b/plugins/channelrx/demodacars/acarsiridiumchannelizer.h @@ -57,6 +57,23 @@ // M / 4 rather than M leaves a phase step between output blocks of a quarter turn per // channel per block, which is a power of -j and so costs nothing to apply. +//! The transform the bank runs on each block, so that a faster one can be put behind it. +//! +//! The built-in radix 2 is what keeps the channelizer self contained, which is what lets +//! the offline harnesses in test/ build against Qt alone. It is also the single largest +//! thing the bank spends its time on - measured against FFTW on the same 256 point +//! transform it is over five times slower - so the plugin, which has sdrbase, installs +//! SDRangel's FFT engine instead +class AcarsIridiumTransform +{ +public: + virtual ~AcarsIridiumTransform() {} + + //! Always the inverse transform, unscaled, which is what the bank wants + virtual void configure(int size) = 0; + virtual void transform(std::vector>& data) = 0; +}; + class AcarsIridiumChannelizer { public: @@ -77,10 +94,26 @@ public: { } + //! Puts a different transform behind the bank. Must be called before configure, and + //! the caller keeps ownership. Passing nullptr goes back to the built-in one + void setTransform(AcarsIridiumTransform *transform) + { + m_transform = transform ? transform : &m_builtIn; + } + //! channels must be a power of two and a multiple of Oversample. The input rate has //! to be channels * spacing, and for Iridium the spacing wanted is 31.25 kHz, so - //! 8 MS/s gives 256 channels, 4 MS/s gives 128, and so on - void configure(int channels, int tapsPerBranch = 12) + //! 8 MS/s gives 256 channels, 4 MS/s gives 128, and so on. + //! + //! The taps per branch set what the filtering costs: the work is the input rate times + //! the oversampling times this, and nothing else - the channel count cancels out. It + //! was twelve, which left the prototype far better than it needs to be. At eight it + //! still has 70 dB beyond the output Nyquist, which is what folds back, and reaches + //! 60 dB by 1.28 channel spacings against the two that are available. The cost of + //! going lower is not aliasing but a softer channel edge, which lets more of a burst + //! into its neighbours: measured on two recordings, eight finds slightly more bursts + //! than twelve and rather more of them are duplicates of each other + void configure(int channels, int tapsPerBranch = 8) { m_channels = channels; m_decimation = channels / Oversample; @@ -95,7 +128,7 @@ public: m_count = 0; m_block = 0; - m_fft.configure(channels); + m_transform->configure(channels); buildRotations(); } @@ -122,7 +155,13 @@ public: bool processSample(const Cd& sample) { m_delay[m_write] = sample; - m_write = (m_write + 1) % m_length; + + // A conditional wrap, not a modulo: m_length is a member, so the compiler cannot + // turn the division into a multiply, and this runs once per input sample - eight + // million times a second at the widest setting + if (++m_write == m_length) { + m_write = 0; + } m_count++; if (m_count < m_decimation) { @@ -232,91 +271,133 @@ private: //! multiply and the add on the real and imaginary parts together rather than one //! after the other. Two runs are kept going at once because each is a chain of //! dependent adds, and one chain on its own leaves the pipeline waiting on itself - static void accumulate(Cd *out, const Cd *in, const double *h, int run) + //! One chunk of channels, all taps, with the sums held in registers. + //! + //! The other way round - one tap across every channel, which is what this did - has + //! to read and write the output array once per tap, so a complex multiply and add + //! costs three loads and a store. Holding a chunk's sums across all the taps leaves + //! two loads and nothing else, and the output is written once. + //! + //! Every bound here is the constant, never a variable count, so that the loops unroll + //! and the accumulators become registers. Written with a runtime chunk length instead + //! this was 30% SLOWER than the version it replaced, because the array of sums went + //! on the stack and the loads and stores came straight back + void accumulateChunk(int p, int newest) { #if defined(USE_SSE4_1) - int i = 0; + __m128d acc[ChunkChannels]; - for (; (i + 1) < run; i += 2) - { - const __m128d a0 = _mm_loadu_pd((const double *) (in - i)); - const __m128d a1 = _mm_loadu_pd((const double *) (in - i - 1)); - const __m128d o0 = _mm_loadu_pd((double *) (out + i)); - const __m128d o1 = _mm_loadu_pd((double *) (out + i + 1)); - - _mm_storeu_pd((double *) (out + i), - _mm_add_pd(o0, _mm_mul_pd(a0, _mm_set1_pd(h[i])))); - _mm_storeu_pd((double *) (out + i + 1), - _mm_add_pd(o1, _mm_mul_pd(a1, _mm_set1_pd(h[i + 1])))); + for (int i = 0; i < ChunkChannels; i++) { + acc[i] = _mm_setzero_pd(); } - for (; i < run; i++) + for (int q = 0; q < m_tapsPerBranch; q++) { - const __m128d a = _mm_loadu_pd((const double *) (in - i)); - const __m128d o = _mm_loadu_pd((double *) (out + i)); + // Branch p reads the sample this far back, and within the chunk the index + // walks backwards one per channel + int index = newest - (q * m_channels) - p; - _mm_storeu_pd((double *) (out + i), - _mm_add_pd(o, _mm_mul_pd(a, _mm_set1_pd(h[i])))); - } -#else - for (int i = 0; i < run; i++) - { - const Cd& sample = in[-i]; - const double tap = h[i]; + while (index < 0) { + index += m_length; + } + + const double *tap = &m_proto[(q * m_channels) + p]; - out[i] += Cd(sample.real() * tap, sample.imag() * tap); + if (index >= (ChunkChannels - 1)) + { + // The whole chunk is there without the delay line wrapping round + const Cd *in = &m_delay[index]; + + for (int i = 0; i < ChunkChannels; i++) + { + const __m128d a = _mm_loadu_pd((const double *) (in - i)); + + acc[i] = _mm_add_pd(acc[i], _mm_mul_pd(a, _mm_set1_pd(tap[i]))); + } + } + else + { + // At most one chunk per tap straddles the end of the delay line + for (int i = 0; i < ChunkChannels; i++) + { + int j = index - i; + + if (j < 0) { + j += m_length; + } + + const __m128d a = _mm_loadu_pd((const double *) &m_delay[j]); + + acc[i] = _mm_add_pd(acc[i], _mm_mul_pd(a, _mm_set1_pd(tap[i]))); + } + } } -#endif - } - void computeBlock() - { - const int newest = (m_write - 1 + m_length) % m_length; + for (int i = 0; i < ChunkChannels; i++) { + _mm_storeu_pd((double *) &m_out[p + i], acc[i]); + } +#else + Cd acc[ChunkChannels]; - // Each branch filters every Mth sample of the delay line, which is what makes one - // prototype filter serve as the whole bank. Written straight into the output, - // because the transform below is in place and a copy of the whole bank every - // block is megabytes a second for nothing. - // - // The loop runs tap first and branch second, which looks the wrong way round - - // the branch accumulator cannot stay in a register, and the output is read and - // written once per tap instead of once per block. It is much faster anyway, - // because branch first walks both the delay line and the prototype in strides of - // a whole channel count: at 256 channels that is a 4 kB step per access, which no - // prefetcher will follow. This way all three arrays are walked one element at a - // time, which also makes the inner loop something a vector unit can do - std::fill(m_out.begin(), m_out.end(), Cd(0.0, 0.0)); + for (int i = 0; i < ChunkChannels; i++) { + acc[i] = Cd(0.0, 0.0); + } for (int q = 0; q < m_tapsPerBranch; q++) { - // Branch p reads the sample this far back, so p ascending walks backwards - // down the delay line from here - int index = newest - (q * m_channels); + int index = newest - (q * m_channels) - p; while (index < 0) { index += m_length; } - const double *tap = &m_proto[q * m_channels]; - int p = 0; + const double *tap = &m_proto[(q * m_channels) + p]; - while (p < m_channels) + for (int i = 0; i < ChunkChannels; i++) { - // As far as can be gone before the delay line wraps round to its end - const int run = std::min(m_channels - p, index + 1); + int j = index - i; - accumulate(&m_out[p], &m_delay[index], &tap[p], run); + if (j < 0) { + j += m_length; + } - p += run; - index -= run; + const Cd& sample = m_delay[j]; - if (index < 0) { - index += m_length; - } + acc[i] += Cd(sample.real() * tap[i], sample.imag() * tap[i]); } } - m_fft.transform(m_out, true); + for (int i = 0; i < ChunkChannels; i++) { + m_out[p + i] = acc[i]; + } +#endif + } + + void computeBlock() + { + const int newest = (m_write - 1 + m_length) % m_length; + + // Each branch filters every Mth sample of the delay line, which is what makes one + // prototype filter serve as the whole bank. Written straight into the output, + // because the transform below is in place and a copy of the whole bank every + // block is megabytes a second for nothing. + // + // A chunk of channels at a time, with every tap applied before moving on. Taking + // one tap across all the channels instead walks all three arrays one element at + // a time, which looks better and was what this did, but it has to read and write + // the output once per tap. Doing it this way the chunk's sums never leave the + // registers and the output is written once, which is also why nothing needs + // zeroing first. What must not be done is a whole branch at a time, which walks + // the delay line and the prototype in strides of a whole channel count - at 256 + // channels a 4 kB step per access, which no prefetcher will follow + // The channel count is a power of two and never below the chunk, so every chunk + // is full - which is what lets the loops inside run to a constant bound + for (int p = 0; p < m_channels; p += ChunkChannels) + { + accumulateChunk(p, newest); + } + + m_transform->transform(m_out); // The phase for this block, which is where the oversampling is paid for const int base = m_block * m_channels; @@ -328,6 +409,10 @@ private: m_block = (m_block + 1) % Oversample; } + //! Channels whose sums are carried in registers together. Eight complex doubles is + //! eight of the sixteen vector registers, leaving room for the loads and the taps + static const int ChunkChannels = 8; + int m_channels; int m_decimation; int m_tapsPerBranch; @@ -340,7 +425,19 @@ private: std::vector m_delay; std::vector m_out; std::vector m_rotation; - AcarsIridiumFft m_fft; + + //! The transform the bank actually runs, and the one it falls back on + class BuiltInTransform : public AcarsIridiumTransform + { + public: + void configure(int size) override { m_fft.configure(size); } + void transform(std::vector& data) override { m_fft.transform(data, true); } + private: + AcarsIridiumFft m_fft; + }; + + BuiltInTransform m_builtIn; + AcarsIridiumTransform *m_transform = &m_builtIn; }; #endif // INCLUDE_ACARSIRIDIUMCHANNELIZER_H diff --git a/plugins/channelrx/demodacars/acarsiridiumdetector.h b/plugins/channelrx/demodacars/acarsiridiumdetector.h new file mode 100644 index 000000000..41c0c7c29 --- /dev/null +++ b/plugins/channelrx/demodacars/acarsiridiumdetector.h @@ -0,0 +1,373 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_ACARSIRIDIUMDETECTOR_H +#define INCLUDE_ACARSIRIDIUMDETECTOR_H + +#include + +#include +#include +#include + +#if defined(USE_SSE4_1) +#include +#endif + +// Burst detection for a whole bank of channels at once. +// +// Every channel runs the same half dozen arithmetic operations on each of its samples - +// power, a smoothing step, a noise floor step and two comparisons - and at the widest +// setting that is thirty two million of them a second, because the channelizer produces +// four samples per channel for every input sample and there are two hundred and fifty six +// channels. Held one receiver object at a time, that work is slow for a reason that is +// not arithmetic: each block touches a couple of cache lines in each of 256 objects that +// are tens of kilobytes apart, so the whole thing runs at the speed of the cache rather +// than of the adds. +// +// Holding the state as one array per quantity instead puts a block's worth of each in a +// handful of cache lines, and makes the arithmetic something a vector unit can do two +// channels at a time. The samples a burst is made of are not here - those stay with the +// receiver, which is what knows how to demodulate them. +// +// The order of operations within a channel is exactly the order the single channel path +// used, because the two have to agree: the scanner's output is checked against recordings +// frame for frame, and a different rounding order would be a different set of frames. + +class AcarsIridiumDetectorBank +{ +public: + typedef std::complex Cd; + + enum Event + { + Started, //!< A burst began on this channel in this block + Ended //!< It ended, and the receiver should decode what it has + }; + + struct Change + { + int m_channel; + Event m_event; + }; + + AcarsIridiumDetectorBank() : + m_channels(0), + m_startThreshold(8.0), + m_endThreshold(3.0), + m_startSamples(8), + m_endSamples(16), + m_preTriggerLength(16), + m_preTriggerWrite(0), + m_preTriggerCount(0), + m_sampleIndex(0) + { + } + + //! The thresholds are ratios against the tracked noise floor, and the counts are how + //! many samples either side of one is needed before a burst starts or ends + void configure(int channels, double startThreshold, double endThreshold, + int startSamples, int endSamples, int preTriggerLength) + { + m_channels = channels; + m_startThreshold = startThreshold; + m_endThreshold = endThreshold; + m_startSamples = startSamples; + m_endSamples = endSamples; + m_preTriggerLength = preTriggerLength; + + reset(); + } + + void reset() + { + m_smoothed.assign(m_channels, 0.0); + m_noiseFloor.assign(m_channels, 0.0); + m_noiseValid.assign(m_channels, 0); + m_inBurst.assign(m_channels, 0); + m_aboveCount.assign(m_channels, 0); + m_belowCount.assign(m_channels, 0); + + // One ring for the whole bank, holding whole blocks rather than a ring per + // channel, and laid out block first so that a block is written as one run. + // + // The other way round - all of a channel's history together - is the obvious + // layout and is much worse: a block then writes one sample into each channel's + // own stretch, a cache line apart, so at 256 channels it touches 256 lines over + // 64 kB and falls out of L1. That showed up as the detector costing 80% more per + // sample at 256 channels than at 128, while every other stage stayed flat. + // Reading one channel's history is strided instead, but that only happens when a + // burst starts, which is thousands of blocks apart + m_preTrigger.assign((size_t) m_channels * m_preTriggerLength, Cd(0.0, 0.0)); + m_preTriggerWrite = 0; + m_preTriggerCount = 0; + m_sampleIndex = 0; + m_burstChannels.clear(); + } + + //! The index the next block will have, which is what a burst start is measured from + qint64 sampleIndex() const { return m_sampleIndex; } + int preTriggerCount() const { return m_preTriggerCount; } + + //! The channels currently receiving a burst, so the caller does not have to look + const std::vector& burstChannels() const { return m_burstChannels; } + + bool inBurst(int channel) const { return m_inBurst[channel] != 0; } + + //! The tracked noise floor for a channel, which is what a burst's signal to noise is + //! measured against + double noiseFloor(int channel) const { return m_noiseFloor[channel]; } + + + + //! Ends a burst the caller has given up on, without decoding it - a channel that has + //! been transmitting continuously for longer than any burst can be. The noise floor + //! is invalidated so it re-converges rather than staying at whatever it was + void abandonBurst(int channel) + { + m_inBurst[channel] = 0; + m_aboveCount[channel] = 0; + m_noiseValid[channel] = 0; + removeBurstChannel(channel); + } + + //! Feeds one sample per channel. + //! + //! append(channel, sample) is called for every channel that was already receiving + //! when the block arrived, and returns true if that channel has now taken more + //! samples than any burst can be - it is given the sample before the end test, which + //! is the order the single channel path used, so the sample a burst ends on is part + //! of it. A channel that starts in this block is not appended to: its samples so far + //! are the pre-trigger history. + //! + //! begin(channel, burstStart) is called when a burst starts and returns the buffer to + //! put that history in, which is filled here rather than afterwards: this block's + //! sample goes into the ring at the end, over the oldest one, so by the time the + //! caller had a chance to read it the window would be short of where it started + template + void processBlock(const Cd *samples, std::vector& changes, Append append, Begin begin) + { + power(samples); + continueBursts(samples, changes, append); + idleAndHistory(samples, changes, begin); + + m_sampleIndex++; + } + +private: + + //! Power and the smoothing step, for every channel. Nothing here depends on whether a + //! channel is in a burst, so it is one straight run over two arrays + void power(const Cd *samples) + { + const double *in = (const double *) samples; + double *smoothed = m_smoothed.data(); + int c = 0; + +#if defined(USE_SSE4_1) + const __m128d alpha = _mm_set1_pd(0.25); + + for (; c + 2 <= m_channels; c += 2) + { + // Two complex samples are four doubles: multiply by themselves and add the + // halves across to get the two norms + const __m128d a = _mm_loadu_pd(in + (2 * c)); + const __m128d b = _mm_loadu_pd(in + (2 * c) + 2); + const __m128d aa = _mm_mul_pd(a, a); + const __m128d bb = _mm_mul_pd(b, b); + const __m128d p = _mm_hadd_pd(aa, bb); + + const __m128d s = _mm_loadu_pd(smoothed + c); + + _mm_storeu_pd(smoothed + c, + _mm_add_pd(s, _mm_mul_pd(_mm_sub_pd(p, s), alpha))); + } +#endif + + for (; c < m_channels; c++) + { + const double p = std::norm(samples[c]); + + smoothed[c] += (p - smoothed[c]) * 0.25; + } + } + + //! The noise floor, the start test and the history ring, in one pass. + //! + //! One pass rather than three: the arithmetic here is only a handful of operations + //! per channel, so walking the arrays is most of what it costs, and splitting it up + //! was measurably worse than the single fused loop it replaced. Within a channel the + //! order is the one the single channel path used - the idle test, then the start, + //! then the ring write, so that a burst's history is taken before this block's + //! sample lands on the oldest slot + template + void idleAndHistory(const Cd *samples, std::vector& changes, Begin begin) + { + const double *smoothed = m_smoothed.data(); + double *noise = m_noiseFloor.data(); + quint8 *valid = m_noiseValid.data(); + const quint8 *inBurst = m_inBurst.data(); + qint32 *above = m_aboveCount.data(); + Cd *ring = m_preTrigger.data(); + const int length = m_preTriggerLength; + const size_t write = (size_t) m_preTriggerWrite; + + for (int c = 0; c < m_channels; c++) + { + if (!inBurst[c]) + { + if (!valid[c]) + { + noise[c] = smoothed[c]; + valid[c] = 1; + } + else + { + noise[c] += (smoothed[c] - noise[c]) * 0.0001; + } + + if (smoothed[c] > (noise[c] * m_startThreshold)) + { + above[c]++; + + if (above[c] >= m_startSamples) { + startBurst(c, changes, begin); + } + } + else + { + above[c] = 0; + } + } + + ring[((size_t) write * m_channels) + c] = samples[c]; + } + + m_preTriggerWrite++; + + if (m_preTriggerWrite == length) { + m_preTriggerWrite = 0; + } + + if (m_preTriggerCount < length) { + m_preTriggerCount++; + } + } + + //! The channels that were already receiving: take this block's sample, then test + //! whether the burst has ended. Walked backwards so that removing one does not + //! disturb the ones still to be looked at, and only over the channels that were + //! receiving before this block - on a real band a handful out of hundreds + template + void continueBursts(const Cd *samples, std::vector& changes, Append append) + { + const double *smoothed = m_smoothed.data(); + const double *noise = m_noiseFloor.data(); + + for (int i = (int) m_burstChannels.size() - 1; i >= 0; i--) + { + const int c = m_burstChannels[i]; + + if (append(c, samples[c])) + { + // Longer than any burst can be, so something is transmitting continuously + m_inBurst[c] = 0; + m_aboveCount[c] = 0; + m_noiseValid[c] = 0; + m_burstChannels.erase(m_burstChannels.begin() + i); + continue; + } + + if (smoothed[c] < (noise[c] * m_endThreshold)) + { + m_belowCount[c]++; + + if (m_belowCount[c] >= m_endSamples) + { + m_inBurst[c] = 0; + m_aboveCount[c] = 0; + m_burstChannels.erase(m_burstChannels.begin() + i); + changes.push_back({ c, Ended }); + } + } + else + { + m_belowCount[c] = 0; + } + } + } + + //! Channels whose start counter has reached the threshold. The counter only advances + //! for an idle channel, so one that reaches it here cannot already be receiving, and + //! the end test above has already run without it + template + void startBurst(int c, std::vector& changes, Begin begin) + { + m_inBurst[c] = 1; + m_belowCount[c] = 0; + m_burstChannels.push_back(c); + changes.push_back({ c, Started }); + + // The samples from before the detector fired are part of the burst, and the + // preamble they hold is what the frequency estimate needs. Oldest first, which + // with a ring is wherever the next write would go + std::vector& out = begin(c, m_sampleIndex - (qint64) m_preTriggerCount); + + for (int i = 0; i < m_preTriggerCount; i++) + { + const int slot = (m_preTriggerWrite + m_preTriggerLength - m_preTriggerCount + i) + % m_preTriggerLength; + + out.push_back(m_preTrigger[((size_t) slot * m_channels) + c]); + } + } + + void removeBurstChannel(int channel) + { + for (size_t i = 0; i < m_burstChannels.size(); i++) + { + if (m_burstChannels[i] == channel) + { + m_burstChannels.erase(m_burstChannels.begin() + i); + return; + } + } + } + + int m_channels; + double m_startThreshold; + double m_endThreshold; + int m_startSamples; + int m_endSamples; + int m_preTriggerLength; + + std::vector m_smoothed; + std::vector m_noiseFloor; + std::vector m_noiseValid; + std::vector m_inBurst; + std::vector m_aboveCount; + std::vector m_belowCount; + std::vector m_burstChannels; + + std::vector m_preTrigger; + int m_preTriggerWrite; + int m_preTriggerCount; + qint64 m_sampleIndex; +}; + +#endif // INCLUDE_ACARSIRIDIUMDETECTOR_H diff --git a/plugins/channelrx/demodacars/acarsiridiumfftengine.h b/plugins/channelrx/demodacars/acarsiridiumfftengine.h new file mode 100644 index 000000000..5bdd35acb --- /dev/null +++ b/plugins/channelrx/demodacars/acarsiridiumfftengine.h @@ -0,0 +1,173 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_ACARSIRIDIUMFFTENGINE_H +#define INCLUDE_ACARSIRIDIUMFFTENGINE_H + +#include +#include +#include + +#include + +#include "dsp/dspengine.h" +#include "dsp/fftengine.h" +#include "dsp/fftfactory.h" + +#include "acarsiridiumchannelizer.h" +#include "acarsiridiumfft.h" + +// Puts SDRangel's FFT engine behind the Iridium channelizer. +// +// The bank runs one transform per output block, which at the widest setting is a hundred +// and twenty five thousand 256 point transforms a second, and that was over a third of +// everything the scanner cost. The radix 2 in acarsiridiumfft.h is deliberately plain so +// that the offline harnesses in test/ can build against Qt alone; here, where sdrbase is +// available, FFTW does the same transform several times faster. +// +// Single precision, because that is what SDRangel's engines work in. The polyphase +// filtering either side of it stays double, and a 256 point transform in float carries +// far more precision than a burst detector and a DQPSK slicer can use. + +class AcarsIridiumFftEngine : public AcarsIridiumTransform +{ +public: + AcarsIridiumFftEngine() : + m_engine(nullptr), + m_sequence(0), + m_size(0) + { + } + + ~AcarsIridiumFftEngine() + { + release(); + } + + void configure(int size) override + { + release(); + + FFTFactory *factory = DSPEngine::instance()->getFFTFactory(); + + // Inverse, which the factory configures the engine for. Both this and the radix 2 + // leave it unscaled, which is what a filter bank wants + m_sequence = factory->getEngine(size, true, &m_engine); + m_size = size; + m_builtIn.configure(size); + + if (!m_engine) + { + qWarning() << "AcarsIridiumFftEngine: no engine for size" << size + << "- falling back to the built-in transform"; + return; + } + + qInfo() << "AcarsIridiumFftEngine: using" << m_engine->getName() + << "for the" << size << "point channelizer transform"; + + checkAgainstBuiltIn(size); + } + + void transform(std::vector>& data) override + { + if (!m_engine) + { + m_builtIn.transform(data, true); + return; + } + + Complex *in = m_engine->in(); + + for (int i = 0; i < m_size; i++) { + in[i] = Complex((float) data[i].real(), (float) data[i].imag()); + } + + m_engine->transform(); + + const Complex *out = m_engine->out(); + + for (int i = 0; i < m_size; i++) { + data[i] = std::complex(out[i].real(), out[i].imag()); + } + } + +private: + + //! One transform of a known vector through both, compared, when the engine is taken. + //! + //! Worth the once-per-configure cost because the ways this can be wrong are not + //! subtle but are silent: a library that scales its inverse by 1/N, or orders its + //! output differently, would leave the bank producing plausible rubbish and the only + //! visible symptom would be that nothing ever decodes. The tests in test/ cannot + //! cover this path, because they build without sdrbase and so never see this engine + void checkAgainstBuiltIn(int size) + { + AcarsIridiumFft reference; + reference.configure(size); + + std::vector> a(size); + + for (int i = 0; i < size; i++) + { + const double phase = 0.7 * i; + a[i] = std::complex(std::cos(phase) + (0.1 * i), std::sin(phase) - (0.05 * i)); + } + + std::vector> b = a; + + reference.transform(a, true); + transform(b); + + double worst = 0.0; + double scale = 1e-12; + + for (int i = 0; i < size; i++) + { + worst = std::max(worst, std::abs(b[i] - a[i])); + scale = std::max(scale, std::abs(a[i])); + } + + // Generous: single precision over a 256 point transform of values this large is + // good to about a part in a million, and anything structurally wrong is out by + // orders of magnitude rather than by rounding + if ((worst / scale) > 1e-4) + { + qWarning() << "AcarsIridiumFftEngine:" << m_engine->getName() + << "disagrees with the built-in transform by" << (worst / scale) + << "- falling back to the built-in one"; + release(); + } + } + + void release() + { + if (m_engine) + { + DSPEngine::instance()->getFFTFactory()->releaseEngine(m_size, true, m_sequence); + m_engine = nullptr; + } + } + + FFTEngine *m_engine; + unsigned int m_sequence; + int m_size; + AcarsIridiumFft m_builtIn; +}; + +#endif // INCLUDE_ACARSIRIDIUMFFTENGINE_H diff --git a/plugins/channelrx/demodacars/acarsiridiumscanner.h b/plugins/channelrx/demodacars/acarsiridiumscanner.h index 373677de6..634e3a3d5 100644 --- a/plugins/channelrx/demodacars/acarsiridiumscanner.h +++ b/plugins/channelrx/demodacars/acarsiridiumscanner.h @@ -31,6 +31,7 @@ #include "acarsiridium.h" #include "acarsiridiumframe.h" #include "acarsiridiumchannelizer.h" +#include "acarsiridiumdetector.h" // Watches the whole Iridium band at once. // @@ -98,6 +99,13 @@ public: m_decimation = m_channelizer.decimation(); m_receivers.clear(); m_receivers.resize(channels); + m_detector.configure(channels, + AcarsIridiumReceiver::StartThreshold, + AcarsIridiumReceiver::EndThreshold, + AcarsIridiumReceiver::StartSamples, + AcarsIridiumReceiver::EndSamples, + AcarsIridiumReceiver::PreTriggerLength); + m_changes.clear(); m_pending.clear(); m_detections.clear(); m_sampleIndex = 0; @@ -109,6 +117,10 @@ public: m_acarsCount = 0; } + //! Puts a different transform behind the channelizer. Must be called before + //! configure, and the caller keeps ownership + void setTransform(AcarsIridiumTransform *transform) { m_channelizer.setTransform(transform); } + int channels() const { return m_channels; } double inputRate() const { return m_inputRate; } @@ -123,12 +135,30 @@ public: const std::vector& channelSamples = m_channelizer.channelSamples(); - for (int c = 0; c < m_channels; c++) + // Detection for every channel in one pass over arrays rather than a receiver at + // a time - see the note on AcarsIridiumDetectorBank + m_changes.clear(); + m_detector.processBlock(channelSamples.data(), m_changes, + [this](int channel, const Cd& sample) { + return m_receivers[channel].appendBurst(sample); + }, + [this](int channel, qint64 burstStart) -> std::vector& { + m_receivers[channel].beginBurst(burstStart); + return m_receivers[channel].burstSamples(); + }); + + for (size_t i = 0; i < m_changes.size(); i++) { - if (!m_receivers[c].processSample(channelSamples[c])) { + const AcarsIridiumDetectorBank::Change& change = m_changes[i]; + const int c = change.m_channel; + + // A start has already been dealt with, inside the block + if (change.m_event == AcarsIridiumDetectorBank::Started) { continue; } + m_receivers[c].finishBurst(m_detector.noiseFloor(c)); + while (m_receivers[c].hasBurst()) { AcarsIridiumReceiver::Burst burst = m_receivers[c].popBurst(); @@ -142,7 +172,7 @@ public: candidate.m_channel = c; candidate.m_frequency = m_channelizer.channelOffset(c, m_inputRate) + burst.m_frequencyOffset; - // The receiver counts in its own channel samples + // The detector counts in channel samples candidate.m_sampleIndex = burst.m_sampleIndex * m_decimation; candidate.m_detectedAt = m_sampleIndex; m_pending.push_back(candidate); @@ -297,6 +327,8 @@ private: qint64 m_sampleIndex; AcarsIridiumChannelizer m_channelizer; + AcarsIridiumDetectorBank m_detector; + std::vector m_changes; std::vector m_receivers; AcarsIridiumFrameDecoder m_decoder; AcarsIridiumReassembler m_reassembler; diff --git a/plugins/channelrx/demodacars/acarsoqpsk.h b/plugins/channelrx/demodacars/acarsoqpsk.h index 47d41f699..090b2a6eb 100644 --- a/plugins/channelrx/demodacars/acarsoqpsk.h +++ b/plugins/channelrx/demodacars/acarsoqpsk.h @@ -1351,7 +1351,7 @@ private: runSymbolLoop(tau0, available, preSymbols); m_bitsConsumed = 0; - if (decodeSoftBits(tau0, available, preSymbols, true)) + if (decodeSoftBits(available, preSymbols, true)) { m_stats.m_timingTries += oi + 1; if (m_suppressCorrection && m_repairAvailable) { @@ -1386,7 +1386,7 @@ private: runSymbolLoop(tau0, available, preSymbols); m_bitsConsumed = 0; - if (decodeSoftBits(tau0, available, preSymbols, true)) + if (decodeSoftBits(available, preSymbols, true)) { m_reconstructInProgress = false; m_stats.m_impulseReconstructRecovered++; @@ -1782,7 +1782,7 @@ private: return accepted; } - bool decodeSoftBits(double tau0, int available, int preSymbols, bool allowReacquire) + bool decodeSoftBits(int available, int preSymbols, bool allowReacquire) { // Bit sync then character sync: '+' with odd parity, '*', SYN, SYN, each LSB first. // ARINC 618 section 4.2.2 says the + and * are there "to enable bit ambiguity @@ -1858,7 +1858,7 @@ private: m_stats.m_syncReacquired++; runSymbolLoop(anchoredTau, available, preSymbols); m_bitsConsumed = 0; - return decodeSoftBits(anchoredTau, available, preSymbols, false); + return decodeSoftBits(available, preSymbols, false); } } diff --git a/plugins/channelrx/demodacars/acarsvdl2.h b/plugins/channelrx/demodacars/acarsvdl2.h index e0f67784f..70d7d5d8f 100644 --- a/plugins/channelrx/demodacars/acarsvdl2.h +++ b/plugins/channelrx/demodacars/acarsvdl2.h @@ -79,7 +79,7 @@ // What an AVLC frame type abbreviation means, for the table's Label Decode column. The // abbreviations are the ones ISO 13239 and the VDL Mode 2 SARPs use, and are what appears // in the Label column. -static const char *avlcFrameTypeName(const char *type) +inline const char *avlcFrameTypeName(const char *type) { if (!type) { return ""; diff --git a/plugins/feature/map/msfsassetconverter/portholes.cpp b/plugins/feature/map/msfsassetconverter/portholes.cpp index 3092bc2fa..8be19e3e6 100644 --- a/plugins/feature/map/msfsassetconverter/portholes.cpp +++ b/plugins/feature/map/msfsassetconverter/portholes.cpp @@ -352,7 +352,7 @@ QString mirrorInsetPortholes(QJsonObject *root, QVector *buffers) for (qint64 i = 0; i < count; i++) { if (type == ComponentUnsignedByte) { - indices[i] = static_cast(elements[i]); + indices[i] = static_cast(elements.constData()[i]); } else if (type == ComponentUnsignedShort) { quint16 v; std::memcpy(&v, elements.constData() + i * 2, 2);