From 5239d73ebe8c28a40301b19760f6e0e1fb87c371 Mon Sep 17 00:00:00 2001 From: Jon Beniston Date: Wed, 30 Sep 2026 18:24:23 +0100 Subject: [PATCH] Add matched filter to improve performance. Increase carrier pull-in range. Separate demod for easier testing. --- plugins/channelrx/demodpsk31/CMakeLists.txt | 2 + plugins/channelrx/demodpsk31/psk31demod.cpp | 28 +- plugins/channelrx/demodpsk31/psk31demod.h | 6 + .../channelrx/demodpsk31/psk31demodgui.cpp | 11 +- plugins/channelrx/demodpsk31/psk31demodgui.h | 1 + .../channelrx/demodpsk31/psk31demodsink.cpp | 255 +------ plugins/channelrx/demodpsk31/psk31demodsink.h | 79 +-- .../channelrx/demodpsk31/psk31demodulator.cpp | 646 ++++++++++++++++++ .../channelrx/demodpsk31/psk31demodulator.h | 195 ++++++ plugins/channelrx/demodpsk31/readme.md | 107 +-- sdrbase/dsp/costasloop.h | 1 + .../doc/swagger/include/PSK31Demod.yaml | 6 +- sdrbase/util/psk31.cpp | 15 +- sdrbase/util/psk31.h | 1 + sdrbench/CMakeLists.txt | 5 +- sdrbench/test_psk31.cpp | 570 +++++++++++++--- .../api/swagger/include/PSK31Demod.yaml | 6 +- 17 files changed, 1451 insertions(+), 483 deletions(-) create mode 100644 plugins/channelrx/demodpsk31/psk31demodulator.cpp create mode 100644 plugins/channelrx/demodpsk31/psk31demodulator.h diff --git a/plugins/channelrx/demodpsk31/CMakeLists.txt b/plugins/channelrx/demodpsk31/CMakeLists.txt index ba56457be..a70f33f9f 100644 --- a/plugins/channelrx/demodpsk31/CMakeLists.txt +++ b/plugins/channelrx/demodpsk31/CMakeLists.txt @@ -5,6 +5,7 @@ set(demodpsk31_SOURCES psk31demodsettings.cpp psk31demodbaseband.cpp psk31demodsink.cpp + psk31demodulator.cpp psk31demodplugin.cpp psk31demodwebapiadapter.cpp ) @@ -14,6 +15,7 @@ set(demodpsk31_HEADERS psk31demodsettings.h psk31demodbaseband.h psk31demodsink.h + psk31demodulator.h psk31demodplugin.h psk31demodwebapiadapter.h ) diff --git a/plugins/channelrx/demodpsk31/psk31demod.cpp b/plugins/channelrx/demodpsk31/psk31demod.cpp index a918029b6..6d80ec61e 100644 --- a/plugins/channelrx/demodpsk31/psk31demod.cpp +++ b/plugins/channelrx/demodpsk31/psk31demod.cpp @@ -190,10 +190,12 @@ bool PSK31Demod::handleMessage(const Message& cmd) } // Write to log file - if (m_logFile.isOpen()) + if (m_logFile.isOpen() && !report.getCharacter().isEmpty()) { - m_logStream << report.getCharacter(); + const QChar character = report.getCharacter()[0]; + m_logStream << displayText(character, m_previousLogCharacter); m_logStream.flush(); + m_previousLogCharacter = character; } return true; @@ -222,6 +224,19 @@ bool PSK31Demod::handleMessage(const Message& cmd) } } +QString PSK31Demod::displayText(QChar character, QChar previousCharacter) +{ + if (character == '\r') { + return QStringLiteral("\n"); + } else if (character == '\n') { + return previousCharacter == '\r' ? QString() : QStringLiteral("\n"); + } else if ((character == '\t') || character.isPrint()) { + return QString(character); + } else { + return QString(); + } +} + ScopeVis *PSK31Demod::getScopeSink() { return m_basebandSink->getScopeSink(); @@ -552,9 +567,14 @@ void PSK31Demod::webapiFormatChannelReport(SWGSDRangel::SWGChannelReport& respon response.getPSK31DemodReport()->setChannelPowerDb(CalcDb::dbPower(magsqAvg)); response.getPSK31DemodReport()->setChannelSampleRate(m_basebandSink->getChannelSampleRate()); - response.getPSK31DemodReport()->setFrequencyOffset(getFrequencyOffset()); - response.getPSK31DemodReport()->setSnr(getSNR()); response.getPSK31DemodReport()->setLocked(isLocked() ? 1 : 0); + + // Only meaningful when a signal is being received + if (isLocked()) + { + response.getPSK31DemodReport()->setFrequencyOffset(getFrequencyOffset()); + response.getPSK31DemodReport()->setSnr(getSNR()); + } } void PSK31Demod::webapiReverseSendSettings(const QList& channelSettingsKeys, const PSK31DemodSettings& settings, bool force) diff --git a/plugins/channelrx/demodpsk31/psk31demod.h b/plugins/channelrx/demodpsk31/psk31demod.h index 4675103ce..82c209c7e 100644 --- a/plugins/channelrx/demodpsk31/psk31demod.h +++ b/plugins/channelrx/demodpsk31/psk31demod.h @@ -185,6 +185,11 @@ public: uint32_t getNumberOfDeviceStreams() const; + // Text to display for a received character. Senders usually end lines + // with CR LF, so CR, LF and CR LF each give a single newline. Other + // control characters, which are most likely noise, give nothing. + static QString displayText(QChar character, QChar previousCharacter); + static const char * const m_channelIdURI; static const char * const m_channelId; @@ -198,6 +203,7 @@ private: QUdpSocket m_udpSocket; QFile m_logFile; QTextStream m_logStream; + QChar m_previousLogCharacter; QNetworkAccessManager *m_networkManager; QNetworkRequest m_networkRequest; diff --git a/plugins/channelrx/demodpsk31/psk31demodgui.cpp b/plugins/channelrx/demodpsk31/psk31demodgui.cpp index d05e7f403..98dd9e7d0 100644 --- a/plugins/channelrx/demodpsk31/psk31demodgui.cpp +++ b/plugins/channelrx/demodpsk31/psk31demodgui.cpp @@ -91,15 +91,22 @@ void PSK31DemodGUI::characterReceived(QString c) // Restore scroll position ui->text->verticalScrollBar()->setValue(scrollPos); - if (c == '\b') + const QChar character = c.isEmpty() ? QChar() : c[0]; + + if (character == '\b') { ui->text->textCursor().deletePreviousChar(); } else { - ui->text->insertPlainText(c); + const QString text = PSK31Demod::displayText(character, m_previousCharacter); + if (!text.isEmpty()) { + ui->text->insertPlainText(text); + } } + m_previousCharacter = character; + // Scroll to bottom, if we we're previously at the bottom if (atBottom) { ui->text->verticalScrollBar()->setValue(ui->text->verticalScrollBar()->maximum()); diff --git a/plugins/channelrx/demodpsk31/psk31demodgui.h b/plugins/channelrx/demodpsk31/psk31demodgui.h index 4bef79fb7..c12e113e3 100644 --- a/plugins/channelrx/demodpsk31/psk31demodgui.h +++ b/plugins/channelrx/demodpsk31/psk31demodgui.h @@ -80,6 +80,7 @@ private: PSK31Demod* m_psk31Demod; int m_basebandSampleRate; uint32_t m_tickCount; + QChar m_previousCharacter; MessageQueue m_inputMessageQueue; explicit PSK31DemodGUI(PluginAPI* pluginAPI, DeviceUISet *deviceUISet, BasebandSampleSink *rxChannel, QWidget* parent = 0); diff --git a/plugins/channelrx/demodpsk31/psk31demodsink.cpp b/plugins/channelrx/demodpsk31/psk31demodsink.cpp index dfe0a284b..ea6f508c6 100644 --- a/plugins/channelrx/demodpsk31/psk31demodsink.cpp +++ b/plugins/channelrx/demodpsk31/psk31demodsink.cpp @@ -17,242 +17,49 @@ // along with this program. If not, see . // /////////////////////////////////////////////////////////////////////////////////// -#include -#include - #include "dsp/scopevis.h" -#ifndef PSK31_DEMOD_SINK_BENCH + #include "psk31demod.h" -#endif #include "psk31demodsink.h" PSK31DemodSink::PSK31DemodSink() : m_scopeSink(nullptr), m_messageQueueToChannel(nullptr), - m_channelSampleRate(m_internalSampleRate), + m_channelSampleRate(PSK31DemodSettings::PSK31DEMOD_CHANNEL_SAMPLE_RATE), m_channelFrequencyOffset(0), - m_interpolatorDistance(1.0f), - m_interpolatorDistanceRemain(1.0f), - m_costasLoop(2.0f * M_PI / 300.0f, 2), - m_magsq(0.0), - m_magsqSum(0.0), - m_magsqPeak(0.0), - m_magsqCount(0), - m_snrInPhaseSum(0.0), - m_snrQuadratureSum(0.0), - m_snrCount(0), - m_snr(0.0f), - m_clockCount(m_samplesPerSymbol / 2), - m_previousPolarity(false), - m_lockCount(0), - m_unlockCount(0), - m_locked(false), - m_reportSampleCount(0), m_scopeBufferIndex(0) { m_scopeBuffer.resize(m_scopeBufferSize); + m_demodulator.setCharacterCallback([this](QChar character) { characterReceived(character); }); + m_demodulator.setReportCallback([this]() { report(); }); + m_demodulator.setScopeCallback([this](const Complex& sample) { sampleToScope(sample); }); applySettings(QStringList(), m_settings, true); applyChannelSettings(m_channelSampleRate, m_channelFrequencyOffset, true); } void PSK31DemodSink::feed(const SampleVector::const_iterator& begin, const SampleVector::const_iterator& end) { - Complex output; - - for (SampleVector::const_iterator it = begin; it != end; ++it) - { - Complex sample(it->real(), it->imag()); - sample *= m_nco.nextIQ(); - - if (m_interpolatorDistance < 1.0f) - { - while (!m_interpolator.interpolate(&m_interpolatorDistanceRemain, sample, &output)) - { - processOneSample(output); - m_interpolatorDistanceRemain += m_interpolatorDistance; - } - } - else if (m_interpolator.decimate(&m_interpolatorDistanceRemain, sample, &output)) - { - processOneSample(output); - m_interpolatorDistanceRemain += m_interpolatorDistance; - } - } + m_demodulator.feed(begin, end); } -void PSK31DemodSink::processOneSample(Complex sample) +void PSK31DemodSink::characterReceived(QChar character) { - const double magsqRaw = sample.real() * sample.real() + sample.imag() * sample.imag(); - const Real magsq = magsqRaw / (SDR_RX_SCALED * SDR_RX_SCALED); - m_movingAverage(magsq); - m_magsq = m_movingAverage.asDouble(); - m_magsqSum += magsq; - m_magsqPeak = std::max(m_magsqPeak, static_cast(magsq)); - ++m_magsqCount; - - if (m_magsqCount >= m_internalSampleRate / 10) - { - m_magSqLevelStore.m_magsq = m_magsqSum / m_magsqCount; - m_magSqLevelStore.m_magsqPeak = m_magsqPeak; - m_magSqLevelStore.m_nbSamples = m_magsqCount; - m_magsqSum = 0.0; - m_magsqPeak = 0.0; - m_magsqCount = 0; + if (m_messageQueueToChannel) { + m_messageQueueToChannel->push(PSK31Demod::MsgCharacter::create(QString(character))); } - - sample /= SDR_RX_SCALEF; - sample = m_lowpass.filter(sample); - - // The Costas detector gain is proportional to input power. Normalize from - // the short-term envelope so acquisition bandwidth does not collapse for - // signals below full scale, while preserving the shaped zero crossings. - // The recovered carrier is applied to the original sample below. - const Real carrierScale = 1.0f / std::max(static_cast(std::sqrt(m_magsq)), 1.0e-4f); - m_costasLoop.feed(sample.real() * carrierScale, sample.imag() * carrierScale); - const Complex carrier = -std::conj(m_costasLoop.getComplex()); - const Complex corrected = sample * carrier; - const Real correctedMagnitude = std::abs(corrected); - - if (correctedMagnitude > 0.0f) { - m_lockAverage((std::abs(corrected.real()) - std::abs(corrected.imag())) / correctedMagnitude); - } else { - m_lockAverage(0.0f); - } - - const bool lockDetected = m_lockAverage.instantAverage() > 0.35f; - - // Use a Schmitt decision for transition timing. A pulse-shaped BPSK phase - // reversal crosses zero, so testing the instantaneous magnitude at the - // sign change suppresses the very transition needed to recenter the clock. - bool polarity = m_previousPolarity; - const Real polarityThreshold = 0.2f * std::sqrt(m_magsq); - if (corrected.real() > polarityThreshold) { - polarity = true; - } else if (corrected.real() < -polarityThreshold) { - polarity = false; - } - - if (polarity != m_previousPolarity) - { - // A phase reversal should occur half a symbol before the next sample. - // Nudge the free-running clock toward that point rather than resetting - // it, so an isolated noise crossing cannot insert or delete a symbol. - const Real timingError = m_samplesPerSymbol / 2.0f - m_clockCount; - const Real correction = std::clamp( - m_timingGain * timingError, - -m_maxTimingCorrection, - m_maxTimingCorrection); - m_clockCount += correction; - } - m_previousPolarity = polarity; - - bool symbolSample = false; - m_clockCount -= 1.0f; - - if (m_clockCount <= 0.0f) - { - const bool wasLocked = m_locked; - - // Qualify lock at symbol rate. Noise can briefly cross the instantaneous - // lock threshold, so require a sustained acquisition before accepting - // bits and use a short dropout hysteresis once a signal is acquired. - if (lockDetected) - { - m_unlockCount = 0; - m_lockCount = std::min(m_lockCount + 1, m_lockConfirmSymbols); - m_locked = m_locked || (m_lockCount >= m_lockConfirmSymbols); - } - else - { - m_lockCount = 0; - m_unlockCount = std::min(m_unlockCount + 1, m_unlockConfirmSymbols); - m_locked = m_locked && (m_unlockCount < m_unlockConfirmSymbols); - } - - if (m_locked) { - receiveSymbol(polarity); - } else { - resetDecoder(); - } - - if (m_locked && !wasLocked) - { - // Start a fresh one-second measurement at acquisition. Otherwise - // the first locked report includes pre-lock samples and reads low. - resetSNR(); - m_reportSampleCount = 0; - } - - m_clockCount += m_samplesPerSymbol; - symbolSample = true; - } - - if (m_locked) - { - m_snrInPhaseSum += corrected.real() * corrected.real(); - m_snrQuadratureSum += corrected.imag() * corrected.imag(); - ++m_snrCount; - } - - if (++m_reportSampleCount >= m_internalSampleRate) - { - if (m_locked && (m_snrCount > 0)) - { - const double inPhasePower = m_snrInPhaseSum / m_snrCount; - const double quadraturePower = m_snrQuadratureSum / m_snrCount; - const double signalPower = std::max(inPhasePower - quadraturePower, 1.0e-20); - const double measuredNoisePower = std::max(2.0 * quadraturePower, 1.0e-20); - const double referenceNoisePower = measuredNoisePower - * m_snrReferenceBandwidth / m_settings.m_rfBandwidth; - m_snr = std::clamp( - static_cast(10.0 * std::log10(signalPower / referenceNoisePower)), - -99.9f, - 99.9f); - resetSNR(); - } - -#ifndef PSK31_DEMOD_SINK_BENCH - if (m_messageQueueToChannel) { - m_messageQueueToChannel->push( - PSK31Demod::MsgDemodReport::create(getFrequencyOffset(), m_snr, m_locked)); - } -#endif - m_reportSampleCount = 0; - } - - sampleToScope(Complex(corrected.real(), symbolSample ? 1.0f : 0.0f)); } -void PSK31DemodSink::receiveSymbol(bool symbol) +void PSK31DemodSink::report() { - QChar character; - if (m_decoder.decodeSymbol(symbol, character)) + if (m_messageQueueToChannel) { -#ifndef PSK31_DEMOD_SINK_BENCH - if (m_messageQueueToChannel) - { - PSK31Demod::MsgCharacter *message = PSK31Demod::MsgCharacter::create(QString(character)); - m_messageQueueToChannel->push(message); - } -#endif - if (m_characterSink) { - m_characterSink(character); - } + m_messageQueueToChannel->push(PSK31Demod::MsgDemodReport::create( + m_demodulator.getFrequencyOffset(), + m_demodulator.getSNR(), + m_demodulator.isLocked())); } } -void PSK31DemodSink::resetDecoder() -{ - m_decoder.reset(); -} - -void PSK31DemodSink::resetSNR() -{ - m_snrInPhaseSum = 0.0; - m_snrQuadratureSum = 0.0; - m_snrCount = 0; -} - void PSK31DemodSink::sampleToScope(const Complex& sample) { if (!m_scopeSink) { @@ -277,22 +84,9 @@ void PSK31DemodSink::applyChannelSettings(int channelSampleRate, int channelFreq if ((channelSampleRate != m_channelSampleRate) || (channelFrequencyOffset != m_channelFrequencyOffset) || force) { - m_nco.setFreq(-channelFrequencyOffset, channelSampleRate); - m_interpolator.create(32, channelSampleRate, m_settings.m_rfBandwidth / 2.0f); - m_interpolatorDistance = static_cast(channelSampleRate) / m_internalSampleRate; - m_interpolatorDistanceRemain = m_interpolatorDistance; + m_demodulator.setChannel(channelSampleRate, channelFrequencyOffset); m_channelSampleRate = channelSampleRate; m_channelFrequencyOffset = channelFrequencyOffset; - m_costasLoop.reset(); - m_lockAverage.reset(); - m_lockCount = 0; - m_unlockCount = 0; - m_locked = false; - resetSNR(); - m_snr = 0.0f; - m_clockCount = m_samplesPerSymbol / 2; - m_previousPolarity = false; - resetDecoder(); } } @@ -301,16 +95,8 @@ void PSK31DemodSink::applySettings(const QStringList& settingsKeys, const PSK31D PSK31DemodSettings validatedSettings = settings; validatedSettings.m_rfBandwidth = PSK31DemodSettings::validateRFBandwidth(settings.m_rfBandwidth); - if (settingsKeys.contains("rfBandwidth") || force) - { - m_interpolator.create(32, m_channelSampleRate, validatedSettings.m_rfBandwidth / 2.0f); - m_lowpass.create(129, m_internalSampleRate, validatedSettings.m_rfBandwidth / 2.0f); - const Real maxFrequency = std::max(5.0f, validatedSettings.m_rfBandwidth / 2.0f - 20.0f); - m_costasLoop.setMaxFreq(maxFrequency * 2.0f * M_PI / m_internalSampleRate); - m_costasLoop.setMinFreq(-maxFrequency * 2.0f * M_PI / m_internalSampleRate); - resetSNR(); - m_snr = 0.0f; - m_reportSampleCount = 0; + if (settingsKeys.contains("rfBandwidth") || force) { + m_demodulator.setRFBandwidth(validatedSettings.m_rfBandwidth); } if (force) { @@ -319,8 +105,3 @@ void PSK31DemodSink::applySettings(const QStringList& settingsKeys, const PSK31D m_settings.applySettings(settingsKeys, validatedSettings); } } - -float PSK31DemodSink::getFrequencyOffset() const -{ - return m_costasLoop.getFreq() * m_internalSampleRate / (2.0f * M_PI); -} diff --git a/plugins/channelrx/demodpsk31/psk31demodsink.h b/plugins/channelrx/demodpsk31/psk31demodsink.h index 208796430..f99355947 100644 --- a/plugins/channelrx/demodpsk31/psk31demodsink.h +++ b/plugins/channelrx/demodpsk31/psk31demodsink.h @@ -20,19 +20,11 @@ #ifndef INCLUDE_PSK31DEMODSINK_H #define INCLUDE_PSK31DEMODSINK_H -#include - #include "dsp/channelsamplesink.h" -#include "dsp/costasloop.h" -#include "dsp/interpolator.h" -#include "dsp/firfilter.h" -#include "dsp/nco.h" -#include "dsp/dsptypes.h" #include "util/messagequeue.h" -#include "util/movingaverage.h" -#include "util/psk31.h" #include "psk31demodsettings.h" +#include "psk31demodulator.h" class ScopeVis; @@ -47,81 +39,30 @@ public: void applySettings(const QStringList& settingsKeys, const PSK31DemodSettings& settings, bool force = false); void setScopeSink(ScopeVis *scopeSink) { m_scopeSink = scopeSink; } void setMessageQueueToChannel(MessageQueue *queue) { m_messageQueueToChannel = queue; } - void setCharacterSink(const std::function& sink) { m_characterSink = sink; } -#ifdef PSK31_DEMOD_SINK_BENCH - void feedTestSample(const Complex& normalizedSample) { processOneSample(normalizedSample * SDR_RX_SCALEF); } -#endif - double getMagSq() const { return m_magsq; } - float getFrequencyOffset() const; - float getSNR() const { return m_snr; } - bool isLocked() const { return m_locked; } + double getMagSq() const { return m_demodulator.getMagSq(); } + float getFrequencyOffset() const { return m_demodulator.getFrequencyOffset(); } + float getSNR() const { return m_demodulator.getSNR(); } + bool isLocked() const { return m_demodulator.isLocked(); } - void getMagSqLevels(double& avg, double& peak, int& nbSamples) - { - avg = m_magSqLevelStore.m_magsq; - peak = m_magSqLevelStore.m_magsqPeak; - nbSamples = m_magSqLevelStore.m_nbSamples; + void getMagSqLevels(double& avg, double& peak, int& nbSamples) { + m_demodulator.getMagSqLevels(avg, peak, nbSamples); } private: - struct MagSqLevelsStore - { - MagSqLevelsStore() : m_magsq(1e-12), m_magsqPeak(1e-12), m_nbSamples(1) {} - double m_magsq; - double m_magsqPeak; - int m_nbSamples; - }; - - static const int m_internalSampleRate = 1000; - static const int m_samplesPerSymbol = 32; static const int m_scopeBufferSize = 50; - static const int m_lockConfirmSymbols = 8; - static const int m_unlockConfirmSymbols = 2; - static constexpr Real m_snrReferenceBandwidth = 100.0f; - static constexpr Real m_timingGain = 0.25f; - static constexpr Real m_maxTimingCorrection = 2.0f; ScopeVis *m_scopeSink; MessageQueue *m_messageQueueToChannel; PSK31DemodSettings m_settings; - int m_channelSampleRate; int m_channelFrequencyOffset; - NCO m_nco; - Interpolator m_interpolator; - Real m_interpolatorDistance; - Real m_interpolatorDistanceRemain; - Lowpass m_lowpass; - CostasLoop m_costasLoop; - - MovingAverageUtil m_movingAverage; - MovingAverageUtil m_lockAverage; - double m_magsq; - double m_magsqSum; - double m_magsqPeak; - int m_magsqCount; - MagSqLevelsStore m_magSqLevelStore; - double m_snrInPhaseSum; - double m_snrQuadratureSum; - int m_snrCount; - float m_snr; - - Real m_clockCount; - bool m_previousPolarity; - int m_lockCount; - int m_unlockCount; - bool m_locked; - int m_reportSampleCount; - PSK31Decoder m_decoder; - std::function m_characterSink; + PSK31Demodulator m_demodulator; SampleVector m_scopeBuffer; int m_scopeBufferIndex; - void processOneSample(Complex sample); - void receiveSymbol(bool symbol); - void resetDecoder(); - void resetSNR(); + void characterReceived(QChar character); + void report(); void sampleToScope(const Complex& sample); }; diff --git a/plugins/channelrx/demodpsk31/psk31demodulator.cpp b/plugins/channelrx/demodpsk31/psk31demodulator.cpp new file mode 100644 index 000000000..de01e9975 --- /dev/null +++ b/plugins/channelrx/demodpsk31/psk31demodulator.cpp @@ -0,0 +1,646 @@ +/////////////////////////////////////////////////////////////////////////////////// +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include + +#include "psk31demodulator.h" + +PSK31Demodulator::PSK31Demodulator() : + m_rfBandwidth(100.0f), + m_channelSampleRate(m_sampleRate), + m_channelFrequencyOffset(0), + m_interpolatorDistance(1.0f), + m_interpolatorDistanceRemain(1.0f), + m_costasLoop(2.0f * M_PI / 300.0f, 2), + m_maxFrequency(0.0f), + m_trackingCutoff(0.0f), + m_trackingNoiseBandwidth(1.0f), + m_afcFrequency(0.0f), + m_afcPhase(0.0f), + m_magsq(0.0), + m_magsqSum(0.0), + m_magsqPeak(0.0), + m_magsqCount(0), + m_afcIndex(0), + m_afcCount(0), + m_afcCandidate(0.0f), + m_afcCandidateValid(false), + m_matchedFilterIndex(0), + m_historyIndex(0), + m_symbolPower(0.0f), + m_clockCount(0.0f), + m_timingIntegrator(0.0f), + m_lockMetric(0.0f), + m_lockCount(0), + m_presentCount(0), + m_unlockCount(0), + m_lockedLevel(0.0f), + m_locked(false), + m_snrInPhaseSum(0.0), + m_snrQuadratureSum(0.0), + m_snrCount(0), + m_snrSignalPower(0.0), + m_snrNoisePower(0.0), + m_snrAverageValid(false), + m_snr(0.0f), + m_reportSampleCount(0) +{ + // PSK31 shapes each phase reversal with a cosine envelope, so each symbol + // is a raised cosine pulse spanning two symbol periods. Matching it + // restricts the noise at the decision point to roughly the symbol rate. + const int matchedFilterLength = 2 * m_samplesPerSymbol + 1; + m_matchedFilterTaps.resize(matchedFilterLength); + Real sum = 0.0f; + for (int i = 0; i < matchedFilterLength; ++i) + { + m_matchedFilterTaps[i] = 0.5f - 0.5f * std::cos(2.0f * M_PI * i / (matchedFilterLength - 1)); + sum += m_matchedFilterTaps[i]; + } + for (auto& tap : m_matchedFilterTaps) { + tap /= sum; + } + m_matchedFilterSamples.resize(matchedFilterLength); + m_history.resize(m_samplesPerSymbol + 1); + + m_afcBuffer.resize(m_afcLength); + m_afcTwiddle.resize(m_afcLength); + m_afcWindow.resize(m_afcLength); + for (int i = 0; i < m_afcLength; ++i) + { + m_afcTwiddle[i] = Complex(std::cos(2.0 * M_PI * i / m_afcLength), -std::sin(2.0 * M_PI * i / m_afcLength)); + m_afcWindow[i] = 0.5f - 0.5f * std::cos(2.0f * M_PI * i / m_afcLength); + } + + setRFBandwidth(m_rfBandwidth); + setChannel(m_channelSampleRate, m_channelFrequencyOffset); +} + +void PSK31Demodulator::setChannel(int channelSampleRate, int channelFrequencyOffset) +{ + m_nco.setFreq(-channelFrequencyOffset, channelSampleRate); + m_interpolator.create(32, channelSampleRate, m_rfBandwidth / 2.0f); + m_interpolatorDistance = static_cast(channelSampleRate) / m_sampleRate; + m_interpolatorDistanceRemain = m_interpolatorDistance; + m_channelSampleRate = channelSampleRate; + m_channelFrequencyOffset = channelFrequencyOffset; + reset(); +} + +void PSK31Demodulator::setRFBandwidth(Real rfBandwidth) +{ + m_rfBandwidth = std::isfinite(rfBandwidth) ? std::clamp(rfBandwidth, 20.0f, m_sampleRate / 2.0f) : 100.0f; + m_interpolator.create(32, m_channelSampleRate, m_rfBandwidth / 2.0f); + m_channelFilter.create(m_channelFilterTaps, m_sampleRate, m_rfBandwidth / 2.0f); + m_trackingCutoff = std::min(m_trackingBandwidth, m_rfBandwidth) / 2.0f; + m_trackingFilter.create(m_channelFilterTaps, m_sampleRate, m_trackingCutoff); + + // Equivalent noise bandwidth of the tracking filter, for SNR normalization + std::vector taps; + FirFilterGenerators::generateLowPassFilter(m_channelFilterTaps, m_sampleRate, m_trackingCutoff, taps); + double sum = 0.0; + double sumSquares = 0.0; + for (size_t i = 0; i < taps.size(); ++i) + { + // Only half the symmetric taps are stored. The last is the center. + const int weight = (i == taps.size() - 1) ? 1 : 2; + sum += weight * taps[i]; + sumSquares += weight * taps[i] * taps[i]; + } + m_trackingNoiseBandwidth = m_sampleRate * sumSquares / (sum * sum); + + // Leave room for the signal's main lobe inside the channel filter. + m_maxFrequency = std::max(5.0f, m_rfBandwidth / 2.0f - 15.0f); + m_costasLoop.setMaxFreq(m_costasRange * 2.0f * M_PI / m_sampleRate); + m_costasLoop.setMinFreq(-m_costasRange * 2.0f * M_PI / m_sampleRate); + + resetSNR(); + m_snrAverageValid = false; + m_snr = 0.0f; + m_reportSampleCount = 0; +} + +void PSK31Demodulator::reset() +{ + m_costasLoop.reset(); + m_lockMetric = 0.0f; + m_levelAverage.reset(); + m_signalLevelAverage.reset(); + m_lockCount = 0; + m_presentCount = 0; + m_unlockCount = 0; + m_lockedLevel = 0.0f; + m_locked = false; + m_pendingCharacters.clear(); + m_acquisitionSymbols.clear(); + m_decoder.reset(); + resetSNR(); + m_snrAverageValid = false; + m_snr = 0.0f; + m_clockCount = m_samplesPerSymbol / 2; + m_timingIntegrator = 0.0f; + m_symbolPower = 0.0f; + m_afcFrequency = 0.0f; + m_afcPhase = 0.0f; + std::fill(m_matchedFilterSamples.begin(), m_matchedFilterSamples.end(), Complex(0.0f, 0.0f)); + std::fill(m_history.begin(), m_history.end(), 0.0f); + std::fill(m_afcBuffer.begin(), m_afcBuffer.end(), Complex(0.0f, 0.0f)); + m_afcIndex = 0; + m_afcCount = 0; + m_afcCandidate = 0.0f; + m_afcCandidateValid = false; +} + +void PSK31Demodulator::feed(const SampleVector::const_iterator& begin, const SampleVector::const_iterator& end) +{ + Complex output; + + for (SampleVector::const_iterator it = begin; it != end; ++it) + { + Complex sample(it->real(), it->imag()); + sample *= m_nco.nextIQ(); + + if (m_interpolatorDistance < 1.0f) + { + while (!m_interpolator.interpolate(&m_interpolatorDistanceRemain, sample, &output)) + { + processSample(output / SDR_RX_SCALEF); + m_interpolatorDistanceRemain += m_interpolatorDistance; + } + } + else if (m_interpolator.decimate(&m_interpolatorDistanceRemain, sample, &output)) + { + processSample(output / SDR_RX_SCALEF); + m_interpolatorDistanceRemain += m_interpolatorDistance; + } + } +} + +void PSK31Demodulator::processSample(const Complex& input) +{ + // Measure levels after the channel filter so signals outside the RF + // bandwidth do not reduce loop gain or distort the channel power reading. + const Complex sample = m_channelFilter.filter(input); + const Real magsq = std::norm(sample); + m_movingAverage(magsq); + m_magsq = m_movingAverage.asDouble(); + m_magsqSum += magsq; + m_magsqPeak = std::max(m_magsqPeak, static_cast(magsq)); + ++m_magsqCount; + + if (m_magsqCount >= m_sampleRate / 10) + { + m_magSqLevelStore.m_magsq = m_magsqSum / m_magsqCount; + m_magSqLevelStore.m_magsqPeak = m_magsqPeak; + m_magSqLevelStore.m_nbSamples = m_magsqCount; + m_magsqSum = 0.0; + m_magsqPeak = 0.0; + m_magsqCount = 0; + } + + acquireCarrier(sample); + + // Move the acquired carrier to the center of the narrower tracking filter, + // which keeps adjacent signals out of the carrier and timing loops. + m_afcPhase += m_afcFrequency; + if (m_afcPhase > M_PI) { + m_afcPhase -= 2.0f * M_PI; + } else if (m_afcPhase < -M_PI) { + m_afcPhase += 2.0f * M_PI; + } + const Complex tracked = m_trackingFilter.filter(sample * Complex(std::cos(m_afcPhase), -std::sin(m_afcPhase))); + + // The Costas detector gain is proportional to input power. Normalize over + // two symbols so acquisition bandwidth does not depend on signal level. + m_levelAverage(std::norm(tracked)); + m_signalLevelAverage(std::norm(tracked)); + const Real scale = 1.0f / std::sqrt(std::max(m_levelAverage.asDouble(), 1.0e-20)); + const Complex normalized = tracked * scale; + m_costasLoop.feed(normalized.real(), normalized.imag()); + + if (m_locked) + { + // Slowly move the Costas loop's frequency into the AFC, so the signal + // stays centered in the tracking filter as it drifts. + const Real transfer = m_costasLoop.getFreq() * m_afcTransferRate; + m_afcFrequency += transfer; + m_costasLoop.setFreq(m_costasLoop.getFreq() - transfer); + } + + const Complex corrected = normalized * -std::conj(m_costasLoop.getComplex()); + const Complex symbolValue = matchedFilter(corrected); + const Real filtered = symbolValue.real(); + m_historyIndex = (m_historyIndex + 1) % m_history.size(); + m_history[m_historyIndex] = filtered; + + bool symbolSample = false; + m_clockCount -= 1.0f; + + if (m_clockCount <= 0.0f) + { + // Gardner timing error: the matched filter output half way between + // opposite symbols should be zero. Transitions provide the timing + // information, so steady carrier leaves the clock free running. + const int size = m_history.size(); + const Real previous = m_history[(m_historyIndex + 1) % size]; + const Real middle = m_history[(m_historyIndex + 1 + m_samplesPerSymbol / 2) % size]; + m_symbolPower += 0.05f * (filtered * filtered - m_symbolPower); + const Real timingError = m_symbolPower > 0.0f + ? std::clamp(middle * (previous - filtered) / m_symbolPower, -m_maxTimingError, m_maxTimingError) + : 0.0f; + // Proportional plus integral, so a sample clock offset between + // transmitter and receiver does not leave a steady timing error. + m_timingIntegrator = std::clamp( + m_timingIntegrator + m_timingIntegralGain * timingError, + -m_maxTimingRate, + m_maxTimingRate); + m_clockCount += m_samplesPerSymbol + m_timingGain * timingError + m_timingIntegrator; + + symbol(symbolValue); + symbolSample = true; + } + + if (m_locked && (m_unlockCount == 0)) + { + m_snrInPhaseSum += corrected.real() * corrected.real(); + m_snrQuadratureSum += corrected.imag() * corrected.imag(); + ++m_snrCount; + } + + if (++m_reportSampleCount >= m_sampleRate) + { + if (m_locked && (m_snrCount > 0)) + { + const double inPhasePower = m_snrInPhaseSum / m_snrCount; + const double quadraturePower = m_snrQuadratureSum / m_snrCount; + const double signalPower = std::max(inPhasePower - quadraturePower, 1.0e-20); + const double noisePower = std::max(2.0 * quadraturePower, 1.0e-20); + + // Average over a few seconds for a steadier reading + if (m_snrAverageValid) + { + m_snrSignalPower += 0.5 * (signalPower - m_snrSignalPower); + m_snrNoisePower += 0.5 * (noisePower - m_snrNoisePower); + } + else + { + m_snrSignalPower = signalPower; + m_snrNoisePower = noisePower; + m_snrAverageValid = true; + } + + const double referenceNoisePower = m_snrNoisePower * m_snrReferenceBandwidth / m_trackingNoiseBandwidth; + m_snr = std::clamp( + static_cast(10.0 * std::log10(m_snrSignalPower / referenceNoisePower)), + -99.9f, + 99.9f); + resetSNR(); + } + + if (m_reportCallback) { + m_reportCallback(); + } + + m_reportSampleCount = 0; + } + + if (m_scopeCallback) + { + const Real normalizedFiltered = m_symbolPower > 0.0f ? filtered / std::sqrt(m_symbolPower) : 0.0f; + m_scopeCallback(Complex(normalizedFiltered, symbolSample ? 1.0f : 0.0f)); + } +} + +void PSK31Demodulator::acquireCarrier(const Complex& sample) +{ + // Squaring BPSK removes the modulation, leaving a tone at twice the + // carrier offset. Search for it and tune there, as the Costas loop itself + // only pulls in over a few Hz. + m_afcBuffer[m_afcIndex] = sample * sample; + m_afcIndex = (m_afcIndex + 1) % m_afcLength; + + if (m_afcCount < m_afcLength) + { + ++m_afcCount; + return; + } + + if ((m_afcIndex % m_afcInterval) != 0) { + return; + } + + const Real current = getFrequencyOffset(); + + if (m_locked) + { + checkIdleToneLock(current); + return; + } + + const int maxBin = static_cast(2.0f * m_maxFrequency * m_afcLength / m_sampleRate); + int peakBin = -maxBin; + Real peakPower = 0.0f; + m_afcPowers.resize(2 * maxBin + 1); + + for (int bin = -maxBin; bin <= maxBin; ++bin) + { + const Real power = afcPower(bin); + m_afcPowers[bin + maxBin] = power; + + if (power > peakPower) + { + peakPower = power; + peakBin = bin; + } + } + + // Compare against the median, as the signal's own tones would inflate a mean. + m_afcSorted = m_afcPowers; + std::nth_element(m_afcSorted.begin(), m_afcSorted.begin() + m_afcSorted.size() / 2, m_afcSorted.end()); + const Real noisePower = m_afcSorted[m_afcSorted.size() / 2]; + + if ((noisePower <= 0.0f) || (peakPower < m_afcThreshold * noisePower)) { + return; + } + + // Parabolic interpolation between bins + Real delta = 0.0f; + if ((peakBin > -maxBin) && (peakBin < maxBin)) + { + const Real left = m_afcPowers[peakBin + maxBin - 1]; + const Real right = m_afcPowers[peakBin + maxBin + 1]; + const Real denominator = left - 2.0f * peakPower + right; + if (denominator != 0.0f) { + delta = std::clamp(0.5f * (left - right) / denominator, -0.5f, 0.5f); + } + } + + const Real frequency = std::clamp( + (peakBin + delta) * m_sampleRate / (2.0f * m_afcLength), + -m_maxFrequency, + m_maxFrequency); + + if (std::abs(frequency - current) > m_afcRetuneHz) { + retune(frequency); + } +} + +void PSK31Demodulator::checkIdleToneLock(Real current) +{ + // An idle signal is two tones, one symbol rate apart. To the Costas loop, + // either looks like an unmodulated carrier, so it can lock 15.6 Hz from the + // true carrier. Squared, the true carrier's tone is then 6 dB stronger than + // the one at our frequency. Only these bins are checked, so strong signals + // elsewhere in the RF bandwidth can't pull us away once locked. + const int centerBin = static_cast(std::lround(2.0f * current * m_afcLength / m_sampleRate)); + const int offsetBins = static_cast(std::lround(m_sampleRate / static_cast(m_samplesPerSymbol) * m_afcLength / m_sampleRate)); + const int maxBin = static_cast(2.0f * m_maxFrequency * m_afcLength / m_sampleRate); + Real centerPower = 0.0f; + Real sidePower = 0.0f; + int sideBin = 0; + + for (int bin = centerBin - 1; bin <= centerBin + 1; ++bin) { + centerPower = std::max(centerPower, afcPower(bin)); + } + + for (int side : {centerBin - offsetBins, centerBin + offsetBins}) + { + for (int bin = side - 1; bin <= side + 1; ++bin) + { + if (std::abs(bin) > maxBin) { + continue; + } + + const Real power = afcPower(bin); + if (power > sidePower) + { + sidePower = power; + sideBin = bin; + } + } + } + + if (sidePower <= m_afcIdleToneRatio * centerPower) + { + m_afcCandidateValid = false; + return; + } + + // Require consecutive estimates to agree before moving. + const Real frequency = sideBin * m_sampleRate / (2.0f * m_afcLength); + + if (m_afcCandidateValid && (std::abs(frequency - m_afcCandidate) < m_afcRetuneHz)) { + retune(frequency); + } + else + { + m_afcCandidate = frequency; + m_afcCandidateValid = true; + } +} + +Real PSK31Demodulator::afcPower(int bin) const +{ + Complex sum(0.0f, 0.0f); + const int step = ((bin % m_afcLength) + m_afcLength) % m_afcLength; + int twiddleIndex = 0; + + for (int i = 0; i < m_afcLength; ++i) + { + sum += m_afcWindow[i] * m_afcBuffer[(m_afcIndex + i) % m_afcLength] * m_afcTwiddle[twiddleIndex]; + twiddleIndex = (twiddleIndex + step) % m_afcLength; + } + + return std::norm(sum); +} + +void PSK31Demodulator::retune(Real frequency) +{ + m_afcFrequency = frequency * 2.0f * M_PI / m_sampleRate; + m_costasLoop.setFreq(0.0f); + m_afcCandidateValid = false; + + if (m_locked) + { + // Symbols during the retuning transient are unreliable, and before it + // the loop was on an idle tone, so there's nothing worth keeping. + m_pendingCharacters.clear(); + m_decoder.reset(); + } +} + +Complex PSK31Demodulator::matchedFilter(const Complex& sample) +{ + const int size = m_matchedFilterSamples.size(); + m_matchedFilterSamples[m_matchedFilterIndex] = sample; + Complex sum(0.0f, 0.0f); + int index = m_matchedFilterIndex; + + for (int i = 0; i < size; ++i) + { + sum += m_matchedFilterTaps[i] * m_matchedFilterSamples[index]; + index = (index == 0) ? size - 1 : index - 1; + } + + m_matchedFilterIndex = (m_matchedFilterIndex + 1) % size; + return sum; +} + +void PSK31Demodulator::symbol(const Complex& value) +{ + // When the carrier is tracked, symbols lie on the real axis. Noise has no + // preferred phase, so this averages to zero without a signal. + const Real power = std::norm(value); + const Real lockValue = power > 0.0f ? (value.real() * value.real() - value.imag() * value.imag()) / power : 0.0f; + m_lockMetric += m_lockMetricAlpha * (lockValue - m_lockMetric); + const bool lockDetected = m_lockMetric > m_lockThreshold; + + // The lock metric responds slowly when a signal ends, particularly as the + // Costas loop partly tracks noise. A drop in power from the level seen + // while locked shows that the signal has gone (or faded) much sooner. + // Average over four symbols, as power over shorter periods varies with + // the data: phase reversals have half the power of steady carrier. + const Real level = m_signalLevelAverage.asDouble(); + const bool signalPresent = lockDetected && (level > m_signalLossRatio * m_lockedLevel); + // With hysteresis, so noise at low SNR doesn't look like the signal returning + const bool signalReturned = lockDetected && (level > m_signalReturnRatio * m_lockedLevel); + + // Qualify lock at symbol rate. Noise can briefly cross the lock threshold, + // so require sustained acquisition before accepting bits. Once acquired, + // ride through short fades: characters decoded while the signal is absent + // are held back, then released if it returns or dropped if it doesn't. + m_lockCount = lockDetected ? std::min(m_lockCount + 1, m_lockConfirmSymbols) : 0; + m_presentCount = signalReturned ? std::min(m_presentCount + 1, m_relockConfirmSymbols) : 0; + const bool decision = value.real() >= 0.0f; + + if (!m_locked) + { + if (m_lockCount >= m_lockConfirmSymbols) + { + m_locked = true; + m_lockedLevel = level; + // Start a fresh one-second measurement at acquisition. Otherwise + // the first locked report includes pre-lock samples and reads low. + resetSNR(); + m_snrAverageValid = false; + m_reportSampleCount = 0; + + // Lock takes a while to confirm, and a transmission may not start + // with much idle, so decode the symbols received while confirming. + m_decoder.reset(); + for (bool previous : m_acquisitionSymbols) { + decode(previous); + } + } + else + { + m_acquisitionSymbols.push_back(decision); + if ((int) m_acquisitionSymbols.size() >= m_lockConfirmSymbols) { + m_acquisitionSymbols.pop_front(); + } + } + } + else if (m_unlockCount > 0) + { + // Noise alone can briefly raise the lock detector, so require a few + // consecutive symbols before accepting that the signal is back. + if (m_presentCount >= m_relockConfirmSymbols) { + m_unlockCount = 0; + } + else if (++m_unlockCount >= m_unlockConfirmSymbols) + { + unlock(); + } + } + else if (!signalPresent) + { + m_unlockCount = 1; + } + + if (m_locked && (m_unlockCount == 0)) { + m_lockedLevel += m_lockedLevelAlpha * (level - m_lockedLevel); + } + + if (m_locked) + { + decode(decision); + + // The lock detector takes a few symbols to respond when a signal ends, + // so only output characters once lock has been held for that long + // after them. Otherwise noise at the end of every transmission would + // be decoded. Output is paused during a fade. + if (m_unlockCount == 0) + { + for (auto& pending : m_pendingCharacters) { + --pending.second; + } + while (!m_pendingCharacters.empty() && (m_pendingCharacters.front().second <= 0)) + { + emitCharacter(m_pendingCharacters.front().first); + m_pendingCharacters.pop_front(); + } + } + } + else + { + m_decoder.reset(); + } +} + +void PSK31Demodulator::decode(bool symbol) +{ + QChar character; + if (m_decoder.decodeSymbol(symbol, character)) { + m_pendingCharacters.push_back({character, m_characterDelaySymbols}); + } +} + +void PSK31Demodulator::emitCharacter(QChar character) +{ + if (m_characterCallback) { + m_characterCallback(character); + } +} + +void PSK31Demodulator::unlock() +{ + m_locked = false; + m_unlockCount = 0; + // The lock metric decays slowly, so it may still be above threshold. + // Require fresh evidence of a signal, rather than relocking on noise. + m_lockMetric = 0.0f; + m_lockCount = 0; + m_presentCount = 0; + m_pendingCharacters.clear(); + m_acquisitionSymbols.clear(); + m_decoder.reset(); + resetSNR(); + m_snr = 0.0f; +} + +void PSK31Demodulator::resetSNR() +{ + m_snrInPhaseSum = 0.0; + m_snrQuadratureSum = 0.0; + m_snrCount = 0; +} + +float PSK31Demodulator::getFrequencyOffset() const +{ + return (m_afcFrequency + m_costasLoop.getFreq()) * m_sampleRate / (2.0f * M_PI); +} diff --git a/plugins/channelrx/demodpsk31/psk31demodulator.h b/plugins/channelrx/demodpsk31/psk31demodulator.h new file mode 100644 index 000000000..1cc106bbc --- /dev/null +++ b/plugins/channelrx/demodpsk31/psk31demodulator.h @@ -0,0 +1,195 @@ +/////////////////////////////////////////////////////////////////////////////////// +// 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_PSK31DEMODULATOR_H +#define INCLUDE_PSK31DEMODULATOR_H + +#include +#include +#include +#include + +#include + +#include "dsp/costasloop.h" +#include "dsp/dsptypes.h" +#include "dsp/firfilter.h" +#include "dsp/interpolator.h" +#include "dsp/nco.h" +#include "util/movingaverage.h" +#include "util/psk31.h" + +// PSK31 receiver core: channel filter, carrier acquisition, tracking filter, +// carrier tracking, matched filter, symbol timing recovery, differential +// detection and Varicode decoding. Samples are resampled to an internal rate +// of 1000 samples/s. +class PSK31Demodulator +{ +public: + static const int m_sampleRate = 1000; + static const int m_samplesPerSymbol = 32; + + PSK31Demodulator(); + + // Resamples from channelSampleRate after mixing channelFrequencyOffset to 0 Hz. + void setChannel(int channelSampleRate, int channelFrequencyOffset); + void setRFBandwidth(Real rfBandwidth); + Real getRFBandwidth() const { return m_rfBandwidth; } + + void feed(const SampleVector::const_iterator& begin, const SampleVector::const_iterator& end); + // Process one sample at the internal rate, normalized so full scale is 1.0. + void processSample(const Complex& sample); + void reset(); + + void setCharacterCallback(const std::function& callback) { m_characterCallback = callback; } + // Called once per second of samples. + void setReportCallback(const std::function& callback) { m_reportCallback = callback; } + // Called for every internal sample: real is the normalized matched filter + // output, imag is 1.0 at the symbol sampling instants and 0.0 otherwise. + void setScopeCallback(const std::function& callback) { m_scopeCallback = callback; } + + double getMagSq() const { return m_magsq; } + void getMagSqLevels(double& avg, double& peak, int& nbSamples) const + { + avg = m_magSqLevelStore.m_magsq; + peak = m_magSqLevelStore.m_magsqPeak; + nbSamples = m_magSqLevelStore.m_nbSamples; + } + float getFrequencyOffset() const; //!< Carrier offset from channel center in Hz + float getSNR() const { return m_snr; } //!< Only valid when isLocked() + bool isLocked() const { return m_locked; } + +private: + struct MagSqLevelsStore + { + MagSqLevelsStore() : m_magsq(1e-12), m_magsqPeak(1e-12), m_nbSamples(1) {} + double m_magsq; + double m_magsqPeak; + int m_nbSamples; + }; + + static const int m_channelFilterTaps = 255; + static const int m_lockConfirmSymbols = 20; + static const int m_relockConfirmSymbols = 4; + static const int m_unlockConfirmSymbols = 20; + static const int m_characterDelaySymbols = 8; + static constexpr Real m_lockMetricAlpha = 1.0f / 16.0f; + static constexpr Real m_lockThreshold = 0.5f; + static constexpr Real m_signalLossRatio = 0.35f; + static constexpr Real m_signalReturnRatio = 0.5f; + static constexpr Real m_lockedLevelAlpha = 1.0f / 32.0f; + static const int m_afcLength = 512; + static const int m_afcInterval = 256; + static constexpr Real m_snrReferenceBandwidth = 100.0f; + static constexpr Real m_trackingBandwidth = 70.0f; + static constexpr Real m_costasRange = 15.0f; + static constexpr Real m_timingGain = 1.0f; + static constexpr Real m_timingIntegralGain = 0.02f; + static constexpr Real m_maxTimingError = 2.0f; + static constexpr Real m_maxTimingRate = 1.0f; + static constexpr Real m_afcThreshold = 20.0f; + static constexpr Real m_afcRetuneHz = 2.0f; + static constexpr Real m_afcIdleToneRatio = 2.0f; + static constexpr Real m_afcTransferRate = 0.001f; + + Real m_rfBandwidth; + int m_channelSampleRate; + int m_channelFrequencyOffset; + NCO m_nco; + Interpolator m_interpolator; + Real m_interpolatorDistance; + Real m_interpolatorDistanceRemain; + Lowpass m_channelFilter; + Lowpass m_trackingFilter; + CostasLoop m_costasLoop; + Real m_maxFrequency; + Real m_trackingCutoff; + Real m_trackingNoiseBandwidth; //!< Hz + + // Levels + MovingAverageUtil m_movingAverage; + MovingAverageUtil m_levelAverage; + MovingAverageUtil m_signalLevelAverage; + double m_magsq; + double m_magsqSum; + double m_magsqPeak; + int m_magsqCount; + MagSqLevelsStore m_magSqLevelStore; + + // Carrier acquisition + std::vector m_afcBuffer; + std::vector m_afcTwiddle; + std::vector m_afcWindow; + std::vector m_afcPowers; + std::vector m_afcSorted; + int m_afcIndex; + int m_afcCount; + Real m_afcCandidate; //!< Hz + bool m_afcCandidateValid; + Real m_afcFrequency; //!< radians/sample + Real m_afcPhase; + + // Matched filter and symbol timing + std::vector m_matchedFilterTaps; + std::vector m_matchedFilterSamples; + int m_matchedFilterIndex; + std::vector m_history; + int m_historyIndex; + Real m_symbolPower; + Real m_clockCount; + Real m_timingIntegrator; + + // Lock detection + Real m_lockMetric; + int m_lockCount; + int m_presentCount; + int m_unlockCount; + Real m_lockedLevel; //!< Tracked signal power while locked + bool m_locked; + std::deque> m_pendingCharacters; //!< Character and symbols until output + std::deque m_acquisitionSymbols; + + // SNR + double m_snrInPhaseSum; + double m_snrQuadratureSum; + int m_snrCount; + double m_snrSignalPower; + double m_snrNoisePower; + bool m_snrAverageValid; + float m_snr; + int m_reportSampleCount; + + PSK31Decoder m_decoder; + + std::function m_characterCallback; + std::function m_reportCallback; + std::function m_scopeCallback; + + void acquireCarrier(const Complex& sample); + void checkIdleToneLock(Real current); + Real afcPower(int bin) const; + void retune(Real frequency); + Complex matchedFilter(const Complex& sample); + void symbol(const Complex& value); + void decode(bool symbol); + void emitCharacter(QChar character); + void unlock(); + void resetSNR(); +}; + +#endif // INCLUDE_PSK31DEMODULATOR_H diff --git a/plugins/channelrx/demodpsk31/readme.md b/plugins/channelrx/demodpsk31/readme.md index 997ff0e5c..1ed0207ce 100644 --- a/plugins/channelrx/demodpsk31/readme.md +++ b/plugins/channelrx/demodpsk31/readme.md @@ -2,9 +2,11 @@

Introduction

-This channel receives PSK31 text. It performs carrier and symbol-clock recovery, -differential BPSK decoding, and Varicode decoding at the standard 31.25 baud rate. -The decoder supports the same extended Latin-1 Varicode table as the [PSK31 modulator](../../channeltx/modpsk31/readme.md). +This channel receives PSK31 text at the standard 31.25 baud rate. It searches the +RF bandwidth for the signal's carrier, centers it in a narrow tracking filter, +recovers carrier phase and symbol timing, and makes differential BPSK decisions +from a filter matched to the PSK31 pulse shape. The decoder supports the same +extended Latin-1 Varicode table as the [PSK31 modulator](../../channeltx/modpsk31/readme.md).

Interface

@@ -14,21 +16,26 @@ The top and bottom bars of the channel window are described [here](../../../sdrg

1: Frequency offset

-Tune the channel marker to the center of the PSK31 signal. The carrier-recovery -loop corrects a small remaining frequency and phase error. With the default -100 Hz bandwidth, tune to within about 10 Hz for reliable acquisition. The -carrier status label shows the residual error after the loop has locked. +Tune the channel marker to the PSK31 signal. The demodulator finds the carrier +within the RF bandwidth (3) and tracks it from there, so the marker does not need +to be exactly on frequency: with the default 100 Hz bandwidth, signals within +about 30 Hz of the marker are acquired. The carrier status (7) shows the +carrier's offset from the marker once locked.

2: Channel power and level meter

-Channel power is displayed in dB relative to a full-scale signal. The level meter -shows average power, instantaneous peak power, and peak hold. +Power within the RF bandwidth (3), in dB relative to a full-scale signal. The +level meter shows average power, instantaneous peak power, and peak hold.

3: RF bandwidth

-This sets the input filter bandwidth. The default 100 Hz bandwidth is appropriate -for most PSK31 signals. A narrower setting rejects more adjacent-channel energy; -a wider setting allows a larger initial tuning error. +This sets the bandwidth searched for a signal. Signals up to 15 Hz inside either +edge are acquired. Once acquired, the signal is kept centered in a fixed 70 Hz +tracking filter (or the RF bandwidth, if that is narrower) followed by the +matched filter, so the RF bandwidth has little effect on adjacent-channel +rejection after lock. The default 100 Hz bandwidth suits most use. Reduce it if a +stronger signal nearby is acquired instead of the one wanted; increase it to +allow a larger tuning error.

4: UDP

@@ -44,13 +51,21 @@ UDP port number to forward received characters to.

7: Carrier status

-Shows whether the demodulator is locked to the carrier. Once locked, it also -shows the residual frequency error and the estimated SNR. The SNR is measured -from the carrier-corrected constellation over one second of locked samples. Its -noise power is normalized to a 100 Hz reference bandwidth, so changing the RF -bandwidth does not introduce the usual 3 dB change for each doubling or halving -of bandwidth. The first SNR value is displayed after one complete second of -carrier lock; samples collected before acquisition are excluded. +Shows whether the demodulator is locked to a PSK31 signal. Once locked, it also +shows the carrier's frequency offset from the channel marker and the estimated +SNR. The SNR is measured from the carrier-corrected signal each second and +averaged over a few seconds. Its noise power is normalized to a 100 Hz reference +bandwidth, so it does not depend on the RF bandwidth setting. The first SNR value +is displayed after one complete second of lock; samples collected before +acquisition are excluded. + +Lock is confirmed over 20 symbols, which keeps noise from being decoded as text. +Symbols received while confirming are decoded once lock is confirmed, so text +that follows a short idle preamble is not lost. Characters are output after an +8 symbol delay. If the signal level drops more than about 4.6 dB in that time, +output is paused, so noise received as a transmission ends is not displayed. +During a fade of up to about half a second, lock is held and output paused; if +the signal returns, decoding continues without having to reacquire.

8: Start/stop Logging Messages to .txt File

@@ -66,59 +81,57 @@ Clear the received text view (11) of received characters.

11: Received text

-Decoded text is appended to the text view. +Decoded text is appended to the text view. CR, LF and CR LF line endings each +start a new line. Other control characters are not displayed.

Measured performance

-The sample-level benchmark sends a -raised-cosine PSK31 waveform with 256 idle symbols followed by the 30-character -test frame `CQ CQ DE SDRANGEL 0123456789\r\n`. A frame passes only when every +The sample-level benchmark sends a raised-cosine PSK31 waveform, as generated by +the PSK31 modulator, with 256 idle symbols followed by the 30-character test frame +`CQ CQ DE SDRANGEL 0123456789\r\n`. Some tests instead use the classic PSK31 +cosine envelope, or a short idle preamble. A frame passes only when every character is correct. Run it with: ``` sdrangelbench -t psk31 -a perf ``` -Measurements on the 1000 sample/s internal receiver with the default 100 Hz RF -bandwidth gave these results: +Measurements with the default 100 Hz RF bandwidth gave these results: | Test | Result | |---|---| -| AWGN, acquired carrier | 32% exact frames at 7 dB SNR; 62% at 8 dB; 88% at 9 dB; 96% at 10 dB; 100% at every tested point from 11 through 16 dB | -| Residual frequency, random starting phase | 10/10 exact frames at every offset from -14 Hz through +11 Hz; use +/-10 Hz as the tuning target | +| AWGN, acquired carrier | 26% exact frames at 3 dB SNR; 66% at 4 dB; 90% at 5 dB; 94% at 6 dB; 98% at 7 and 8 dB; 100% from 9 dB. The classic cosine envelope gives the same results within a frame or two | +| Frequency offset, random starting phase | At 10 dB SNR, 10/10 exact frames at every offset from -33 Hz through +30 Hz. At 5 dB SNR, 7/10 to 10/10 from -30 Hz through +30 Hz | +| Short preamble, random phase and offset within +/-15 Hz, 10 dB SNR | 20/20 exact frames with 32 or more idle symbols; 19/20 with 24; 13/20 with 16 | | Sample-clock error | 5/5 exact frames with zero character errors at every tested point from -5000 through +5000 ppm | -| Noiseless input level | 8/8 timing phases at every tested level from -10 through -60 dBFS | +| Noiseless input level | 8/8 timing phases at every tested level from -10 through -100 dBFS | | Noise only at -40 dBFS | Zero lock acquisitions and zero decoded characters in one simulated hour | -| CW interferer at 25 Hz separation | 5/5 exact frames at -20 dB relative to the wanted signal; 3/5 at -10 dB; 0/5 at equal power | -| CW interferer at 50 Hz separation | 5/5 exact frames at -10 dB relative to the wanted signal; 0/5 at equal power | -| CW interferer at 75 or 100 Hz separation | 5/5 exact frames with the interferer 10 dB stronger than the wanted signal | -| Core demodulator CPU throughput | 5.60-5.93 million internal samples/s, or 5600-5900 times real time at 1000 samples/s | +| Transmission ending without a carrier tail, followed by noise | No characters decoded after the end in 100/100 trials at 20 dB and 10 dB SNR; 94/100 at 5 dB, with a single character in the others | +| Fade to -40 dB in the middle of text, 15 dB SNR | Average character errors: 0.2 for 50 ms; 0.8 for 100 ms; 2.2 for 200 ms; 2.7 for 300 ms; 3.8 for 500 ms | +| CW interferer, 15 dB SNR | 5/5 exact frames with the interferer 10 dB weaker at 25 Hz separation, equal power at 50 Hz, and 40 dB stronger at 75, 100 or 150 Hz | +| PSK31 interferer, 15 dB SNR | 5/5 exact frames with the interferer 10 dB weaker at 25 Hz separation, equal power at 50 Hz, 30 dB stronger at 75 Hz, and 40 dB stronger at 100 or 150 Hz | +| Full channel path at 1536 samples/s, 10 dB SNR | 5/5 exact frames with PSK31 interferers 20 dB stronger at both +/-75 Hz, 30 dB stronger at 100 Hz, or a CW carrier 40 dB stronger at 300 Hz or at -600 Hz, which aliases when resampled | +| Core demodulator CPU throughput | 4.45-4.49 million internal samples/s, or about 4500 times real time at 1000 samples/s | SNR is average wanted-signal power divided by complex AWGN power in a 100 Hz -reference bandwidth, after carrier acquisition. The demodulator estimates signal -and noise from the in-phase and quadrature power of the recovered BPSK carrier, -then scales the measured noise from the selected RF bandwidth to 100 Hz. In the -regression test, a 20 dB input measured 21.25 dB with a 100 Hz RF bandwidth and -20.84 dB with a 200 Hz RF bandwidth. At 31.25 baud, 10 dB in 100 Hz corresponds -to about 15 dB Eb/N0. The frequency result measures acquisition after roughly -8.2 seconds of idle symbols; the loop's configured tracking clamp is wider than -its measured acquisition range. Input level alone is not a sensitivity figure -because the usable floor depends on noise and receiver dynamic range. +reference bandwidth. At 31.25 baud, 3 dB in 100 Hz corresponds to about 8 dB +Eb/N0. In the regression test, a 20 dB input is reported as about 21.5 dB with +either a 100 Hz or a 200 Hz RF bandwidth. Input level alone is not a sensitivity +figure because the usable floor depends on noise and receiver dynamic range. The CPU result is the range from three one-second runs of the RelWithDebInfo Windows build on an Intel Core i9-14900K. It repeatedly feeds representative -BPSK samples directly to the demodulator sink. At the 1000 sample/s internal -rate, this corresponds to roughly 0.018% of one CPU core. It measures the -channel-specific carrier recovery, symbol timing, and decoding path; device -input, channelization, scope rendering, and other application overhead are not +BPSK samples to the demodulator at its internal rate. At 1000 samples/s, this +corresponds to roughly 0.02% of one CPU core. It measures filtering, carrier +acquisition and tracking, symbol timing, and decoding; device input, +channelization, scope rendering, and other application overhead are not included. Run this focused measurement with: ``` sdrangelbench -t psk31 -a cpu ``` -The receiver qualifies carrier lock over eight symbols before decoding and drops -lock after two failed symbol checks. Run the standalone noise test with: +Run the standalone noise test with: ``` sdrangelbench -t psk31 -a noise diff --git a/sdrbase/dsp/costasloop.h b/sdrbase/dsp/costasloop.h index f8371c4c6..49cbdcede 100644 --- a/sdrbase/dsp/costasloop.h +++ b/sdrbase/dsp/costasloop.h @@ -40,6 +40,7 @@ public: void setSampleRate(unsigned int sampleRate); void setMaxFreq(float freq) { m_maxFreq = freq; } void setMinFreq(float freq) { m_minFreq = freq; } + void setFreq(float freq) { m_freq = freq; } void feed(float re, float im); const std::complex& getComplex() const { return m_y; } float getReal() const { return m_y.real(); } diff --git a/sdrbase/resources/webapi/doc/swagger/include/PSK31Demod.yaml b/sdrbase/resources/webapi/doc/swagger/include/PSK31Demod.yaml index 1b5bb5658..2db198da2 100644 --- a/sdrbase/resources/webapi/doc/swagger/include/PSK31Demod.yaml +++ b/sdrbase/resources/webapi/doc/swagger/include/PSK31Demod.yaml @@ -83,13 +83,13 @@ PSK31DemodReport: frequencyOffset: type: number format: float - description: "Fine carrier-frequency estimate in Hz relative to the selected channel frequency." + description: "Carrier-frequency estimate in Hz relative to the selected channel frequency. Only present when locked." snr: type: number format: float - description: "Signal-to-noise ratio in dB, normalized to a 100 Hz noise bandwidth." + description: "Signal-to-noise ratio in dB, normalized to a 100 Hz noise bandwidth. Only present when locked." locked: type: integer minimum: 0 maximum: 1 - description: "Whether the BPSK carrier-recovery loop is locked." + description: "Whether a PSK31 signal is locked and being decoded." diff --git a/sdrbase/util/psk31.cpp b/sdrbase/util/psk31.cpp index 5884be77a..ffb2c9fd5 100644 --- a/sdrbase/util/psk31.cpp +++ b/sdrbase/util/psk31.cpp @@ -337,6 +337,7 @@ void PSK31Decoder::reset() { m_code.clear(); m_zeroCount = 0; + m_discard = false; m_havePreviousSymbol = false; m_previousSymbol = false; } @@ -359,6 +360,12 @@ bool PSK31Decoder::decode(bool bit, QChar& character) { if (bit) { + if (m_discard) + { + m_zeroCount = 0; + return false; + } + if ((m_zeroCount == 1) && !m_code.isEmpty()) { m_code.append('0'); } @@ -366,10 +373,13 @@ bool PSK31Decoder::decode(bool bit, QChar& character) m_zeroCount = 0; m_code.append('1'); + // No Varicode is longer than 12 bits, so this is not a character, but + // e.g. an unmodulated carrier. Its tail could look like a valid code, + // so ignore everything up to the next character gap. if (m_code.size() > 12) { m_code.clear(); - m_zeroCount = 0; + m_discard = true; } return false; @@ -381,9 +391,10 @@ bool PSK31Decoder::decode(bool bit, QChar& character) return false; } - const bool decoded = decodeCode(character); + const bool decoded = !m_discard && decodeCode(character); m_code.clear(); m_zeroCount = 0; + m_discard = false; return decoded; } diff --git a/sdrbase/util/psk31.h b/sdrbase/util/psk31.h index 40b527e0b..d45354aaf 100644 --- a/sdrbase/util/psk31.h +++ b/sdrbase/util/psk31.h @@ -61,6 +61,7 @@ public: private: QString m_code; int m_zeroCount; + bool m_discard; bool m_havePreviousSymbol; bool m_previousSymbol; diff --git a/sdrbench/CMakeLists.txt b/sdrbench/CMakeLists.txt index a1f45b4f7..bf62d5757 100644 --- a/sdrbench/CMakeLists.txt +++ b/sdrbench/CMakeLists.txt @@ -16,8 +16,7 @@ set(sdrbench_SOURCES test_firrrc.cpp test_meshtastic.cpp test_psk31.cpp - ../plugins/channelrx/demodpsk31/psk31demodsink.cpp - ../plugins/channelrx/demodpsk31/psk31demodsettings.cpp + ../plugins/channelrx/demodpsk31/psk31demodulator.cpp ) set(sdrbench_HEADERS @@ -40,8 +39,6 @@ include_directories( ${CMAKE_SOURCE_DIR} ) -target_compile_definitions(sdrbench PRIVATE PSK31_DEMOD_SINK_BENCH) - if(DEFINED FFTW3F_DEPENDS) add_dependencies(sdrbench "${FFTW3F_DEPENDS}") endif() diff --git a/sdrbench/test_psk31.cpp b/sdrbench/test_psk31.cpp index 8843260ee..5e529603d 100644 --- a/sdrbench/test_psk31.cpp +++ b/sdrbench/test_psk31.cpp @@ -27,7 +27,7 @@ #include "dsp/raisedcosine.h" #include "mainbench.h" -#include "psk31demodsink.h" +#include "psk31demodulator.h" #include "util/psk31.h" namespace { @@ -38,6 +38,12 @@ constexpr float measurementBandwidth = 100.0f; constexpr int noiseDurationSeconds = 3600; constexpr float noiseLevelDbFS = -40.0f; +enum class PulseShape +{ + RaisedCosine, // As generated by SDRangel's PSK31 modulator + CosineEnvelope // Classic PSK31: cosine amplitude envelope on each reversal +}; + struct TrialOptions { float snrDb100Hz = std::numeric_limits::infinity(); @@ -48,12 +54,24 @@ struct TrialOptions float initialPhase = std::numeric_limits::quiet_NaN(); float interfererOffset = 0.0f; float interfererRelativeDb = -std::numeric_limits::infinity(); + bool interfererPSK31 = false; // PSK31 station rather than a CW carrier float rfBandwidth = measurementBandwidth; int phaseGlitchStart = -1; int phaseGlitchLength = 0; + int fadeStart = -1; + int fadeLength = 0; + float fadeDb = -40.0f; quint32 seed = 1; }; +struct TrialResult +{ + QString received; + float snr = 0.0f; + bool locked = false; + float frequencyOffset = 0.0f; +}; + struct NoiseResult { int characters = 0; @@ -61,14 +79,14 @@ struct NoiseResult int lockAcquisitions = 0; }; -QVector encodeBits(const QString& text) +QVector encodeBits(const QString& text, int carrierTailSymbols = 0, int preambleSymbols = 256) { PSK31Encoder encoder; QVector bits; // Reversing phase on every idle zero gives the Costas loop and symbol clock - // enough time to acquire before any scored text arrives. - bits.fill(false, 256); + // time to acquire before any scored text arrives. + bits.fill(false, preambleSymbols); for (QChar character : text) { @@ -85,16 +103,26 @@ QVector encodeBits(const QString& text) bits.append(false); } + // Unmodulated carrier, as sent at the end of a transmission + for (int i = 0; i < carrierTailSymbols; ++i) { + bits.append(true); + } + return bits; } -QVector modulate(const QVector& bits) +QVector modulate(const QVector& bits, PulseShape shape = PulseShape::RaisedCosine) { QVector waveform; waveform.reserve((bits.size() + 4) * samplesPerSymbol); RaisedCosine pulseShape; pulseShape.create(1.0, 2, samplesPerSymbol, true); + std::vector cosinePulse(2 * samplesPerSymbol); + for (int i = 0; i < 2 * samplesPerSymbol; ++i) { + cosinePulse[i] = 0.5f - 0.5f * std::cos(2.0f * M_PI * i / (2 * samplesPerSymbol)); + } + std::vector symbols; bool symbol = false; @@ -104,37 +132,91 @@ QVector modulate(const QVector& bits) symbol = !symbol; } - for (int sample = 0; sample < samplesPerSymbol; ++sample) { - waveform.append(pulseShape.filter(sample == 1 ? (symbol ? 1.0f : -1.0f) : 0.0f)); + if (shape == PulseShape::RaisedCosine) + { + for (int sample = 0; sample < samplesPerSymbol; ++sample) { + waveform.append(pulseShape.filter(sample == 1 ? (symbol ? 1.0f : -1.0f) : 0.0f)); + } + } + else + { + symbols.push_back(symbol ? 1.0f : -1.0f); + } + } + + if (shape == PulseShape::RaisedCosine) + { + // Flush the pulse-shaping filter. + for (int i = 0; i < 3 * samplesPerSymbol; ++i) { + waveform.append(pulseShape.filter(0.0f)); + } + } + else + { + waveform.fill(0.0f, (symbols.size() + 2) * samplesPerSymbol); + for (int k = 0; k < (int) symbols.size(); ++k) + { + for (int i = 0; i < 2 * samplesPerSymbol; ++i) { + waveform[k * samplesPerSymbol + i] += symbols[k] * cosinePulse[i]; + } } } - // Flush the pulse-shaping filter. - for (int i = 0; i < 3 * samplesPerSymbol; ++i) { - waveform.append(pulseShape.filter(0.0f)); + return waveform; +} + +QVector appendSilence(QVector waveform, int samples) +{ + for (int i = 0; i < samples; ++i) { + waveform.append(0.0f); } + return waveform; +} + +QVector prependSilence(const QVector& waveform, int samples) +{ + QVector result(samples, 0.0f); + result.append(waveform); + return result; +} +// An unrelated PSK31 transmission used as an adjacent channel interferer +const QVector& interfererWaveform() +{ + static const QVector waveform = modulate(encodeBits( + "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG 1234567890 the quick brown fox jumps over the lazy dog " + "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG 1234567890 the quick brown fox jumps over the lazy dog ")); return waveform; } -QString runTrial(const QVector& source, const TrialOptions& options, float* measuredSNR = nullptr) +double meanPower(const QVector& waveform) +{ + double power = 0.0; + for (float sample : waveform) { + power += sample * sample; + } + return power / waveform.size(); +} + +QVector resample(const QVector& source, double scale, double offset) { - const double clockScale = 1.0 + options.clockErrorPpm * 1.0e-6; QVector resampled; - resampled.reserve(static_cast(source.size() * clockScale) + 1); + resampled.reserve(static_cast(source.size() * scale) + 1); - for (double position = options.timingOffset; position < source.size() - 1; position += 1.0 / clockScale) + for (double position = offset; position < source.size() - 1; position += 1.0 / scale) { const int index = static_cast(position); const float fraction = static_cast(position - index); resampled.append(source[index] + fraction * (source[index + 1] - source[index])); } - double meanSignalPower = 0.0; - for (float sample : resampled) { - meanSignalPower += sample * sample; - } - meanSignalPower = options.amplitude * options.amplitude * meanSignalPower / resampled.size(); + return resampled; +} + +TrialResult runTrial(const QVector& source, const TrialOptions& options) +{ + const QVector resampled = resample(source, 1.0 + options.clockErrorPpm * 1.0e-6, options.timingOffset); + const double meanSignalPower = options.amplitude * options.amplitude * meanPower(resampled); // SNR is quoted in the demodulator's 100 Hz RF bandwidth. The generated // complex AWGN spans the 1000 sample/s simulation bandwidth. @@ -150,18 +232,18 @@ QString runTrial(const QVector& source, const TrialOptions& options, floa std::uniform_real_distribution phaseDistribution(-M_PI, M_PI); const float initialPhase = std::isfinite(options.initialPhase) ? options.initialPhase : phaseDistribution(generator); + const QVector& psk31Interferer = interfererWaveform(); + const float interfererScale = options.interfererPSK31 ? 1.0f / std::sqrt(meanPower(psk31Interferer)) : 1.0f; const float interfererAmplitude = std::isfinite(options.interfererRelativeDb) - ? options.amplitude * std::pow(10.0f, options.interfererRelativeDb / 20.0f) + ? std::sqrt(meanSignalPower) * std::pow(10.0f, options.interfererRelativeDb / 20.0f) : 0.0f; + const float fadeAmplitude = std::pow(10.0f, options.fadeDb / 20.0f); - PSK31DemodSink sink; - PSK31DemodSettings settings; - settings.m_rfBandwidth = options.rfBandwidth; - sink.applySettings(QStringList(), settings, true); - sink.applyChannelSettings(sampleRate, 0, true); + PSK31Demodulator demod; + demod.setRFBandwidth(options.rfBandwidth); - QString received; - sink.setCharacterSink([&received](QChar character) { received.append(character); }); + TrialResult result; + demod.setCharacterCallback([&result](QChar character) { result.received.append(character); }); for (int i = 0; i < resampled.size(); ++i) { @@ -171,19 +253,93 @@ QString runTrial(const QVector& source, const TrialOptions& options, floa if ((i >= options.phaseGlitchStart) && (i < options.phaseGlitchStart + options.phaseGlitchLength)) { sample = -sample; } + if ((i >= options.fadeStart) && (i < options.fadeStart + options.fadeLength)) { + sample *= fadeAmplitude; + } if (interfererAmplitude > 0.0f) { const float interfererPhase = 0.37f + 2.0f * M_PI * options.interfererOffset * i / sampleRate; - sample += interfererAmplitude * Complex(std::cos(interfererPhase), std::sin(interfererPhase)); + const float modulation = options.interfererPSK31 + ? interfererScale * psk31Interferer[(i + 1234) % psk31Interferer.size()] + : 1.0f; + sample += interfererAmplitude * modulation * Complex(std::cos(interfererPhase), std::sin(interfererPhase)); } sample += Complex(gaussian(generator), gaussian(generator)); - sink.feedTestSample(sample); + demod.processSample(sample); } - if (measuredSNR) { - *measuredSNR = sink.getSNR(); + result.snr = demod.getSNR(); + result.locked = demod.isLocked(); + result.frequencyOffset = demod.getFrequencyOffset(); + return result; +} + +struct ChannelInterferer +{ + float offset; // Hz relative to the wanted signal + float relativeDb; // Power relative to the wanted signal + bool psk31; +}; + +// Run the full channel path: NCO, resampling to the internal rate and +// fixed-point samples, as used by the plugin. +QString runChannelTrial( + const QVector& source, + int channelSampleRate, + int channelFrequencyOffset, + float residualOffset, + const std::vector& interferers, + float snrDb100Hz, + quint32 seed) +{ + const double scale = channelSampleRate / sampleRate; + const QVector resampled = resample(source, scale, 0.0); + const float amplitude = 0.01f; // -40 dBFS, leaving headroom for strong interferers + const double meanSignalPower = amplitude * amplitude * meanPower(resampled); + double noisePower = 0.0; + if (std::isfinite(snrDb100Hz)) { + noisePower = meanSignalPower * (channelSampleRate / measurementBandwidth) / std::pow(10.0, snrDb100Hz / 10.0); + } + + std::mt19937 generator(seed); + std::normal_distribution gaussian(0.0f, std::sqrt(noisePower / 2.0)); + const QVector& psk31Interferer = interfererWaveform(); + const float interfererScale = 1.0f / std::sqrt(meanPower(psk31Interferer)); + + PSK31Demodulator demod; + demod.setChannel(channelSampleRate, channelFrequencyOffset); + QString received; + demod.setCharacterCallback([&received](QChar character) { received.append(character); }); + + SampleVector samples; + samples.reserve(resampled.size()); + const float signalFrequency = channelFrequencyOffset + residualOffset; + + for (int i = 0; i < resampled.size(); ++i) + { + const double t = i / static_cast(channelSampleRate); + const double phase = 0.5 + 2.0 * M_PI * signalFrequency * t; + Complex sample = amplitude * resampled[i] * Complex(std::cos(phase), std::sin(phase)); + + for (const auto& interferer : interferers) + { + const double interfererPhase = 1.1 + 2.0 * M_PI * (signalFrequency + interferer.offset) * t; + const float interfererAmplitude = std::sqrt(meanSignalPower) * std::pow(10.0f, interferer.relativeDb / 20.0f); + const float modulation = interferer.psk31 + ? interfererScale * psk31Interferer[static_cast(t * sampleRate + 777) % psk31Interferer.size()] + : 1.0f; + sample += interfererAmplitude * modulation * Complex(std::cos(interfererPhase), std::sin(interfererPhase)); + } + + sample += Complex(gaussian(generator), gaussian(generator)); + samples.push_back(Sample(sample.real() * SDR_RX_SCALEF, sample.imag() * SDR_RX_SCALEF)); + } + + constexpr int blockSize = 1000; + for (int i = 0; i < samples.size(); i += blockSize) { + demod.feed(samples.begin() + i, samples.begin() + std::min(i + blockSize, samples.size())); } return received; @@ -195,21 +351,18 @@ NoiseResult runNoiseTrial(int durationSeconds, float levelDbFS, quint32 seed) std::mt19937 generator(seed); std::normal_distribution gaussian(0.0f, std::sqrt(noisePower / 2.0f)); - PSK31DemodSink sink; - PSK31DemodSettings settings; - settings.m_rfBandwidth = measurementBandwidth; - sink.applySettings(QStringList(), settings, true); - sink.applyChannelSettings(sampleRate, 0, true); + PSK31Demodulator demod; + demod.setRFBandwidth(measurementBandwidth); NoiseResult result; - sink.setCharacterSink([&result](QChar) { ++result.characters; }); + demod.setCharacterCallback([&result](QChar) { ++result.characters; }); bool wasLocked = false; const int sampleCount = static_cast(durationSeconds * sampleRate); for (int i = 0; i < sampleCount; ++i) { - sink.feedTestSample(Complex(gaussian(generator), gaussian(generator))); - const bool locked = sink.isLocked(); + demod.processSample(Complex(gaussian(generator), gaussian(generator))); + const bool locked = demod.isLocked(); result.lockedSamples += locked; result.lockAcquisitions += locked && !wasLocked; wasLocked = locked; @@ -218,6 +371,65 @@ NoiseResult runNoiseTrial(int durationSeconds, float levelDbFS, quint32 seed) return result; } +QString escaped(const QString& text) +{ + QString result; + for (QChar character : text) + { + if ((character.unicode() < 0x20) || (character.unicode() >= 0x7f)) { + result.append(QString("<%1>").arg(static_cast(character.unicode()), 2, 16, QChar('0'))); + } else { + result.append(character); + } + } + return result; +} + +int editDistance(const QString& a, const QString& b) +{ + std::vector previous(b.size() + 1); + std::vector current(b.size() + 1); + + for (int j = 0; j <= b.size(); ++j) { + previous[j] = j; + } + + for (int i = 1; i <= a.size(); ++i) + { + current[0] = i; + for (int j = 1; j <= b.size(); ++j) + { + current[j] = std::min({ + previous[j] + 1, + current[j - 1] + 1, + previous[j - 1] + (a[i - 1] != b[j - 1] ? 1 : 0)}); + } + std::swap(previous, current); + } + + return previous[b.size()]; +} + +// Number of trials where characters are decoded after a transmission that +// ends without a carrier tail, followed by noise +int abruptEndTrials(const QVector& waveform, const QString& payload, float snrDb, int trials) +{ + const QVector abrupt = appendSilence(waveform, 3000); + int extra = 0; + + for (int trial = 0; trial < trials; ++trial) + { + TrialOptions options; + options.snrDb100Hz = snrDb; + options.seed = 9000 + trial; + const QString received = runTrial(abrupt, options).received; + const int index = received.indexOf(payload); + extra += (index >= 0) && (received.size() > index + payload.size()); + } + + return extra; +} + void measureNoiseRejection() { const NoiseResult noise = runNoiseTrial(noiseDurationSeconds, noiseLevelDbFS, 6000); @@ -243,11 +455,8 @@ void measureCPUPerformance() block[i] = Complex(inPhase, quadrature); } - PSK31DemodSink sink; - PSK31DemodSettings settings; - settings.m_rfBandwidth = measurementBandwidth; - sink.applySettings(QStringList(), settings, true); - sink.applyChannelSettings(sampleRate, 0, true); + PSK31Demodulator demod; + demod.setRFBandwidth(measurementBandwidth); qint64 processedSamples = 0; QElapsedTimer timer; @@ -256,7 +465,7 @@ void measureCPUPerformance() do { for (const Complex& sample : block) { - sink.feedTestSample(sample); + demod.processSample(sample); } processedSamples += blockSize; } while (timer.elapsed() < minimumElapsedMilliseconds); @@ -274,7 +483,7 @@ void measureCPUPerformance() bool framePassed(const QVector& waveform, const QString& payload, const TrialOptions& options) { - return runTrial(waveform, options).contains(payload); + return runTrial(waveform, options).received.contains(payload); } int trailingCharacterErrors(const QString& received, const QString& payload) @@ -290,15 +499,16 @@ int trailingCharacterErrors(const QString& received, const QString& payload) return errors; } -void measurePerformance(const QVector& waveform, const QString& payload) +void measurePerformance(const QVector& waveform, const QVector& cosineWaveform, const QString& payload, const QString& argsStr) { qInfo().noquote() << "PSK31 RX performance benchmark"; qInfo().noquote() << "SNR definition: average signal power / AWGN power in 100 Hz; acquired carrier; exact-frame criterion"; - qInfo().noquote() << "SNR_dB,frames_passed,frames_total"; + qInfo().noquote() << "SNR_dB,raised_cosine_frames_passed,cosine_envelope_frames_passed,frames_total"; - for (int snrDb = 0; snrDb <= 16; ++snrDb) + for (int snrDb = -2; snrDb <= 12; ++snrDb) { int passed = 0; + int cosinePassed = 0; constexpr int trials = 50; for (int trial = 0; trial < trials; ++trial) @@ -308,26 +518,35 @@ void measurePerformance(const QVector& waveform, const QString& payload) options.initialPhase = 0.0f; // Measure AWGN sensitivity after carrier acquisition. options.seed = 1000 + trial; passed += framePassed(waveform, payload, options); + cosinePassed += framePassed(cosineWaveform, payload, options); } - qInfo().noquote() << QString("%1,%2,%3").arg(snrDb).arg(passed).arg(trials); + qInfo().noquote() << QString("%1,%2,%3,%4").arg(snrDb).arg(passed).arg(cosinePassed).arg(trials); } - qInfo().noquote() << "Residual_frequency_Hz,frames_passed,frames_total"; - for (int offset = -28; offset <= 28; ++offset) + qInfo().noquote() << "Frequency_offset_Hz,frames_passed_10dB,frames_passed_5dB,frames_total (random starting phase)"; + for (int offset = -45; offset <= 45; offset += 3) { int passed = 0; + int weakPassed = 0; constexpr int trials = 10; for (int trial = 0; trial < trials; ++trial) { TrialOptions options; - options.frequencyOffset = offset; + options.frequencyOffset = offset + 0.37f * trial; + options.snrDb100Hz = 10.0f; options.seed = 2000 + trial; - passed += framePassed(waveform, payload, options); + const TrialResult result = runTrial(waveform, options); + passed += result.received.contains(payload); + if (argsStr.contains("trace", Qt::CaseInsensitive) && !result.received.contains(payload)) { + qInfo().noquote() << " " << options.frequencyOffset << result.frequencyOffset << result.locked << escaped(result.received); + } + options.snrDb100Hz = 5.0f; + weakPassed += framePassed(waveform, payload, options); } - qInfo().noquote() << QString("%1,%2,%3").arg(offset).arg(passed).arg(trials); + qInfo().noquote() << QString("%1,%2,%3,%4").arg(offset).arg(passed).arg(weakPassed).arg(trials); } qInfo().noquote() << "Sample_clock_error_ppm,frames_passed,frames_total,total_character_errors"; @@ -343,7 +562,7 @@ void measurePerformance(const QVector& waveform, const QString& payload) options.clockErrorPpm = ppm; options.timingOffset = trial * 6; options.seed = 3000 + trial; - const QString received = runTrial(waveform, options); + const QString received = runTrial(waveform, options).received; passed += received.contains(payload); characterErrors += trailingCharacterErrors(received, payload); } @@ -352,7 +571,7 @@ void measurePerformance(const QVector& waveform, const QString& payload) } qInfo().noquote() << "Signal_level_dBFS,timing_phases_passed,timing_phases_total"; - for (int levelDb = -10; levelDb >= -60; levelDb -= 5) + for (int levelDb = -10; levelDb >= -100; levelDb -= 10) { int passed = 0; constexpr int trials = 8; @@ -369,57 +588,111 @@ void measurePerformance(const QVector& waveform, const QString& payload) qInfo().noquote() << QString("%1,%2,%3").arg(levelDb).arg(passed).arg(trials); } - qInfo().noquote() << "Interferer_offset_Hz,interferer_over_signal_dB,frames_passed,frames_total"; - for (int offset : {25, 50, 75, 100}) + for (bool psk31 : {false, true}) { - for (int relativeDb : {-20, -10, 0, 6, 10}) + qInfo().noquote() << QString("%1_interferer_offset_Hz,interferer_over_signal_dB,frames_passed,frames_total (15 dB SNR)") + .arg(psk31 ? "PSK31" : "CW"); + for (int offset : {25, 50, 75, 100, 150}) { - int passed = 0; - constexpr int trials = 5; - - for (int trial = 0; trial < trials; ++trial) + for (int relativeDb : {-20, -10, 0, 10, 20, 30, 40}) { - TrialOptions options; - options.interfererOffset = offset; - options.interfererRelativeDb = relativeDb; - options.seed = 5000 + trial; - passed += framePassed(waveform, payload, options); + int passed = 0; + constexpr int trials = 5; + + for (int trial = 0; trial < trials; ++trial) + { + TrialOptions options; + options.interfererOffset = (trial & 1) ? -offset : offset; + options.interfererRelativeDb = relativeDb; + options.interfererPSK31 = psk31; + options.snrDb100Hz = 15.0f; + options.seed = 5000 + trial; + passed += framePassed(waveform, payload, options); + } + + qInfo().noquote() << QString("%1,%2,%3,%4") + .arg(offset).arg(relativeDb).arg(passed).arg(trials); } + } + } + + qInfo().noquote() << "Preamble_symbols,frames_passed,frames_total (noise before signal, random phase, offset within +/-15 Hz, 10 dB SNR)"; + for (int preamble : {8, 16, 24, 32, 48, 64}) + { + const QVector shortWaveform = prependSilence(modulate(encodeBits(payload, 0, preamble)), 2000); + int passed = 0; + constexpr int trials = 20; - qInfo().noquote() << QString("%1,%2,%3,%4") - .arg(offset).arg(relativeDb).arg(passed).arg(trials); + for (int trial = 0; trial < trials; ++trial) + { + TrialOptions options; + options.snrDb100Hz = 10.0f; + options.frequencyOffset = -15.0f + 1.5f * (trial % 21); + options.seed = 8000 + trial; + passed += framePassed(shortWaveform, payload, options); } + + qInfo().noquote() << QString("%1,%2,%3").arg(preamble).arg(passed).arg(trials); + } + + qInfo().noquote() << "Abrupt_end_SNR_dB,trials_with_characters_after_end,trials_total (no carrier tail, then noise)"; + for (int snrDb : {20, 10, 5}) + { + constexpr int trials = 100; + qInfo().noquote() << QString("%1,%2,%3").arg(snrDb).arg(abruptEndTrials(waveform, payload, snrDb, trials)).arg(trials); + } + + qInfo().noquote() << "Fade_ms,average_character_errors (fade to -40 dB inside text, 15 dB SNR)"; + for (int fadeMs : {0, 50, 100, 200, 300, 500}) + { + int errors = 0; + constexpr int trials = 10; + + for (int trial = 0; trial < trials; ++trial) + { + TrialOptions options; + options.snrDb100Hz = 15.0f; + options.fadeStart = 256 * samplesPerSymbol + 40 * samplesPerSymbol + trial * 7; + options.fadeLength = fadeMs; + options.seed = 6000 + trial; + const QString received = runTrial(waveform, options).received; + errors += editDistance(received, payload); + if (argsStr.contains("trace", Qt::CaseInsensitive)) { + qInfo().noquote() << " " << escaped(received); + } + } + + qInfo().noquote() << QString("%1,%2").arg(fadeMs).arg(errors / static_cast(trials), 0, 'f', 1); + } + + qInfo().noquote() << "Channel_path_interferers,frames_passed,frames_total (1536 S/s channel, 10 dB SNR)"; + const std::vector>> channelCases = { + {"none", {}}, + {"PSK31 +20 dB at +/-75 Hz", {{75.0f, 20.0f, true}, {-75.0f, 20.0f, true}}}, + {"PSK31 +30 dB at 100 Hz", {{100.0f, 30.0f, true}}}, + {"CW +40 dB at 300 Hz", {{300.0f, 40.0f, false}}}, + {"CW +40 dB at -600 Hz (aliases)", {{-600.0f, 40.0f, false}}}, + }; + for (const auto& channelCase : channelCases) + { + int passed = 0; + constexpr int trials = 5; + for (int trial = 0; trial < trials; ++trial) { + passed += runChannelTrial(waveform, 1536, 200, 7.0f, channelCase.second, 10.0f, 7000 + trial).contains(payload); + } + qInfo().noquote() << QString("%1,%2,%3").arg(channelCase.first).arg(passed).arg(trials); } measureNoiseRejection(); measureCPUPerformance(); } -} - -void MainBench::testPSK31(const QString& argsStr) +bool testDecoder() { PSK31Encoder encoder; PSK31Decoder decoder; QVector decoded; - PSK31DemodSettings serverSettings; - - // Server builds have no scope GUI. Serializing their settings must remain safe. - bool success = !serverSettings.serialize().isEmpty(); - - PSK31DemodSettings edgeSettings; - edgeSettings.m_rfBandwidth = 0.0f; - edgeSettings.m_reverseAPIPort = 1; - edgeSettings.m_udpPort = 65535; - PSK31DemodSettings restoredEdgeSettings; - const bool edgeSettingsRestored = restoredEdgeSettings.deserialize(edgeSettings.serialize()); - const bool settingsValidationPassed = edgeSettingsRestored - && (restoredEdgeSettings.m_rfBandwidth == PSK31DemodSettings::PSK31DEMOD_MIN_RF_BANDWIDTH) - && (restoredEdgeSettings.m_reverseAPIPort == 1) - && (restoredEdgeSettings.m_udpPort == 65535) - && (PSK31DemodSettings::validateRFBandwidth( - std::numeric_limits::quiet_NaN()) == 100.0f); - success = success && settingsValidationPassed; + bool success = true; // Exercise every entry in the shared extended-ASCII Varicode table as one // continuous stream. This also checks character-boundary synchronization. @@ -453,11 +726,16 @@ void MainBench::testPSK31(const QString& argsStr) for (int i = 0; i < 8; ++i) { success = success && !decoder.decode(false, character); } - for (int i = 0; i < 13; ++i) { - success = success && !decoder.decode(true, character); + // Overlong runs of ones, such as unmodulated carrier, must not decode. + // A 14-bit run would leave "1" (space) after a naive overflow reset. + for (int ones : {13, 14, 15, 17, 40}) + { + for (int i = 0; i < ones; ++i) { + success = success && !decoder.decode(true, character); + } + success = success && !decoder.decode(false, character); + success = success && !decoder.decode(false, character); } - success = success && !decoder.decode(false, character); - success = success && !decoder.decode(false, character); unsigned bits; unsigned int bitCount; @@ -495,40 +773,108 @@ void MainBench::testPSK31(const QString& argsStr) if (decoder.decodeSymbol(symbol, character)) { received.append(character); } - success = success && (received == message); + + return success && (received == message); +} + +} + +void MainBench::testPSK31(const QString& argsStr) +{ + const bool decoderPassed = testDecoder(); + bool success = decoderPassed; const QString payload("CQ CQ DE SDRANGEL 0123456789\r\n"); const QVector waveform = modulate(encodeBits(payload)); + const QVector cosineWaveform = modulate(encodeBits(payload), PulseShape::CosineEnvelope); + TrialOptions nominal; nominal.snrDb100Hz = 20.0f; - float measuredSNR; - const bool nominalPassed = runTrial(waveform, nominal, &measuredSNR).contains(payload); - const bool snrPassed = std::isfinite(measuredSNR) && (std::abs(measuredSNR - nominal.snrDb100Hz) < 5.0f); + const TrialResult nominalResult = runTrial(waveform, nominal); + const bool nominalPassed = nominalResult.received.contains(payload); + const bool snrPassed = std::abs(nominalResult.snr - nominal.snrDb100Hz) < 2.0f; + const bool cosinePassed = framePassed(cosineWaveform, payload, nominal); TrialOptions wideBandwidth = nominal; wideBandwidth.rfBandwidth = 200.0f; - float wideBandwidthSNR; - const bool wideBandwidthPassed = runTrial(waveform, wideBandwidth, &wideBandwidthSNR).contains(payload); - const bool bandwidthNormalized = std::isfinite(wideBandwidthSNR) - && (std::abs(wideBandwidthSNR - measuredSNR) < 1.0f); - success = success && nominalPassed && snrPassed && wideBandwidthPassed && bandwidthNormalized; + const TrialResult wideResult = runTrial(waveform, wideBandwidth); + const bool wideBandwidthPassed = wideResult.received.contains(payload); + const bool bandwidthNormalized = std::abs(wideResult.snr - nominalResult.snr) < 1.0f; TrialOptions glitch; glitch.phaseGlitchStart = 250 * samplesPerSymbol + 2; glitch.phaseGlitchLength = 12; const bool glitchPassed = framePassed(waveform, payload, glitch); - success = success && glitchPassed; - qInfo() << "PSK31 regressions: nominal" << nominalPassed - << "reported SNR" << measuredSNR << "valid" << snrPassed - << "200 Hz SNR" << wideBandwidthSNR << "normalized" << bandwidthNormalized + + // Carrier acquisition beyond the Costas loop's own pull-in range + bool offsetPassed = true; + for (float offset : {-30.0f, -20.0f, 20.0f, 30.0f}) + { + TrialOptions options = nominal; + options.frequencyOffset = offset; + offsetPassed = offsetPassed && framePassed(waveform, payload, options); + } + + // Unmodulated carrier at the end of a transmission must not produce a + // character. Afterwards, lock and SNR must not be left stale. + TrialOptions tail = nominal; + const TrialResult tailResult = runTrial(appendSilence(modulate(encodeBits(payload, 40)), 3000), tail); + const bool tailPassed = tailResult.received.endsWith(payload); + const bool unlockPassed = !tailResult.locked && (tailResult.snr == 0.0f); + + // Transmission ending without a carrier tail must not have noise decoded + // after it + const int abruptEndExtra = abruptEndTrials(waveform, payload, 20.0f, 40); + const bool abruptEndPassed = abruptEndExtra == 0; + + // Transmission starting with a typical one second of idle + TrialOptions shortPreamble = nominal; + shortPreamble.frequencyOffset = 12.0f; + const bool shortPreamblePassed = framePassed( + prependSilence(modulate(encodeBits(payload, 0, 32)), 2000), payload, shortPreamble); + + // Short fade inside text must not lose lock + TrialOptions fade = nominal; + fade.fadeStart = 256 * samplesPerSymbol + 40 * samplesPerSymbol; + fade.fadeLength = 100; + const int fadeErrors = editDistance(runTrial(waveform, fade).received, payload); + const bool fadePassed = fadeErrors <= 2; + + // Full channel path with strong adjacent signals + const QString channelReceived = runChannelTrial( + waveform, 1536, 200, 7.0f, + {{100.0f, 30.0f, true}, {-75.0f, 20.0f, true}, {-600.0f, 40.0f, false}}, + 15.0f, 7000); + const bool channelPassed = channelReceived.contains(payload); + + if (!tailPassed) { + qWarning().noquote() << "PSK31 carrier tail received:" << escaped(tailResult.received); + } + if (!channelPassed) { + qWarning().noquote() << "PSK31 channel path received:" << escaped(channelReceived); + } + + success = success && nominalPassed && snrPassed && cosinePassed && wideBandwidthPassed && bandwidthNormalized + && glitchPassed && offsetPassed && tailPassed && unlockPassed && abruptEndPassed && shortPreamblePassed + && fadePassed && channelPassed; + qInfo() << "PSK31 regressions: decoder" << decoderPassed + << "nominal" << nominalPassed + << "reported SNR" << nominalResult.snr << "valid" << snrPassed + << "cosine envelope" << cosinePassed + << "200 Hz SNR" << wideResult.snr << "normalized" << bandwidthNormalized << "phase glitch" << glitchPassed - << "settings validation" << settingsValidationPassed; + << "frequency offset" << offsetPassed + << "carrier tail" << tailPassed << "unlock" << unlockPassed + << "abrupt end extra" << abruptEndExtra + << "short preamble" << shortPreamblePassed + << "fade errors" << fadeErrors + << "channel path" << channelPassed; const NoiseResult noise = runNoiseTrial(noiseDurationSeconds, noiseLevelDbFS, 6000); success = success && (noise.characters == 0); if (argsStr.contains("perf", Qt::CaseInsensitive)) { - measurePerformance(waveform, payload); + measurePerformance(waveform, cosineWaveform, payload, argsStr); } else if (argsStr.contains("noise", Qt::CaseInsensitive)) { measureNoiseRejection(); @@ -543,7 +889,7 @@ void MainBench::testPSK31(const QString& argsStr) { TrialOptions options; options.clockErrorPpm = ppm; - const QString trace = runTrial(waveform, options); + const QString trace = runTrial(waveform, options).received; qInfo().noquote() << QString("clock %1 ppm: %2").arg(ppm, 6).arg(QString(trace.toLatin1().toHex())); } } diff --git a/swagger/sdrangel/api/swagger/include/PSK31Demod.yaml b/swagger/sdrangel/api/swagger/include/PSK31Demod.yaml index 1c0d50e7f..5ce2ccf14 100644 --- a/swagger/sdrangel/api/swagger/include/PSK31Demod.yaml +++ b/swagger/sdrangel/api/swagger/include/PSK31Demod.yaml @@ -83,13 +83,13 @@ PSK31DemodReport: frequencyOffset: type: number format: float - description: "Fine carrier-frequency estimate in Hz relative to the selected channel frequency." + description: "Carrier-frequency estimate in Hz relative to the selected channel frequency. Only present when locked." snr: type: number format: float - description: "Signal-to-noise ratio in dB, normalized to a 100 Hz noise bandwidth." + description: "Signal-to-noise ratio in dB, normalized to a 100 Hz noise bandwidth. Only present when locked." locked: type: integer minimum: 0 maximum: 1 - description: "Whether the BPSK carrier-recovery loop is locked." + description: "Whether a PSK31 signal is locked and being decoded."