diff options
| author | Dave Hibberd <hibby@debian.org> | 2026-10-20 22:35:06 +0100 |
|---|---|---|
| committer | Dave Hibberd <hibby@debian.org> | 2026-10-20 22:35:06 +0100 |
| commit | 82ebb1ed1af30cee4dfbb1c628431d32885a00e0 (patch) | |
| tree | 1a1f782d3e576b758be0bc61171574a7cd8f2376 /widgets | |
| parent | 061658210acb6425517733ea012dda803a7f72a1 (diff) | |
| parent | 61d684922b0f1c8455cc60eb3d123df058c9e1f5 (diff) | |
Merge tag 'debian/3.3.0_beta2+dfsg-1' into hibbian/trixie-backports
tagging wsjtx 3.3.0~beta2+dfsg-1
Diffstat (limited to 'widgets')
29 files changed, 4662 insertions, 1765 deletions
diff --git a/widgets/AbstractLogWindow.cpp b/widgets/AbstractLogWindow.cpp index 667573ce..284fc34f 100644 --- a/widgets/AbstractLogWindow.cpp +++ b/widgets/AbstractLogWindow.cpp @@ -11,6 +11,8 @@ #include <QItemSelectionModel> #include <QItemSelection> #include <QTimer> +#include <QSet> +#include <QVector> #include "Configuration.hpp" #include "SettingsGroup.hpp" #include "MessageBox.hpp" @@ -46,46 +48,55 @@ public: #include "moc_AbstractLogWindow.cpp" #include "AbstractLogWindow.moc" -namespace -{ - bool row_is_higher (QModelIndex const& lhs, QModelIndex const& rhs) - { - return lhs.row () > rhs.row (); - } -} - void AbstractLogWindow::impl::delete_QSOs () { auto selection_model = log_view_->selectionModel (); selection_model->select (selection_model->selection (), QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows); auto row_indexes = selection_model->selectedRows (); + QSet<qlonglong> record_ids; + record_ids.reserve (row_indexes.size ()); + for (auto const& row_index : row_indexes) + { + record_ids.insert (row_index.sibling (row_index.row (), 0) + .data (Qt::EditRole).toLongLong ()); + } - if (row_indexes.size () + if (record_ids.size () && MessageBox::Yes == MessageBox::query_message (self_ , tr ("Confirm Delete") , tr ("Are you sure you want to delete the %n " "selected QSO(s) from the log?", "" - , row_indexes.size ()) + , record_ids.size ()) , QString {} , MessageBox::Yes | MessageBox::No , MessageBox::No)) { - // We must work with source model indexes because we don't want row - // removes to invalidate model indexes we haven't yet processed. We - // achieve that by processing them in descending row order. - for (auto& row_index : row_indexes) + // Logging can refresh the model and reset its fetched rows during confirmation. + auto source_model = model_.sourceModel (); + while (source_model->canFetchMore (QModelIndex {})) { - row_index = model_.mapToSource (row_index); + source_model->fetchMore (QModelIndex {}); } - - // reverse sort by row - std::sort (row_indexes.begin (), row_indexes.end (), row_is_higher); - - for (auto index : row_indexes) + QVector<int> rows; + for (auto row = 0; row < model_.rowCount (); ++row) + { + auto const id = model_.index (row, 0).data (Qt::EditRole).toLongLong (); + if (record_ids.contains (id)) + { + rows.push_back (row); + } + } + std::sort (rows.begin (), rows.end (), [] (int lhs, int rhs) { + return lhs > rhs; + }); + bool removed = false; + for (auto row : rows) + { + removed = model_.removeRow (row) || removed; + } + if (removed) { - auto row = model_.mapFromSource(index).row(); - model_.removeRow(row); - self_->log_model_changed(); + self_->log_model_changed (); } } } diff --git a/widgets/DecodeHighlightingListView.cpp b/widgets/DecodeHighlightingListView.cpp index 2997017a..74afcdd1 100644 --- a/widgets/DecodeHighlightingListView.cpp +++ b/widgets/DecodeHighlightingListView.cpp @@ -67,7 +67,7 @@ DecodeHighlightingListView::DecodeHighlightingListView (QWidget * parent) } }); - auto * defaults_action = new QAction {tr ("&Reset this item to defaults"), this}; + auto * defaults_action = new QAction {tr ("&Reset this item to Default 1"), this}; addAction (defaults_action); connect (defaults_action, &QAction::triggered, [this] (bool /*checked*/) { auto const& index = currentIndex (); diff --git a/widgets/JttyDraftAcceptanceTracker.hpp b/widgets/JttyDraftAcceptanceTracker.hpp deleted file mode 100644 index 2263831f..00000000 --- a/widgets/JttyDraftAcceptanceTracker.hpp +++ /dev/null @@ -1,56 +0,0 @@ -#ifndef JTTY_DRAFT_ACCEPTANCE_TRACKER_HPP_ -#define JTTY_DRAFT_ACCEPTANCE_TRACKER_HPP_ - -#include <QHash> - -class JttyDraftAcceptanceTracker -{ -public: - void noteDraftChanged () noexcept - { - ++revision_; - } - - void trackSubmission (qint64 requestId) - { - submissions_.insert (requestId, revision_); - } - - bool hasPendingSubmissionForCurrentDraft () const - { - for (auto it = submissions_.cbegin (); it != submissions_.cend (); ++it) { - if (it.value () == revision_) { - return true; - } - } - return false; - } - - bool isPending (qint64 requestId) const - { - return submissions_.contains (requestId); - } - - bool accept (qint64 requestId) - { - auto const it = submissions_.find (requestId); - if (it == submissions_.end ()) { - return false; - } - - auto const submittedRevision = it.value (); - submissions_.erase (it); - return submittedRevision == revision_; - } - - void reject (qint64 requestId) - { - submissions_.remove (requestId); - } - -private: - quint64 revision_ {0}; - QHash<qint64, quint64> submissions_; -}; - -#endif diff --git a/widgets/JttyLiveEntry.hpp b/widgets/JttyLiveEntry.hpp new file mode 100644 index 00000000..fc4810d8 --- /dev/null +++ b/widgets/JttyLiveEntry.hpp @@ -0,0 +1,53 @@ +// -*- Mode: C++ -*- +#ifndef JTTY_LIVE_ENTRY_HPP +#define JTTY_LIVE_ENTRY_HPP + +#include <QString> +#include <QStringList> + +namespace Jtty +{ + // Widest lookahead try_compact() uses (lib/jtty/jtty_mod.f90, words(3)); holding back this many trailing words guarantees an atom in progress is never split by an early commit. + inline constexpr int maxCompactAtomWords = 3; + + struct IncrementalCommitPlan + { + QString text; // Text to pack and send now; empty means nothing yet. + int length {0}; // uncommittedText.left(length) == text, exactly. + }; + + // Number of complete (space-terminated) words in uncommittedText -- a word still being typed (no trailing space yet) doesn't count. Exposed so callers can gate on how much has piled up, not just whether anything has. + inline int completeWordCount (QString const& uncommittedText) + { + if (uncommittedText.isEmpty ()) return 0; + bool const endsWithCompleteWord = uncommittedText.back () == QLatin1Char {' '}; + QStringList const words = uncommittedText.split ( + QLatin1Char {' '}, Qt::SkipEmptyParts); + return endsWithCompleteWord ? words.size () : words.size () - 1; + } + + // Releases uncommittedText up to its trailing holdbackWords complete words (plus any partial word), since a compact atom there could still be extended by what's typed next; forceFlush releases all of it (newline/segment-limit boundary). Assumes single-space-normalized input, matching prepareTransmitText's convention. + inline IncrementalCommitPlan planIncrementalCommit ( + QString const& uncommittedText, bool forceFlush = false, + int holdbackWords = maxCompactAtomWords) + { + if (uncommittedText.isEmpty ()) return {}; + if (forceFlush) return {uncommittedText, uncommittedText.size ()}; + + int const commitWordCount = completeWordCount (uncommittedText) - holdbackWords; + if (commitWordCount <= 0) return {}; + + // Advance to the end of the commitWordCount-th word's trailing space, so the remainder starts cleanly at the next word. + int length = 0; + int wordsSeen = 0; + while (wordsSeen < commitWordCount) { + int const spaceAt = uncommittedText.indexOf (QLatin1Char {' '}, length); + Q_ASSERT (spaceAt >= 0); // completeWordCount already bounds this walk. + length = spaceAt + 1; + ++wordsSeen; + } + return {uncommittedText.left (length), length}; + } +} + +#endif diff --git a/widgets/JttyMessages.hpp b/widgets/JttyMessages.hpp index 2a1f4162..9f51a6a0 100644 --- a/widgets/JttyMessages.hpp +++ b/widgets/JttyMessages.hpp @@ -5,6 +5,7 @@ #include <algorithm> #include <cmath> #include <cstddef> +#include <optional> #include <type_traits> #include <QByteArray> @@ -17,6 +18,35 @@ namespace Jtty { + // A content-free "keep transmitting" pattern (ordinary TEXT5-encoded text, nothing protocol-special) used to bridge a typing pause without PTT dropping/re-keying; '<' isn't used in normal chat text, so it's recognized and suppressed wherever JTTY text is displayed or logged. + inline QString const jttyFillerText = + QStringLiteral ("<<<<< <<<<<"); + + inline bool isJttyFillerText (QString const& text) + { + QString const trimmed = text.trimmed (); + if (trimmed.isEmpty ()) return false; + for (QChar const c : trimmed) { + if (c != QLatin1Char ('<') && c != QLatin1Char (' ')) return false; + } + return true; + } + + // Collapses embedded filler runs (any internal spacing) to a single space, without trimming the string's own leading/trailing edge. For a growing-message delta fragment (e.g. ReceiveResultController's N1MM echo), a leading/trailing space is the word boundary against already-echoed text, not something filler-adjacent to discard. + inline QString collapseJttyFillerRuns (QString text) + { + static QRegularExpression const pattern ( + QStringLiteral ("\\s*(?:<{5}\\s*)+")); + text.replace (pattern, QStringLiteral (" ")); + return text; + } + + // Filler travels gaplessly inside the same growing message as the real content around it, so it shows up embedded mid-string rather than as an isolated update; strips one-or-more 5-char '<' blocks (any internal spacing) and collapses the surrounding whitespace to a single space. + inline QString stripJttyFillerText (QString text) + { + return collapseJttyFillerRuns (text).simplified (); + } + struct ParsedDecodeLine { int frequency {0}; @@ -28,12 +58,6 @@ namespace Jtty { QString text; bool substituted {false}; - bool truncated {false}; - - bool changed () const - { - return substituted || truncated; - } }; enum class NativeAtomKind : qint8 @@ -141,6 +165,7 @@ namespace Jtty NativeExchangeProfile exchangeProfile {NativeExchangeProfile::None}; QString configuredExchange; QString grid; + int snr {-10}; // SNR of received signal, for %R; stubbed until the decoder reports it NativeMacroContext () = default; @@ -191,15 +216,15 @@ namespace Jtty inline PreparedTransmitText prepareTransmitText (QString const& message) { PreparedTransmitText result; - int const maxLength {maxTransmitLength}; - result.truncated = message.size () > maxLength; - QString const bounded = message.left (maxLength); - result.text.reserve (bounded.size ()); + result.text.reserve (message.size ()); - for (QChar c : bounded) { + for (QChar c : message) { if (c == QChar::Null || c == QLatin1Char {'~'}) { result.text.append (QLatin1Char {' '}); result.substituted = true; + } else if (c == QLatin1Char {'\n'} || c == QLatin1Char {'\r'}) { + // A forced segment boundary, not a character; execute_jtty_tx splits on it. + result.text.append (QLatin1Char {'\n'}); } else if (isSourceCharacter (c)) { result.text.append (c); } else { @@ -211,25 +236,54 @@ namespace Jtty return result; } - // A message being queued behind one still transmitting (FIFO chaining, - // see MainWindow::execute_jtty_tx) gets a leading space inserted, since - // the user is unlikely to remember (or want) to type one themselves, - // and unlikely to hit Return mid-word. Re-bounds to maxTransmitLength - // in case the message was already at prepareTransmitText's limit. - // No-op (returns message unchanged) when isChained is false. - inline QString withChainedSpacing (QString const& message, bool isChained) + struct TransmitTextSegment { - if (!isChained) return message; - return (QLatin1Char {' '} + message).left (maxTransmitLength); + int offset {0}; + int length {0}; + QString text; + }; + + // Source spans include separator spaces so every submitted character is accounted for. + inline TransmitTextSegment nextTransmitTextSegment ( + QString const& message, int offset, int maximumLength = maxTransmitLength) + { + if (offset < 0 || offset >= message.size () || maximumLength <= 0) return {}; + + int length = std::min ({message.size () - offset, maximumLength, maxTransmitLength}); + if (offset + length < message.size () + && message.at (offset + length) != QLatin1Char {' '}) { + for (int i = length - 1; i > 0; --i) { + if (message.at (offset + i) == QLatin1Char {' '} + && !message.mid (offset, i).trimmed ().isEmpty ()) { + length = i + 1; + break; + } + } + } + return {offset, length, message.mid (offset, length)}; } - // Builds the fixed-width frame passed to genjtty_. The chained leading space - // is transport-only spacing, so it belongs here rather than in the logical - // message that is logged, displayed, and checked for contest serials. - inline QString transmitFrame (QString const& message, bool isChained) + // A segment that does not encode refuses the line rather than being cut shorter: the rest would continue the receiver's 80-column message. + template <typename Encode> + std::optional<QVector<TransmitTextSegment>> encodeTransmitLine (QString const& line, Encode&& encode) { - QString const spaced = withChainedSpacing (message, isChained); - return spaced + QString (maxTransmitLength - spaced.size (), QLatin1Char {' '}); + QVector<TransmitTextSegment> segments; + for (int offset = 0; offset < line.size ();) { + auto const source = nextTransmitTextSegment (line, offset); + if (!source.text.trimmed ().isEmpty ()) { + if (!encode (source.text)) return std::nullopt; + segments.append (source); + } + offset += source.length; + } + return segments; + } + + // An empty result rejects oversized text before it reaches the fixed-width codec. + inline QString transmitFrame (QString const& message) + { + if (message.size () > maxTransmitLength) return {}; + return message + QString (maxTransmitLength - message.size (), QLatin1Char {' '}); } // Number of receive samples in one complete JTTY frame: 59 symbols of 384 @@ -294,6 +348,41 @@ namespace Jtty } } + // Chat/QSO-style templates for JTTY's "FT8 style" message preset (as opposed + // to the contest-exchange-oriented templates above). F7/F8 are left blank. + inline QString ft8StyleMacroTemplate (int functionKey) + { + static QString const templates[] { + QStringLiteral ("%H %M %G"), + QStringLiteral ("%H %M %R"), + QStringLiteral ("%H %M R%R"), + QStringLiteral ("%H %M RRR"), + QStringLiteral ("%H %M 73"), + QStringLiteral ("CQ %M %G"), + QString {}, + QString {} + }; + if (functionKey < 1 || functionKey > 8) return {}; + return templates[functionKey - 1]; + } + + enum class MessageStyle : qint8 { Contest = 0, Ft8 = 1 }; + + // QSettings key for one function key's template under the given style, so + // Contest- and FT8-style edits persist independently of each other. + inline QString messageStyleSettingsKey (MessageStyle style, int functionKey) + { + return style == MessageStyle::Ft8 + ? QStringLiteral ("JTTY_FT8_msg%1").arg (functionKey) + : QStringLiteral ("JTTY_msg%1").arg (functionKey); + } + + inline QString messageStyleDefaultTemplate (MessageStyle style, int functionKey) + { + return style == MessageStyle::Ft8 + ? ft8StyleMacroTemplate (functionKey) : nativeMacroTemplate (functionKey); + } + inline QString normalizedMacroTemplate (QString const& macroTemplate) { return macroTemplate.simplified ().toUpper (); @@ -330,6 +419,11 @@ namespace Jtty return configured; } + inline QString formatSnr (int snr) + { + return QString::asprintf ("%+03d", snr); + } + inline QString expandLiteralMacro (QString macroTemplate, NativeMacroContext const& context) { @@ -338,7 +432,8 @@ namespace Jtty macroTemplate.replace (QStringLiteral ("%Q"), context.hisCall); macroTemplate.replace (QStringLiteral ("%N"), formatSerialNumber (context.serialNumber)); macroTemplate.replace (QStringLiteral ("%E"), nativeExchangeFieldText (context)); - macroTemplate.replace (QStringLiteral ("%G"), context.grid); + macroTemplate.replace (QStringLiteral ("%G"), context.grid.trimmed ().toUpper ().left (4)); + macroTemplate.replace (QStringLiteral ("%R"), formatSnr (context.snr)); return macroTemplate; } @@ -808,6 +903,14 @@ namespace Jtty tsyncSeconds)); } + // Matches a decode line's freq/SNR column layout with the SNR field left + // blank (a sent message has no measured SNR), so Tx and Rx lines line up. + inline QString formatJttyTxLine (float frequency, QString const& message) + { + QString const frequencyText = QStringLiteral ("%1").arg (qRound (frequency), 4); + return frequencyText + QStringLiteral (" ") + message; + } + inline ParsedDecodeLine parseDecodeLine (QString const& line) { ParsedDecodeLine result; @@ -859,6 +962,21 @@ namespace Jtty return result; } + // Format one JTTY decode line for display/logging: "Freq SNR Message" (a + // leading UTC time label, when wanted, is prepended by the caller). SNR is + // plain right-justified, no zero-pad/forced sign -- matches the existing + // decode-pane convention used by other modes (e.g. FT8's own line format, + // lib/decoder_callbacks.f90, "i4" for its SNR field), deliberately + // different from formatSnr's zero-padded convention for the %R Tx macro. + inline QString formatJttyDecodeLine (float frequency, int snr, QString const& message) + { + QString const frequencyText = QStringLiteral ("%1").arg (qRound (frequency), 4); + QString const snrText = QStringLiteral ("%1").arg (snr, 3); + return message.isEmpty () + ? frequencyText + : frequencyText + QStringLiteral (" ") + snrText + QStringLiteral (" ") + message; + } + struct DecodeLineChange { bool messageChanged {false}; @@ -888,6 +1006,7 @@ namespace Jtty QString text; float sequenceStart {0.f}; bool complete {false}; + int snr {-10}; }; inline bool shouldApplyToQsoHistory (bool alreadyPresent, float frequency, diff --git a/widgets/JttyMmttyHandoff.hpp b/widgets/JttyMmttyHandoff.hpp new file mode 100644 index 00000000..9969674c --- /dev/null +++ b/widgets/JttyMmttyHandoff.hpp @@ -0,0 +1,78 @@ +// -*- Mode: C++ -*- +#ifndef JTTY_MMTTY_HANDOFF_HPP +#define JTTY_MMTTY_HANDOFF_HPP + +#include <QVector> +#include <QtGlobal> + +namespace Jtty +{ + class MmttyHandoff + { + public: + enum class SubmitAction + { + Reject, + Submit, + StopThenSubmit + }; + + explicit MmttyHandoff (int timeoutMs = 10000) + : timeoutMs_ {timeoutMs} + { + } + + int timeoutMs () const noexcept {return timeoutMs_;} + bool active () const noexcept {return waitingForStop_;} + bool empty () const noexcept {return requestIds_.isEmpty ();} + QVector<qint64> const& requestIds () const noexcept {return requestIds_;} + + static SubmitAction planSubmission (bool valid, bool jttySessionActive, + bool backendBusy) noexcept + { + if (!valid) return SubmitAction::Reject; + if (!jttySessionActive && backendBusy) { + return SubmitAction::StopThenSubmit; + } + return SubmitAction::Submit; + } + + bool queue (qint64 requestId) + { + if (requestIds_.size () >= 64) return false; + requestIds_.append (requestId); + return true; + } + void waitForStop () noexcept {waitingForStop_ = true;} + + bool stopCompleted () noexcept + { + if (!waitingForStop_) return false; + waitingForStop_ = false; + return true; + } + + QVector<qint64> expire () + { + auto const ids = requestIds_; + reset (); + return ids; + } + + void submitted (qint64 requestId) {requestIds_.removeOne (requestId);} + void abort () {reset ();} + + private: + void reset () + { + requestIds_.clear (); + waitingForStop_ = false; + } + + int timeoutMs_; + QVector<qint64> requestIds_; + bool waitingForStop_ {false}; + }; +} + +#endif diff --git a/widgets/JttyN1mmOutput.hpp b/widgets/JttyN1mmOutput.hpp index ad92fc23..dc64f7a8 100644 --- a/widgets/JttyN1mmOutput.hpp +++ b/widgets/JttyN1mmOutput.hpp @@ -35,6 +35,16 @@ namespace Jtty } void abort () { *this = N1mmOutput {}; } + // An externally triggered abort (operator stop, watchdog) must resolve + // outstanding requests and close the transaction so OUTPUTCOMPLETE can + // still be reported. Explicit N1MM ABORT uses abort(), which discards it. + void externalAbort () + { + requests_.clear (); + startRequested_ = false; + if (completionPending_) finishRequested_ = true; + } + bool takeCompletion (bool audioActive, bool drained = false) { // Rejections can precede more TXTEXT in the same transaction. OFF diff --git a/widgets/JttySpectrum.cpp b/widgets/JttySpectrum.cpp new file mode 100644 index 00000000..38922bcb --- /dev/null +++ b/widgets/JttySpectrum.cpp @@ -0,0 +1,112 @@ +#include "JttySpectrum.hpp" + +#include <algorithm> +#include <cmath> + +constexpr int JttySpectrumFrame::BinCount; +constexpr float JttySpectrumFrame::BinWidth; +constexpr int JttySpectrum::FftSize; +constexpr int JttySpectrum::Hop; + +extern "C" { + void nuttal_window_ (float *, int *); + void four2a_ (float *, int *, int *, int *, int *); + void flat1_ (float *, int *, int *, float *); + void smo_ (float *, int *, float *, int *); +} + +JttySpectrum::JttySpectrum () +{ + int size = FftSize; + nuttal_window_ (window_.data (), &size); +} + +void JttySpectrum::begin (quint64 reception, qint64 firstSample, qint64 utcFirstSampleMs) +{ + reception_ = reception; + origin_ = nextSample_ = firstSample; + utcOriginMs_ = utcFirstSampleMs; + frameCount_ = 0; + pending_ = write_ = 0; + power_ = 0; + peak_ = 0; + pcm_.fill (0); + average_.fill (0); + frame_ = JttySpectrumFrame {}; +} + +bool JttySpectrum::process (qint64 firstSample, qint16 const * pcm, int count, + int inputGain, bool lowSidelobes, int smoothing, + std::function<void (JttySpectrumFrame const&)> const& emitFrame) +{ + if (!reception_ || firstSample != nextSample_ || count < 0 || (!pcm && count)) return false; + for (int i = 0; i < count; ++i) { + auto const value = pcm[i]; + pcm_[write_] = value; + write_ = (write_ + 1) % FftSize; + if (nextSample_ - origin_ >= 10) { + power_ += double (value) * value; + peak_ = std::max (peak_, std::abs (float (value))); + } + ++nextSample_; + if (++pending_ == Hop) { + transform (inputGain, lowSidelobes, smoothing); + pending_ = 0; + power_ = 0; + peak_ = 0; + emitFrame (frame_); + } + } + return true; +} + +void JttySpectrum::transform (int inputGain, bool lowSidelobes, int smoothing) +{ + for (int i = 0; i < FftSize; ++i) { + fft_[i] = 0.1f * pcm_[(write_ + i) % FftSize]; + if (lowSidelobes) fft_[i] *= window_[i]; + } + int size = FftSize; + int dimension = 1; + int sign = -1; + int form = 0; + four2a_ (fft_.data (), &size, &dimension, &sign, &form); + ++frameCount_; + // Cap the averaging time at 180 seconds so long receptions remain responsive. + double const averageFrames = std::min<quint64> (frameCount_, 180 * 12000 / Hop); + float const factor = (1.0f / FftSize) * (1.0f / FftSize); + float const gain = std::pow (10.0f, 0.1f * inputGain); + for (int i = 0; i < JttySpectrumFrame::BinCount; ++i) { + float const power = factor * (fft_[2 * i] * fft_[2 * i] + fft_[2 * i + 1] * fft_[2 * i + 1]); + average_[i] += (power - average_[i]) / averageFrames; + frame_.cumulative[i] = float (average_[i]); + frame_.bins[i] = 1000.0f * gain * power; + } + if (frameCount_ % 10 == 0) { + static constexpr int widths[] = {1, 2, 4, 9, 18, 36, 72}; + int width = widths[std::max (0, std::min (smoothing, 6))]; + int smooth = 4 * std::min (10 * width, 150); + int count = JttySpectrumFrame::BinCount; + auto& yellow = frame_.linearAverage; + flat1_ (frame_.cumulative.data (), &count, &smooth, yellow.data ()); + if (width >= 2) { + std::array<float, JttySpectrumFrame::BinCount> scratch; + smo_ (yellow.data (), &count, scratch.data (), &width); + smo_ (yellow.data (), &count, scratch.data (), &width); + } + std::fill (yellow.begin (), yellow.begin () + 250, 0); + int const first = int (500.0f / JttySpectrumFrame::BinWidth) - 1; + int const last = int (2700.0f / JttySpectrumFrame::BinWidth); + float const minimum = *std::min_element (yellow.begin () + first, yellow.begin () + last); + float const maximum = *std::max_element (yellow.begin (), yellow.end ()); + if (maximum > minimum && std::isfinite (maximum) && std::isfinite (minimum)) { + for (auto& value : yellow) value = std::max (0.0f, 50.0f / (maximum - minimum) * (value - minimum)); + } else { + yellow.fill (0); + } + } + frame_.row = {reception_, nextSample_ - Hop, nextSample_, + utcOriginMs_ + (nextSample_ - origin_) / 12, false}; + frame_.powerDb = power_ > 0 ? 10.0 * std::log10 (power_ / Hop) : 0; + frame_.maxPowerDb = peak_ > 0 ? 20.0f * std::log10 (peak_) : 0; +} diff --git a/widgets/JttySpectrum.hpp b/widgets/JttySpectrum.hpp new file mode 100644 index 00000000..d5e67f08 --- /dev/null +++ b/widgets/JttySpectrum.hpp @@ -0,0 +1,66 @@ +#ifndef JTTY_SPECTRUM_HPP +#define JTTY_SPECTRUM_HPP + +#include <QtGlobal> +#include <array> +#include <functional> + +struct JttyWaterfallRow +{ + quint64 reception = 0; + qint64 beginSample = 0; + qint64 endSample = 0; + qint64 utcEndMs = 0; + bool gap = false; + + bool hasAudio () const { return reception != 0 && !gap && endSample > beginSample; } +}; + +struct JttySpectrumFrame +{ + static constexpr int BinCount = 6827; + static constexpr float BinWidth = 12000.0f / 16384; + JttyWaterfallRow row; + std::array<float, BinCount> bins {}; + std::array<float, BinCount> cumulative {}; + std::array<float, BinCount> linearAverage {}; + float powerDb = 0; + float maxPowerDb = 0; +}; + +// Consumes new PCM once; FFT scratch is used only on the serialized DSP thread. +class JttySpectrum +{ +public: + static constexpr int FftSize = 16384; + static constexpr int Hop = 3456; + + JttySpectrum (); + JttySpectrum (JttySpectrum const&) = delete; + JttySpectrum& operator= (JttySpectrum const&) = delete; + + void begin (quint64 reception, qint64 firstSample, qint64 utcFirstSampleMs); + bool process (qint64 firstSample, qint16 const * pcm, int count, + int inputGain, bool lowSidelobes, int smoothing, + std::function<void (JttySpectrumFrame const&)> const& emitFrame); + +private: + void transform (int inputGain, bool lowSidelobes, int smoothing); + + quint64 reception_ = 0; + qint64 origin_ = 0; + qint64 nextSample_ = 0; + qint64 utcOriginMs_ = 0; + quint64 frameCount_ = 0; + int pending_ = 0; + int write_ = 0; + double power_ = 0; + float peak_ = 0; + std::array<qint16, FftSize> pcm_ {}; + std::array<float, FftSize> window_ {}; + std::array<float, FftSize + 2> fft_ {}; + std::array<double, JttySpectrumFrame::BinCount> average_ {}; + JttySpectrumFrame frame_; +}; + +#endif diff --git a/widgets/JttyTransmitQueue.hpp b/widgets/JttyTransmitQueue.hpp new file mode 100644 index 00000000..f91cd1f2 --- /dev/null +++ b/widgets/JttyTransmitQueue.hpp @@ -0,0 +1,156 @@ +#ifndef JTTY_TRANSMIT_QUEUE_HPP_ +#define JTTY_TRANSMIT_QUEUE_HPP_ + +#include <QString> +#include <QStringList> +#include <QVector> + +#include <utility> + +namespace Jtty +{ + struct TransmitSegment + { + QString text; + QVector<int> tones; + qint64 endSample {0}; + int frequency {1500}; + // 0-indexed start offset into text of each encoded frame; empty if the caller didn't ask the encoder for boundaries. + QVector<int> frameCharStarts {}; + + qint64 sampleCount () const + { + return qint64 {tones.size ()} * 1536; + } + }; + + class TransmitQueue + { + public: + struct Request + { + qint64 id; + QVector<TransmitSegment> segments; + int committed {0}; + }; + + void append (qint64 id, QVector<TransmitSegment> segments) + { + Q_ASSERT (id > 0); + Q_ASSERT (!segments.isEmpty ()); + requests_.append ({id, std::move (segments), 0}); + } + + bool empty () const + { + return requests_.isEmpty (); + } + + bool hasUncommitted () const + { + return nextSegment () != nullptr; + } + + qint64 nextRequestId () const + { + for (auto const& request : requests_) { + if (request.committed < request.segments.size ()) { + return request.id; + } + } + return 0; + } + + TransmitSegment const * nextSegment () const + { + for (auto const& request : requests_) { + if (request.committed < request.segments.size ()) { + return &request.segments.at (request.committed); + } + } + return nullptr; + } + + bool commitNext (qint64 endSample) + { + Q_ASSERT (endSample > 0); + for (auto& request : requests_) { + if (request.committed < request.segments.size ()) { + request.segments[request.committed].endSample = endSample; + return request.committed++ == 0; + } + } + return false; + } + + // Source consumption only updates progress; completion requires backend drain. + QVector<qint64> complete (qint64 totalAtDrain) + { + QVector<qint64> completed; + for (auto const& request : requests_) { + if (request.committed != request.segments.size () + || request.segments.constLast ().endSample > totalAtDrain) { + break; + } + completed.append (request.id); + } + requests_.remove (0, completed.size ()); + return completed; + } + + QVector<qint64> cancel () + { + QVector<qint64> cancelled; + for (auto const& request : requests_) { + cancelled.append (request.id); + } + requests_.clear (); + return cancelled; + } + + int segmentCount () const + { + int count = 0; + for (auto const& request : requests_) { + count += request.segments.size (); + } + return count; + } + + int remainingSegments (qint64 servedSamples) const + { + int count = 0; + for (auto const& request : requests_) { + for (auto const& segment : request.segments) { + if (!segment.endSample || segment.endSample > servedSamples) { + ++count; + } + } + } + return count; + } + + QString pendingText (qint64 servedSamples) const + { + QStringList pending; + for (auto const& request : requests_) { + for (auto const& segment : request.segments) { + if (!segment.endSample || segment.endSample > servedSamples) { + pending.append (segment.text); + } + } + } + return pending.join ('\n'); + } + + QVector<Request> const& requests () const + { + return requests_; + } + + private: + QVector<Request> requests_; + }; +} + +#endif diff --git a/widgets/JttyTxLifecycle.hpp b/widgets/JttyTxLifecycle.hpp new file mode 100644 index 00000000..ede953fc --- /dev/null +++ b/widgets/JttyTxLifecycle.hpp @@ -0,0 +1,349 @@ +#ifndef JTTY_TX_LIFECYCLE_HPP_ +#define JTTY_TX_LIFECYCLE_HPP_ + +#include <algorithm> +#include <chrono> +#include <optional> +#include <utility> +#include <vector> + +#include "Audio/TxAudioQueue.hpp" + +class JttyTxLifecycle final +{ +public: + enum class Backend + { + None, + Local, + Tci + }; + + enum class Phase + { + Idle, + AwaitingEnqueue, + Ready, + Transmitting, + Stopping + }; + + using Clock = std::chrono::steady_clock; + using Duration = std::chrono::milliseconds; + using TimePoint = Clock::time_point; + + struct Pending + { + qint64 enqueue_id {0}; + qint64 request_id {0}; + }; + + struct Drain + { + TxAudioQueueEpoch epoch {}; + qint64 total {0}; + }; + + struct StopContext + { + Backend backend {Backend::None}; + TxAudioQueueEpoch epoch {}; + TxAudioQueueProgress progress {}; + }; + + struct EnqueueResolution + { + std::optional<Pending> pending; + std::optional<Drain> drain; + }; + + struct BatchResolution + { + std::vector<Pending> pending; + std::optional<Drain> drain; + }; + + static constexpr Duration defaultPreacceptanceTimeout () noexcept + { + return std::chrono::seconds {10}; + } + + explicit JttyTxLifecycle ( + Duration preacceptance_timeout = defaultPreacceptanceTimeout ()) noexcept + : preacceptance_timeout_ {preacceptance_timeout} + { + } + + bool begin (Backend backend, TxAudioQueueEpoch epoch) noexcept + { + if (Phase::Idle != phase_ || Backend::None == backend || !epoch.isValid ()) { + return false; + } + + backend_ = backend; + epoch_ = epoch; + progress_.epoch = epoch; + last_epoch_ = std::max (last_epoch_, epoch.value ()); + phase_ = Phase::AwaitingEnqueue; + return true; + } + + TxAudioQueueEpoch begin (Backend backend) noexcept + { + auto const next_epoch = TxAudioQueueEpoch {last_epoch_ + 1}; + return begin (backend, next_epoch) ? next_epoch : TxAudioQueueEpoch::invalid (); + } + + bool addPending (qint64 enqueue_id, qint64 request_id, + TimePoint now = Clock::now ()) + { + if (!canResolveEnqueue () || enqueue_id <= 0 || request_id <= 0 + || findPending (enqueue_id) != pending_.end ()) { + return false; + } + + if (pending_.empty ()) { + preacceptance_deadline_ = now + preacceptance_timeout_; + } + pending_.push_back (Pending {enqueue_id, request_id}); + return true; + } + + EnqueueResolution accept (TxAudioQueueEpoch epoch, qint64 enqueue_id, + TxAudioQueueProgress progress) + { + if (!canResolveEnqueue () || epoch != epoch_ || progress.epoch != epoch + || progress.total_samples < progress_.total_samples) { + return {}; + } + + auto const found = findPending (enqueue_id); + if (pending_.end () == found) { + return {}; + } + + EnqueueResolution result; + result.pending = *found; + pending_.erase (found); + + if (progress.total_samples > progress_.total_samples) { + progress_ = progress; + deferred_drain_.reset (); + } else { + progress_ = progress; + if (pending_.empty ()) { + result.drain = takeMatchingDeferredDrain (); + } + } + + if (Phase::AwaitingEnqueue == phase_) { + phase_ = Phase::Ready; + } + clearDeadlineWhenSettled (); + return result; + } + + EnqueueResolution accept (TxAudioQueueEpoch epoch, qint64 enqueue_id, + qint64 committed_total) + { + auto progress = progress_; + progress.epoch = epoch; + progress.total_samples = committed_total; + return accept (epoch, enqueue_id, progress); + } + + EnqueueResolution fail (TxAudioQueueEpoch epoch, qint64 enqueue_id) + { + if (!canResolveEnqueue () || epoch != epoch_) { + return {}; + } + + auto const found = findPending (enqueue_id); + if (pending_.end () == found) { + return {}; + } + + EnqueueResolution result; + result.pending = *found; + pending_.erase (found); + if (pending_.empty ()) { + result.drain = takeMatchingDeferredDrain (); + } + clearDeadlineWhenSettled (); + return result; + } + + BatchResolution failAll () + { + BatchResolution result; + if (Phase::Idle == phase_) { + return result; + } + + result.pending = std::move (pending_); + pending_.clear (); + if (Phase::Stopping == phase_) { + deferred_drain_.reset (); + } else { + result.drain = takeMatchingDeferredDrain (); + } + preacceptance_deadline_.reset (); + return result; + } + + std::optional<Drain> observeDrain (TxAudioQueueEpoch epoch, qint64 total) + { + if (!isActive () || Phase::Stopping == phase_ || epoch != epoch_ + || total != progress_.total_samples) { + return {}; + } + + Drain const drain {epoch, total}; + if (!pending_.empty ()) { + deferred_drain_ = drain; + return {}; + } + return drain; + } + + bool markTransmitting () noexcept + { + if (Phase::Ready != phase_) { + return false; + } + phase_ = Phase::Transmitting; + return true; + } + + std::optional<StopContext> beginStop () noexcept + { + if (Phase::Idle == phase_) { + return {}; + } + if (Phase::Stopping != phase_) { + stop_context_ = StopContext {backend_, epoch_, progress_}; + backend_stop_routed_ = false; + preacceptance_deadline_.reset (); + phase_ = Phase::Stopping; + } + return stop_context_; + } + + bool markBackendStopRouted (StopContext const& context) noexcept + { + if (Phase::Stopping != phase_ || !stop_context_ + || !sameStopContext (*stop_context_, context)) { + return false; + } + backend_stop_routed_ = true; + return true; + } + + bool reset () noexcept + { + if (Phase::Stopping != phase_ || !backend_stop_routed_) { + return false; + } + + backend_ = Backend::None; + epoch_ = TxAudioQueueEpoch::invalid (); + progress_ = {}; + pending_.clear (); + deferred_drain_.reset (); + stop_context_.reset (); + backend_stop_routed_ = false; + preacceptance_deadline_.reset (); + phase_ = Phase::Idle; + return true; + } + + bool isActive () const noexcept {return Phase::Idle != phase_;} + bool active () const noexcept {return isActive ();} + bool hasPending () const noexcept {return !pending_.empty ();} + Phase phase () const noexcept {return phase_;} + Backend backend () const noexcept {return backend_;} + TxAudioQueueEpoch epoch () const noexcept {return epoch_;} + TxAudioQueueProgress progress () const noexcept {return progress_;} + qint64 committedTotal () const noexcept {return progress_.total_samples;} + std::vector<Pending> const& pending () const noexcept {return pending_;} + std::optional<Drain> const& deferredDrain () const noexcept + { + return deferred_drain_; + } + std::optional<StopContext> const& stopContext () const noexcept + { + return stop_context_; + } + bool backendStopRouted () const noexcept {return backend_stop_routed_;} + Duration preacceptanceTimeout () const noexcept + { + return preacceptance_timeout_; + } + std::optional<TimePoint> const& preacceptanceDeadline () const noexcept + { + return preacceptance_deadline_; + } + bool preacceptanceTimedOut (TimePoint now = Clock::now ()) const noexcept + { + return preacceptance_deadline_ && now >= *preacceptance_deadline_; + } + +private: + using PendingIterator = std::vector<Pending>::iterator; + + bool canResolveEnqueue () const noexcept + { + return Phase::Idle != phase_ && Phase::Stopping != phase_; + } + + PendingIterator findPending (qint64 enqueue_id) noexcept + { + return std::find_if (pending_.begin (), pending_.end (), + [enqueue_id] (Pending const& pending) { + return pending.enqueue_id == enqueue_id; + }); + } + + std::optional<Drain> takeMatchingDeferredDrain () noexcept + { + if (!deferred_drain_ || deferred_drain_->epoch != epoch_ + || deferred_drain_->total != progress_.total_samples) { + deferred_drain_.reset (); + return {}; + } + auto result = deferred_drain_; + deferred_drain_.reset (); + return result; + } + + void clearDeadlineWhenSettled () noexcept + { + if (pending_.empty ()) { + preacceptance_deadline_.reset (); + } + } + + static bool sameStopContext (StopContext const& lhs, + StopContext const& rhs) noexcept + { + return lhs.backend == rhs.backend && lhs.epoch == rhs.epoch + && lhs.progress.epoch == rhs.progress.epoch + && lhs.progress.queued_samples == rhs.progress.queued_samples + && lhs.progress.served_samples == rhs.progress.served_samples + && lhs.progress.total_samples == rhs.progress.total_samples; + } + + Duration preacceptance_timeout_; + Phase phase_ {Phase::Idle}; + Backend backend_ {Backend::None}; + TxAudioQueueEpoch epoch_ {}; + qint64 last_epoch_ {0}; + TxAudioQueueProgress progress_ {}; + std::vector<Pending> pending_; + std::optional<Drain> deferred_drain_; + std::optional<StopContext> stop_context_; + bool backend_stop_routed_ {false}; + std::optional<TimePoint> preacceptance_deadline_; +}; + +#endif diff --git a/widgets/SuggestedFrequenciesDialog.cpp b/widgets/SuggestedFrequenciesDialog.cpp new file mode 100644 index 00000000..561d3f09 --- /dev/null +++ b/widgets/SuggestedFrequenciesDialog.cpp @@ -0,0 +1,252 @@ +#include "widgets/SuggestedFrequenciesDialog.hpp" + +#include <algorithm> +#include <utility> + +#include <QCheckBox> +#include <QComboBox> +#include <QDialogButtonBox> +#include <QEvent> +#include <QGridLayout> +#include <QHBoxLayout> +#include <QLabel> +#include <QKeyEvent> +#include <QPushButton> +#include <QScrollArea> +#include <QSignalBlocker> +#include <QTimer> +#include <QVBoxLayout> + +#include "Radio.hpp" +#include "models/Bands.hpp" +#include "models/FrequencySuggestions.hpp" + +SuggestedFrequenciesDialog::SuggestedFrequenciesDialog ( + Items const& catalog, Items const& working, Bands const& bands, + QSet<QString> new_keys, QWidget * parent) + : QDialog {parent} + , catalog_ {catalog} + , working_ {working} + , bands_ {bands} + , new_keys_ {std::move (new_keys)} + , band_filter_ {new QComboBox {this}} + , mode_filter_ {new QComboBox {this}} + , show_present_ {new QCheckBox {tr ("Show frequencies already in my list"), this}} + , new_only_ {new QCheckBox {tr ("New suggestions only"), this}} + , selected_only_ {new QCheckBox {tr ("Show selected only"), this}} + , list_ {new QScrollArea {this}} + , empty_label_ {new QLabel {this}} +{ + setWindowTitle (tr ("Add suggested frequencies")); + resize (760, 480); + + auto * layout = new QVBoxLayout {this}; + layout->addWidget (new QLabel {tr ("Select the frequencies to add to your working list."), this}); + + auto * filters = new QHBoxLayout; + band_filter_->addItem (tr ("All bands")); + mode_filter_->addItem (tr ("All modes")); + band_filter_->setAccessibleName (tr ("Filter suggested frequencies by band")); + mode_filter_->setAccessibleName (tr ("Filter suggested frequencies by mode")); + QSet<QString> bands_seen; + QSet<int> modes_seen; + for (auto const& item : catalog_) + { + bands_seen.insert (bands_.find (item.frequency_)); + if (item.mode_ != Modes::ALL) modes_seen.insert (item.mode_); + } + auto band_names = bands_seen.values (); + band_names.sort (); + for (auto const& band : band_names) + band_filter_->addItem (band); + QList<int> modes = modes_seen.values (); + std::sort (modes.begin (), modes.end (), [] (int lhs, int rhs) { + return QString::compare (QString::fromLatin1 (Modes::name (static_cast<Modes::Mode> (lhs))), + QString::fromLatin1 (Modes::name (static_cast<Modes::Mode> (rhs))), + Qt::CaseInsensitive) < 0; + }); + for (auto mode : modes) + mode_filter_->addItem (Modes::name (static_cast<Modes::Mode> (mode)), mode); + + filters->addWidget (new QLabel {tr ("Band:"), this}); + filters->addWidget (band_filter_); + filters->addStretch (); + filters->addWidget (new QLabel {tr ("Mode:"), this}); + filters->addWidget (mode_filter_); + layout->addLayout (filters); + layout->addWidget (show_present_); + new_only_->setVisible (!new_keys_.isEmpty ()); + layout->addWidget (new_only_); + selected_only_->setEnabled (false); + layout->addWidget (selected_only_); + + list_->setAccessibleName (tr ("Suggested frequencies")); + list_->setAccessibleDescription (tr ("Check individual frequencies to add them to your working list.")); + list_->setObjectName (QStringLiteral ("suggested_frequencies_list")); + list_->setWidgetResizable (true); + list_->setFocusPolicy (Qt::NoFocus); + layout->addWidget (list_); + empty_label_->setWordWrap (true); + layout->addWidget (empty_label_); + + auto * buttons = new QDialogButtonBox {QDialogButtonBox::Cancel, this}; + cancel_button_ = buttons->button (QDialogButtonBox::Cancel); + add_button_ = buttons->addButton (tr ("Add selected"), QDialogButtonBox::AcceptRole); + cancel_button_->setFocusPolicy (Qt::StrongFocus); + add_button_->setFocusPolicy (Qt::StrongFocus); + cancel_button_->installEventFilter (this); + add_button_->installEventFilter (this); + add_button_->setEnabled (false); + layout->addWidget (buttons); + + connect (band_filter_, QOverload<int>::of (&QComboBox::currentIndexChanged), + this, [this] { refresh (); }); + connect (mode_filter_, QOverload<int>::of (&QComboBox::currentIndexChanged), + this, [this] { refresh (); }); + connect (show_present_, &QCheckBox::toggled, this, [this] { refresh (); }); + connect (new_only_, &QCheckBox::toggled, this, [this] { refresh (); }); + connect (selected_only_, &QCheckBox::toggled, this, [this] { refresh (); }); + connect (buttons, &QDialogButtonBox::accepted, this, &QDialog::accept); + connect (buttons, &QDialogButtonBox::rejected, this, &QDialog::reject); + + refresh (); +} + +bool SuggestedFrequenciesDialog::eventFilter (QObject * watched, QEvent * event) +{ + if (event->type () == QEvent::KeyPress) + { + auto * key = static_cast<QKeyEvent *> (event); + auto const row = row_checkboxes_.indexOf (qobject_cast<QCheckBox *> (watched)); + if (row >= 0 && key->key () == Qt::Key_Tab) + { + if (row + 1 < row_checkboxes_.size ()) row_checkboxes_.at (row + 1)->setFocus (Qt::TabFocusReason); + else cancel_button_->setFocus (Qt::TabFocusReason); + return true; + } + if (row >= 0 && key->key () == Qt::Key_Backtab) + { + if (row > 0) row_checkboxes_.at (row - 1)->setFocus (Qt::BacktabFocusReason); + else (selected_only_->isEnabled () ? static_cast<QWidget *> (selected_only_) + : static_cast<QWidget *> (show_present_)) + ->setFocus (Qt::BacktabFocusReason); + return true; + } + if (watched == cancel_button_ && key->key () == Qt::Key_Tab) + { + (add_button_->isEnabled () ? static_cast<QWidget *> (add_button_) + : static_cast<QWidget *> (band_filter_)) + ->setFocus (Qt::TabFocusReason); + return true; + } + if (watched == cancel_button_ && key->key () == Qt::Key_Backtab) + { + if (!row_checkboxes_.isEmpty ()) row_checkboxes_.last ()->setFocus (Qt::BacktabFocusReason); + else (selected_only_->isEnabled () ? static_cast<QWidget *> (selected_only_) + : static_cast<QWidget *> (show_present_)) + ->setFocus (Qt::BacktabFocusReason); + return true; + } + if (watched == add_button_ && key->key () == Qt::Key_Tab) + { + band_filter_->setFocus (Qt::TabFocusReason); + return true; + } + if (watched == add_button_ && key->key () == Qt::Key_Backtab) + { + cancel_button_->setFocus (Qt::BacktabFocusReason); + return true; + } + } + return QDialog::eventFilter (watched, event); +} + +auto SuggestedFrequenciesDialog::selected_items () const -> Items +{ + Items items; + for (int index = 0; index < catalog_.size (); ++index) + if (selected_.contains (index)) items.append (catalog_.at (index)); + return items; +} + +void SuggestedFrequenciesDialog::refresh () +{ + row_checkboxes_.clear (); + auto * content = new QWidget; + auto * rows = new QGridLayout {content}; + rows->setColumnStretch (5, 1); + QString const titles[] = {tr ("Add"), tr ("Band"), tr ("Mode"), tr ("Region"), + tr ("Dial frequency"), tr ("Description"), tr ("Status")}; + for (int column = 0; column < 7; ++column) + rows->addWidget (new QLabel {titles[column], content}, 0, column); + int row {1}; + for (int index = 0; index < catalog_.size (); ++index) + { + auto const& item = catalog_.at (index); + auto const band = bands_.find (item.frequency_); + auto const present = FrequencySuggestions::is_present (item, working_); + auto const is_new = new_keys_.contains (FrequencySuggestions::key (item)); + if (selected_only_->isChecked ()) + { + if (!selected_.contains (index)) continue; + } + else + { + if (band_filter_->currentIndex () > 0 && band_filter_->currentText () != band) continue; + if (mode_filter_->currentIndex () > 0 + && mode_filter_->currentData ().toInt () != item.mode_) continue; + if (present && !show_present_->isChecked ()) continue; + if (new_only_->isChecked () && !is_new) continue; + } + + auto * checkbox = new QCheckBox {content}; + checkbox->setAccessibleName (tr ("Add %1 MHz, %2, %3") + .arg (Radio::pretty_frequency_MHz_string (item.frequency_), + QString::fromLatin1 (Modes::name (item.mode_)), + QString::fromLatin1 (IARURegions::name (item.region_)))); + checkbox->setEnabled (!present); + checkbox->setChecked (selected_.contains (index)); + checkbox->installEventFilter (this); + connect (checkbox, &QCheckBox::toggled, this, [this, index] (bool checked) { + if (checked) selected_.insert (index); + else selected_.remove (index); + add_button_->setEnabled (!selected_.isEmpty ()); + add_button_->setText (tr ("Add selected (%1)").arg (selected_.size ())); + auto const refresh_needed = selected_only_->isChecked (); + if (selected_.isEmpty ()) + { + QSignalBlocker blocker {selected_only_}; + selected_only_->setChecked (false); + } + selected_only_->setEnabled (!selected_.isEmpty ()); + if (refresh_needed) QTimer::singleShot (0, this, [this] { refresh (); }); + }); + rows->addWidget (checkbox, row, 0); + row_checkboxes_.append (checkbox); + + QString const values[] = { + band, + QString::fromLatin1 (Modes::name (item.mode_)), + QString::fromLatin1 (IARURegions::name (item.region_)), + Radio::pretty_frequency_MHz_string (item.frequency_) + tr (" MHz"), + item.description_, + present ? tr ("Already in your working list") + : (is_new ? tr ("New") : QString {}) + }; + for (int column = 1; column < 7; ++column) + { + auto * label = new QLabel {values[column - 1], content}; + label->setTextInteractionFlags (Qt::NoTextInteraction); + rows->addWidget (label, row, column); + } + ++row; + } + rows->setRowStretch (row, 1); + list_->setWidget (content); + empty_label_->setText (show_present_->isChecked () || new_only_->isChecked () + || selected_only_->isChecked () + || band_filter_->currentIndex () > 0 || mode_filter_->currentIndex () > 0 + ? tr ("No suggested frequencies match these filters.") + : tr ("Your working list already contains every shipped frequency suggestion.")); + empty_label_->setVisible (row == 1); +} diff --git a/widgets/SuggestedFrequenciesDialog.hpp b/widgets/SuggestedFrequenciesDialog.hpp new file mode 100644 index 00000000..be7fc040 --- /dev/null +++ b/widgets/SuggestedFrequenciesDialog.hpp @@ -0,0 +1,49 @@ +#ifndef SUGGESTED_FREQUENCIES_DIALOG_HPP__ +#define SUGGESTED_FREQUENCIES_DIALOG_HPP__ + +#include <QDialog> +#include <QList> +#include <QSet> + +#include "models/FrequencyList.hpp" + +class Bands; +class QCheckBox; +class QComboBox; +class QLabel; +class QPushButton; +class QScrollArea; + +class SuggestedFrequenciesDialog final : public QDialog +{ +public: + using Items = FrequencyList_v2_101::FrequencyItems; + + SuggestedFrequenciesDialog (Items const& catalog, Items const& working, + Bands const& bands, QSet<QString> new_keys, + QWidget * parent = nullptr); + + Items selected_items () const; + +private: + bool eventFilter (QObject * watched, QEvent * event) override; + void refresh (); + + Items const& catalog_; + Items const& working_; + Bands const& bands_; + QSet<QString> new_keys_; + QSet<int> selected_; + QComboBox * band_filter_; + QComboBox * mode_filter_; + QCheckBox * show_present_; + QCheckBox * new_only_; + QCheckBox * selected_only_; + QScrollArea * list_; + QList<QCheckBox *> row_checkboxes_; + QLabel * empty_label_; + QPushButton * add_button_; + QPushButton * cancel_button_; +}; + +#endif diff --git a/widgets/astro.cpp b/widgets/astro.cpp index dcdbac44..a6813f8d 100644 --- a/widgets/astro.cpp +++ b/widgets/astro.cpp @@ -22,7 +22,8 @@ extern "C" { void astrosub(int nyear, int month, int nday, double uth, double freqMoon, - const char * mygrid, const char * hisgrid, + const char * mygrid, const char * hisgrid, bool use_home_coordinates, + double home_latitude, double home_longitude, double * azsun, double * elsun, double * azmoon, double * elmoon, double * azmoondx, double * elmoondx, int * ntsky, int * ndop, int * ndop00, double * ramoon, double * decmoon, double * dgrd, @@ -108,7 +109,8 @@ void Astro::write_settings () settings_->setValue ("LockSkedFreq",ui_->cbLockSkedFreq->isChecked()); } -auto Astro::astroUpdate(QDateTime const& t, QString const& mygrid, QString const& hisgrid, Frequency freq, +auto Astro::astroUpdate(QDateTime const& t, QString const& mygrid, QString const& hisgrid, + bool use_home_coordinates, double home_latitude, double home_longitude, Frequency freq, bool bEchoMode, bool bTx, bool bAuto, bool no_tx_QSY, double TR_period) -> Correction { Frequency freq_moon {freq}; @@ -133,7 +135,7 @@ auto Astro::astroUpdate(QDateTime const& t, QString const& mygrid, QString const // changed argument from &dgrd to &m_dgrd added for Bob KA1GT astrosub(nyear, month, nday, uth, static_cast<double> (freq_moon), mygrid.toLatin1 ().data (), - hisgrid.toLatin1().data(), + hisgrid.toLatin1().data(), use_home_coordinates, home_latitude, home_longitude, &azsun, &elsun, &azmoon, &elmoon, &azmoondx, &elmoondx, &ntsky, &m_dop, &m_dop00, &ramoon, &decmoon, &m_dgrd, &poloffset, &xnr, extraazel, &techo, &width1, &width2, @@ -308,7 +310,7 @@ auto Astro::astroUpdate(QDateTime const& t, QString const& mygrid, QString const double uth {nhr + nmin/60.0 + sec/3600.0}; astrosub(nyear, month, nday, uth, static_cast<double> (freq_moon), mygrid.toLatin1 ().data (), - hisgrid.toLatin1().data(), + hisgrid.toLatin1().data(), use_home_coordinates, home_latitude, home_longitude, &azsun, &elsun, &azmoon, &elmoon, &azmoondx, &elmoondx, &ntsky, &m_dop, &m_dop00, &ramoon, &decmoon, &dgrd, &poloffset, &xnr, extraazel, &techo, &width1, &width2, diff --git a/widgets/astro.h b/widgets/astro.h index e8caf79e..2823299c 100644 --- a/widgets/astro.h +++ b/widgets/astro.h @@ -57,6 +57,9 @@ public: Correction astroUpdate(QDateTime const& t, QString const& mygrid, QString const& hisgrid, + bool use_home_coordinates, + double home_latitude, + double home_longitude, Frequency frequency, bool dx_is_self, bool bTx, diff --git a/widgets/displaytext.cpp b/widgets/displaytext.cpp index f4b4fcba..228df487 100644 --- a/widgets/displaytext.cpp +++ b/widgets/displaytext.cpp @@ -23,6 +23,7 @@ #include <QResizeEvent> #include "Configuration.hpp" +#include "Radio.hpp" #include "Decoder/decodedtext.h" #include "Network/LotWUsers.hpp" #include "models/DecodeHighlightingModel.hpp" @@ -49,7 +50,6 @@ bool muted = false; namespace { QRegularExpression const message_73_regexp {"^(73|RR73)$"}; - QRegularExpression const grid_regexp {"\\A(?![Rr]{2}73)[A-Ra-r]{2}[0-9]{2}([A-Xa-x]{2}){0,1}\\z"}; // Trailing #? matches Q65's "copied last Tx" flag marker (e.g. "q3#"), // appended after the usual AP-type/averaging-count qualifier. QRegularExpression const ap_regexp {R"((?:\?\s)?(?:a[0-9]|q[0-9][0-9*]?#?)$)"}; @@ -309,34 +309,18 @@ void DisplayText::insertLineSpacer(QString const& line) namespace { using Highlight = DecodeHighlightingModel::Highlight; - using highlight_types = std::vector<Highlight>; + using highlight_types = DecodeHighlightingModel::HighlightTypes; Highlight set_colours (Configuration const * config, QColor * bg, QColor * fg, highlight_types const& types) { - Highlight result = Highlight::CQ; if (config) { - QListIterator<DecodeHighlightingModel::HighlightInfo> it {config->decode_highlighting ().items ()}; - // iterate in reverse to honor priorities - it.toBack (); - while (it.hasPrevious ()) - { - auto const& item = it.previous (); - auto const& type = std::find (types.begin (), types.end (), item.type_); - if (type != types.end () && item.enabled_) - { - if (item.background_.style () != Qt::NoBrush) - { - *bg = item.background_.color (); - } - if (item.foreground_.style () != Qt::NoBrush) - { - *fg = item.foreground_.color (); - } - result = item.type_; - } - } + auto const resolved = DecodeHighlightingModel::resolve_colors ( + config->decode_highlighting ().items (), types, *bg, *fg); + *bg = resolved.background_; + *fg = resolved.foreground_; + return resolved.type_; } - return result; // highest priority enabled highlighting + return Highlight::CQ; } } @@ -761,7 +745,7 @@ bool DisplayText::displayDecodedText(DecodedText const& decodedText, QString con QString dxCall; QString dxGrid; decodedText.deCallAndGrid (/*out*/ dxCall, dxGrid); - if(!dxGrid.contains(grid_regexp)) dxGrid=""; + if(!dxGrid.contains(Radio::decoded_grid_pattern())) dxGrid=""; message = message.left (message.indexOf (QChar::Nbsp)).trimmed (); // strip appended info QString extra; QString state; // NJ0A -- populated only when GridMap() is enabled; drives diff --git a/widgets/logqso.cpp b/widgets/logqso.cpp index 5a81f145..91f581c6 100644 --- a/widgets/logqso.cpp +++ b/widgets/logqso.cpp @@ -83,7 +83,7 @@ namespace LogQSO::LogQSO(QString const& programTitle, QSettings * settings , Configuration const * config, LogBook * log, QWidget *parent) - : QDialog {parent, Qt::WindowStaysOnTopHint | Qt::WindowTitleHint | Qt::WindowSystemMenuHint} + : QDialog {parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint} , ui(new Ui::LogQSO) , m_settings (settings) , m_config {config} @@ -218,7 +218,13 @@ void LogQSO::initLogQSO(QString const& hisCall, QString const& hisGrid, QString Radio::Frequency dialFreq, bool noSuffix, QString xSent, QString xRcvd) { - if(!isHidden()) return; + if (!isHidden ()) + { + if (isMinimized ()) showNormal (); + raise (); + activateWindow (); + return; + } QPushButton* okBtn = ui->buttonBox->button(QDialogButtonBox::Ok); okBtn->setAutoDefault(true); okBtn->setDefault(true); diff --git a/widgets/mainwindow.cpp b/widgets/mainwindow.cpp index 596cb0e0..41f25835 100644 --- a/widgets/mainwindow.cpp +++ b/widgets/mainwindow.cpp @@ -405,9 +405,9 @@ extern "C" { void chk_samples_(int* m_ihsym,int* k, int* m_hsymStop); - void get_q3list_(char* fname, bool* bDiskData, int* nlist, char* list, FCL len1, FCL len2); + void get_q3list_(char* fname, bool* bDiskData, int* capacity, int* nlist, char* list, FCL len1, FCL len2); - void rm_q3list_(char* callsign, FCL len); + void rm_q3list_(char* fname, char* callsign, FCL len1, FCL len2); void jpl_setup_(char* fname, FCL len); } @@ -506,14 +506,14 @@ namespace } QRegExp const MainWindow::message_alphabet {"[- @A-Za-z0-9+./?#<>;$]*"}; -QRegularExpression const MainWindow::grid_regexp {"\\A(?![Rr]{2}73)[A-Ra-r]{2}[0-9]{2}([A-Xa-x]{2}){0,1}\\z"}; +QRegularExpression const MainWindow::grid_regexp {Radio::decoded_grid_pattern()}; QRegularExpression const MainWindow::non_r_db_regexp {"\\A[-+]{1}[0-9]{1,2}\\z"}; constexpr int MainWindow::MaxActiveStationRows; constexpr int MainWindow::MaxQ65PileupCallers; //--------------------------------------------------- MainWindow constructor MainWindow::MainWindow(QDir const& temp_directory, bool multiple, - MultiSettings * multi_settings, QSharedMemory *shdmem, + MultiSettings * multi_settings, DecoderIpc::Session& decoderSession, unsigned downSampleFactor, QSplashScreen * splash, QProcessEnvironment const& env, bool automated_test, @@ -669,7 +669,7 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, m_rpt {"-15"}, m_pfx {Radio::PrefixSuffix::type1Prefixes()}, m_sfx {Radio::PrefixSuffix::type1Suffixes()}, - mem_jt9 {shdmem}, + m_decoderSession {decoderSession}, m_downSampleFactor (downSampleFactor), m_audioThreadPriority (QThread::HighPriority), m_bandEdited {false}, @@ -679,12 +679,8 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, m_transmitting {false}, m_tune {false}, m_tx_watchdog {false}, - m_jttyTxActive {false}, - m_jttyTxUsesTciAudio {false}, - m_jttyTxQueueEpoch {}, - m_jttyTxQueueProgress {}, m_jttyTxRequestId {0}, - m_jttyTciEnqueueId {0}, + m_jttyEnqueueId {0}, m_block_pwr_tooltip {false}, m_PwrBandSetOK {true}, m_toneSpacing {0.}, @@ -703,18 +699,59 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, programStart = true; qApp->setFont (m_config.text_font ()); ui->setupUi(this); + updateJttySendButton (); + ui->Tx_Message->setToolTip (tr ("Ctrl+K sends now (one-shot). Alt+J starts a live session that keeps sending as you type, until Alt+K signs off. Ctrl+Shift+K clears the box. Ctrl+H inserts a chat opener.")); + ui->Tx_Message->installEventFilter (this); configureModeControlsLayout (); - connect (ui->Tx_Message, &QLineEdit::textChanged, this, - [this] { m_jttyDraftAcceptanceTracker.noteDraftChanged (); }); - connect (this, &MainWindow::jttyTextAccepted, this, [this] (qint64 requestId) { - if (m_jttyDraftAcceptanceTracker.accept (requestId)) { - ui->Tx_Message->clear (); + // A non-editable QComboBox always left-aligns its closed-box text, so fake a + // centered "label" via a read-only editable line edit; the dropdown list's + // own item text needs its alignment set separately (item textAlignment isn't + // a supported .ui property for QComboBox the way it is for list/table items). + ui->comboBoxJttyStyle->setEditable (true); + ui->comboBoxJttyStyle->lineEdit ()->setReadOnly (true); + ui->comboBoxJttyStyle->lineEdit ()->setAlignment (Qt::AlignCenter); + for (int i = 0; i < ui->comboBoxJttyStyle->count (); ++i) { + ui->comboBoxJttyStyle->setItemData (i, Qt::AlignCenter, Qt::TextAlignmentRole); + } + connect (ui->Tx_Message, &QPlainTextEdit::textChanged, this, + &MainWindow::guardJttyLiveEntryLock); + connect (ui->Tx_Message, &QPlainTextEdit::textChanged, this, + &MainWindow::autoAdvanceJttyLiveEntry); + connect (ui->Tx_Message, &QPlainTextEdit::textChanged, this, + &MainWindow::updateJttyLiveEntryFrameLabel); + m_jttyAutoAdvanceIdleTimer.setSingleShot (true); + connect (&m_jttyAutoAdvanceIdleTimer, &QTimer::timeout, this, + &MainWindow::idleFlushJttyLiveEntry); + // Acceptance leaves the span in m_jttyLiveEntryPending; only jttyTextCompleted (below) removes it. + connect (this, &MainWindow::jttyTextCompleted, this, [this] (qint64 requestId) { + for (int i = 0; i < m_jttyLiveEntryPending.size (); ++i) { + if (m_jttyLiveEntryPending[i].requestId == requestId) { + m_jttyLiveEntryFramesSent += m_jttyLiveEntryPending[i].totalFrames; + m_jttyLiveEntryPending.remove (i); + m_guardingJttyLiveEntryLock = true; + applyJttyLiveEntryFormatting (); + m_guardingJttyLiveEntryLock = false; + updateJttyLiveEntryFrameLabel (); + break; + } } }); connect (this, &MainWindow::jttyTextRejected, this, [this] (qint64 requestId, JttyTxRejectReason) { - m_jttyDraftAcceptanceTracker.reject (requestId); - }); + for (int i = 0; i < m_jttyLiveEntryPending.size (); ++i) { + if (m_jttyLiveEntryPending[i].requestId != requestId) continue; + auto const entry = m_jttyLiveEntryPending[i]; + m_jttyLiveEntryPending.remove (i); + // Only the most recently committed span can be cleanly reopened for editing. + if (entry.end == m_jttyLiveEntryCommitted) { + m_guardingJttyLiveEntryLock = true; + m_jttyLiveEntryCommitted = entry.start; + applyJttyLiveEntryFormatting (); + m_guardingJttyLiveEntryLock = false; + } + break; + } + }); m_tx_message_button_group = new QButtonGroup {this}; m_tx_message_button_group->addButton (ui->txrb1, 1); m_tx_message_button_group->addButton (ui->txrb2, 2); @@ -829,7 +866,16 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, connect (m_jttyTxStream, &JttyTxStream::txSourceCommitted, this, &MainWindow::recordTxSourceCommit, Qt::QueuedConnection); connect (this, &MainWindow::endJttyStream, m_jttyTxStream, &JttyTxStream::stop); + connect (this, &MainWindow::clearJttyStream, m_jttyTxStream, + &JttyTxStream::clearQueue, Qt::QueuedConnection); + connect (this, &MainWindow::enqueueJttyStream, m_jttyTxStream, + &JttyTxStream::queuePcm, Qt::DirectConnection); + connect (m_jttyTxStream, &JttyTxStream::enqueueAccepted, this, + &MainWindow::onJttyBackendEnqueueAccepted, Qt::QueuedConnection); + connect (m_jttyTxStream, &JttyTxStream::enqueueFailed, this, + &MainWindow::onJttyBackendEnqueueFailed, Qt::QueuedConnection); connect (m_jttyTxStream, &JttyTxStream::drained, this, &MainWindow::onJttyBackendDrained); + connect (m_jttyTxStream, &JttyTxStream::progress, this, &MainWindow::onJttyBackendProgress); connect (&m_audioThread, &QThread::finished, m_jttyTxStream, &QObject::deleteLater); // hook up the audio input stream signals, slots and disposal @@ -890,7 +936,11 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, #endif continue; } - if (previousEpoch != m_receiveConsumer.epoch ()) m_referenceInput.reset (); + if (previousEpoch != m_receiveConsumer.epoch ()) + { + m_referenceInput.reset (); + beginDecoderInput (); + } auto const frames = block->end (); #if defined (WSJT_ENABLE_LIVE_AUDIO_TEST) if (m_automated_test) @@ -917,12 +967,17 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, if (!m_tci_audio) live_data_sink (std::move (audio)); }); connect (&m_audioThread, &QThread::finished, m_detector, &QObject::deleteLater); + connect(m_detector, &Detector::continuousAudioAvailable, this, + [this](JttyReceiveMailboxPtr mailbox) { + consumeJttyAudio(std::move(mailbox)); + }); // setup the waterfall connect(m_wideGraph.data (), SIGNAL(freezeDecode2(int)),this,SLOT(freezeDecode(int))); connect(m_wideGraph.data (), SIGNAL(f11f12(int)),this,SLOT(bumpFqso(int))); connect(m_wideGraph.data (), SIGNAL(setXIT2(int)),this,SLOT(setXIT(int))); - connect(m_wideGraph.data (), SIGNAL(jttyDecodeAgainAt2(float)),this,SLOT(jttyDecodeAgainAt(float))); + connect(m_wideGraph.data(), &WideGraph::jttyDecodeAgainAtSample, + this, &MainWindow::jttyDecodeAgainAtSample); m_wideGraph->setReferenceSpectrumAvailable( QFile::exists(m_config.writeable_data_dir ().absoluteFilePath ("refspec.dat"))); @@ -1170,28 +1225,18 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, m_startup_decoder_reported = true; PerformanceTrace::milestone (m_startup_trace_run, "decoder.process_started"); } - if (Jt9ProcessPhase::InitialStarting == m_jt9ProcessPhase - || Jt9ProcessPhase::ReplacementStarting == m_jt9ProcessPhase) - { - m_decoderStartTimer.stop (); - m_decoderCompletedSinceStart = false; - m_jt9ProcessPhase = Jt9ProcessPhase::Ready; - updateDecodeControls (); - QTimer::singleShot (0, this, [this] { - auto const pendingResult = publishPendingFt8Decode (); - if (DecodePublishResult::Failed == pendingResult) - { - requestDecoderRestart ( - "pending FT8 decode publication failed after restart"); - } - }); - } }); connect(&proc_jt9, &QProcess::readyReadStandardOutput, this, &MainWindow::readFromStdout); - connect(&proc_jt9, &QProcess::started, this, &MainWindow::decoderBackendStarted); #if QT_VERSION < QT_VERSION_CHECK (5, 6, 0) connect(&proc_jt9, static_cast<void (QProcess::*) (QProcess::ProcessError)> (&QProcess::error), [this] (QProcess::ProcessError error) { + if (m_closing || !m_valid) return; + if (Jt9ProcessPhase::InitialStarting == m_jt9ProcessPhase + || Jt9ProcessPhase::ReplacementStarting == m_jt9ProcessPhase) + { + failDecoderStartup (proc_jt9.errorString ()); + return; + } if ((Jt9ProcessPhase::StopRequested == m_jt9ProcessPhase || Jt9ProcessPhase::Terminating == m_jt9ProcessPhase || Jt9ProcessPhase::Killing == m_jt9ProcessPhase) @@ -1201,6 +1246,13 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, }); #else connect(&proc_jt9, &QProcess::errorOccurred, [this] (QProcess::ProcessError error) { + if (m_closing || !m_valid) return; + if (Jt9ProcessPhase::InitialStarting == m_jt9ProcessPhase + || Jt9ProcessPhase::ReplacementStarting == m_jt9ProcessPhase) + { + failDecoderStartup (proc_jt9.errorString ()); + return; + } if ((Jt9ProcessPhase::StopRequested == m_jt9ProcessPhase || Jt9ProcessPhase::Terminating == m_jt9ProcessPhase || Jt9ProcessPhase::Killing == m_jt9ProcessPhase) @@ -1211,7 +1263,15 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, #endif connect(&proc_jt9, static_cast<void (QProcess::*) (int, QProcess::ExitStatus)> (&QProcess::finished), [this] (int exitCode, QProcess::ExitStatus status) { - if (m_closing) return; + if (m_closing || !m_valid) return; + if (Jt9ProcessPhase::InitialStarting == m_jt9ProcessPhase + || Jt9ProcessPhase::ReplacementStarting == m_jt9ProcessPhase) + { + readFromStdout (); + failDecoderStartup (tr ("The decoder exited before completing its startup handshake (code %1).") + .arg (exitCode)); + return; + } if (decoderRestartInProgress ()) { m_decoderShutdownTimer.stop (); @@ -1226,7 +1286,6 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, QTimer::singleShot (0, this, SLOT (close ())); return; } - m_jt9PayloadValid = false; m_activeJt9Decode = {}; m_decoderOutputFramer.reset (); startDecoderProcess (); @@ -1346,11 +1405,16 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, if (m_tci_audio) live_data_sink (std::move (audio)); }); connect (&m_config, &Configuration::transceiver_TCImodActive, this, &MainWindow::tci_mod_active); + connect(&m_config, &Configuration::continuousAudioAvailable, this, + [this](JttyReceiveMailboxPtr mailbox) { + consumeJttyAudio(std::move(mailbox)); + }); connect (&m_config, &Configuration::txSourceCommitted, this, &MainWindow::recordTxSourceCommit, Qt::QueuedConnection); connect (&m_config, &Configuration::rawTxPlayoutSnapshot, this, &MainWindow::recordRawTxPlayout, Qt::QueuedConnection); connect (&m_config, &Configuration::transceiver_jtty_drained, this, &MainWindow::onJttyBackendDrained); + connect (&m_config, &Configuration::transceiver_jtty_progress, this, &MainWindow::onJttyBackendProgress); connect (&m_config, &Configuration::transceiver_jtty_enqueue_accepted, this, &MainWindow::onJttyBackendEnqueueAccepted); connect (&m_config, &Configuration::transceiver_jtty_enqueue_failed, this, &MainWindow::onJttyBackendEnqueueFailed); connect (&m_config, &Configuration::transceiver_closing, this, &MainWindow::handle_transceiver_closing); @@ -1433,12 +1497,14 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, }); m_decoderStartTimer.setSingleShot (true); connect (&m_decoderStartTimer, &QTimer::timeout, this, [this] { - if (Jt9ProcessPhase::ReplacementStarting != m_jt9ProcessPhase - || QProcess::Running == proc_jt9.state ()) return; - MessageBox::critical_message (this, tr ("Decoder Error"), - tr ("The decoder subprocess could not be restarted.")); - m_valid = false; - QTimer::singleShot (0, this, SLOT (close ())); + if (Jt9ProcessPhase::InitialStarting != m_jt9ProcessPhase + && Jt9ProcessPhase::ReplacementStarting != m_jt9ProcessPhase) return; + // A GUI stall can delay stdout notification past the handshake deadline. + proc_jt9.waitForReadyRead (0); + if (proc_jt9.bytesAvailable ()) readFromStdout (); + if (Jt9ProcessPhase::InitialStarting != m_jt9ProcessPhase + && Jt9ProcessPhase::ReplacementStarting != m_jt9ProcessPhase) return; + failDecoderStartup (tr ("The decoder did not complete its startup handshake within five seconds.")); }); stopWRTimer.setSingleShot(true); @@ -1455,6 +1521,14 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, m_jttyTxWatchdog.setSingleShot(true); connect(&m_jttyTxWatchdog, &QTimer::timeout, this, &MainWindow::handleJttyTxWatchdog); + m_jttyEnqueueWatchdog.setSingleShot (true); + connect (&m_jttyEnqueueWatchdog, &QTimer::timeout, + this, &MainWindow::handleJttyEnqueueTimeout); +#ifdef WIN32 + m_mmttyHandoffWatchdog.setSingleShot (true); + connect (&m_mmttyHandoffWatchdog, &QTimer::timeout, + this, &MainWindow::handleMmttyHandoffTimeout); +#endif m_refSpecTimer.setInterval(1000); connect(&m_refSpecTimer, &QTimer::timeout, this, &MainWindow::updateReferenceSpectrumCountdown); @@ -2475,6 +2549,10 @@ void MainWindow::fixStop() //-------------------------------------------------------------- dataSink() void MainWindow::dataSink(qint64 frames) { + if (m_mode == "JTTY") { + if (m_diskData) decodeJttyDisk(int(frames)); + return; + } static float s[NSMAX]; char line[80]; int k(frames); @@ -2508,7 +2586,6 @@ void MainWindow::dataSink(qint64 frames) if(m_bFastMode) return; } - if(m_mode=="JTTY") fastSink(frames); // Get power, spectrum, and ihsym dec_data.params.nfa=m_wideGraph->nStartFreq(); @@ -2532,14 +2609,6 @@ void MainWindow::dataSink(qint64 frames) m_wideGraph->dataSink2(s,m_df3,m_ihsym,m_diskData,m_px); } if(m_mode=="MSK144") return; - if(m_mode=="JTTY") { - if(m_ihsym >= m_hsymStop and (m_saveAll or m_saveDecoded)) { - monitor(false); - jtty_save_wav(); - if(!m_diskData) monitor(true); - } - return; - } fixStop(); if (m_mode == "FreqCal" @@ -2909,24 +2978,6 @@ void MainWindow::fastSink(qint64 frames) ui->signal_meter_widget->setValue(rmsNoGain,pxmax); // Update thermometer m_fastGraph->plotSpec(m_diskData,m_UTCdisk); - if(m_mode=="JTTY") { - jtty_decode(k); -#if defined (WSJT_ENABLE_LIVE_AUDIO_TEST) - if (m_automated_test) - { - Q_EMIT liveAudioTestJttyFramesConsumed (k); - } -#endif - int detectorFrames = dec_data.params.kin; - if (!m_diskData) - { - QMutexLocker lock {&dec_data_mutex ()}; - detectorFrames = m_activeReceiveAudio - ? m_activeReceiveAudio->sourceFrames () : k; - } - if(detectorFrames - k < 10240) fast_decode_done(); - return; - } if(bmsk144 and (line[0]!=0)) { QString message {QString::fromLatin1 (line)}; @@ -3502,6 +3553,15 @@ void MainWindow::on_actionSettings_triggered() // Setup Dialog (Settin void MainWindow::monitor (bool state) { + if (state && jttyDrainInProgress()) return; + bool const leavingDiskData = state && m_diskData; + if (state && !m_monitoring && m_mode == "JTTY") updateJttyReceiveContext(); + if (!state && m_mode == "JTTY") { + auto const reason = m_jttyTxLifecycle.active () ? JttyReceiveReason::Transmission + : JttyReceiveReason::MonitorStopped; + m_detector->setInputStopReason(reason); + m_config.transceiver_receive_stop_reason(reason); + } ui->monitorButton->setChecked (state); if (state) { m_diskData = false; // no longer reading WAV files @@ -3547,6 +3607,7 @@ void MainWindow::monitor (bool state) } m_monitoring = state; if (!state) cancelPendingFt8Decode ("monitoring stopped"); + if (leavingDiskData) updateDecodeControls (); check_button_color(); } @@ -4127,6 +4188,50 @@ bool MainWindow::eventFilter (QObject * object, QEvent * event) } auto const key_event = static_cast<QKeyEvent *> (event); + if (object == ui->Tx_Message && !key_event->isAutoRepeat () + && key_event->key () == Qt::Key_K + && key_event->modifiers () == (Qt::ControlModifier | Qt::ShiftModifier)) + { + clearJttyLiveEntry (); + return true; + } + if (object == ui->Tx_Message && !key_event->isAutoRepeat () + && key_event->key () == Qt::Key_K + && key_event->modifiers () == Qt::ControlModifier) + { + commitJttyLiveEntry (); + return true; + } + // Alt+J: start/continue the live session (pairs with Alt+K to end it, Alt+H/Esc to stop immediately). + if (object == ui->Tx_Message && !key_event->isAutoRepeat () + && key_event->key () == Qt::Key_J + && key_event->modifiers () == Qt::AltModifier) + { + startJttyLiveStream (); + return true; + } + if (object == ui->Tx_Message && !key_event->isAutoRepeat () + && key_event->key () == Qt::Key_K + && key_event->modifiers () == Qt::AltModifier) + { + insertJttyChatSignoff (); + return true; + } + if (object == ui->Tx_Message && !key_event->isAutoRepeat () + && key_event->key () == Qt::Key_H + && key_event->modifiers () == Qt::ControlModifier) + { + insertJttyChatOpener (); + return true; + } + // An undo reaching into locked text can't be fixed by guardJttyLiveEntryLock's own undo() (wrong direction), so block the shortcuts outright while anything is locked. + if (object == ui->Tx_Message && !key_event->isAutoRepeat () + && m_jttyLiveEntryCommitted > 0 + && (key_event->matches (QKeySequence::Undo) + || key_event->matches (QKeySequence::Redo))) + { + return true; + } auto const handled = switchMainWindowTab (key_event) || switchTxNextMessage (key_event); tx_watchdog (false); if (handled) return true; @@ -4209,10 +4314,17 @@ void MainWindow::createStatusBar() //createStatusBar last_tx_label.setFrameStyle (QFrame::Panel | QFrame::Sunken); statusBar()->addWidget (&last_tx_label); - if (m_config.PWR_and_SWR()) statusBar ()->addPermanentWidget (&band_hopping_label); band_hopping_label.setAlignment (Qt::AlignHCenter); band_hopping_label.setMinimumSize (QSize {80, 18}); band_hopping_label.setFrameStyle (QFrame::Panel | QFrame::Sunken); + statusBar ()->addWidget (&band_hopping_label); + band_hopping_label.setVisible (m_mode == "WSPR"); + + swr_label.setAlignment (Qt::AlignHCenter); + swr_label.setMinimumSize (QSize {80, 18}); + swr_label.setFrameStyle (QFrame::Panel | QFrame::Sunken); + statusBar ()->addPermanentWidget (&swr_label); + swr_label.setVisible (m_config.PWR_and_SWR () && m_mode != "Echo"); statusBar()->addPermanentWidget(&progressBar); progressBar.setMinimumSize (QSize {150, 18}); @@ -4228,7 +4340,8 @@ void MainWindow::createStatusBar() //createStatusBar mode_label.setAccessibleName (tr ("Mode")); ndecodes_label.setAccessibleName (tr ("Decode count")); last_tx_label.setAccessibleName (tr ("Last transmitted message")); - band_hopping_label.setAccessibleName (tr ("Power and SWR status")); + band_hopping_label.setAccessibleName (tr ("WSPR band-hopping period")); + swr_label.setAccessibleName (tr ("SWR status")); progressBar.setAccessibleName (tr ("Decode progress")); progressBar.setAccessibleDescription (tr ("Progress for the current decode operation.")); watchdog_label.setAccessibleName (tr ("Transmit watchdog")); @@ -4341,18 +4454,11 @@ void MainWindow::setup_status_bar (bool vhf) } keep_last_tx_label = true; last_tx_label.setText (QString {}); - if (m_mode.contains (QRegularExpression {R"(^(Echo))"})) { - if (band_hopping_label.isVisible ()) statusBar ()->removeWidget (&band_hopping_label); - } else if (m_mode=="WSPR") { + if (m_mode == "WSPR") { mode_label.setStyleSheet ("QLabel{color: #000000; background-color: #ff66ff}"); - if (!band_hopping_label.isVisible ()) { - statusBar ()->addWidget (&band_hopping_label); - band_hopping_label.show (); - band_hopping_label.setMinimumSize (QSize {80, 18}); - } - } else { - if (!m_config.PWR_and_SWR () && band_hopping_label.isVisible ()) statusBar ()->removeWidget (&band_hopping_label); } + band_hopping_label.setVisible (m_mode == "WSPR"); + updateRigMeters (m_rigState); } @@ -4368,6 +4474,10 @@ void MainWindow::paintEvent (QPaintEvent * event) void MainWindow::closeEvent(QCloseEvent * e) { + if (jttyDrainInProgress()) { closeAfterJttyDrain(); e->ignore(); return; } + if (m_closing) { e->accept(); return; } + m_closing = true; + drainJttyReceive(); auto const active_run = PerformanceTrace::current_run (); if (active_run == m_startup_trace_run) { @@ -4412,7 +4522,7 @@ void MainWindow::closeEvent(QCloseEvent * e) m_shortcuts.reset (); m_mouseCmnds.reset (); m_colorHighlighting.reset (); - if(m_mode!="MSK144" and m_mode!="FT8") killWaveFile(); + if(m_mode!="MSK144" and m_mode!="FT8" and m_mode!="JTTY") killWaveFile(); float sw=0.0; int nw=400; int nh=100; @@ -4420,12 +4530,7 @@ void MainWindow::closeEvent(QCloseEvent * e) plotsave_(&sw,&nw,&nh,&irow); { PerformanceTrace::Phase decoder_shutdown {"decoder.shutdown"}; - if (DecoderIpc::hasUsableSize (mem_jt9->size ()) - && mem_jt9->data ()) - { - auto * shared = reinterpret_cast<shared_dec_data_t *> (mem_jt9->data ()); - DecoderIpc::shutdown (*shared); - } + m_decoderSession.shutdown (); if (proc_jt9.state() != QProcess::NotRunning) { if (!proc_jt9.waitForFinished(5000)) { proc_jt9.terminate(); @@ -4437,7 +4542,7 @@ void MainWindow::closeEvent(QCloseEvent * e) } proc_jt9.close(); } - mem_jt9->detach(); + m_decoderSession.detach (); Q_EMIT finished (); QMainWindow::closeEvent (e); close.finish (); @@ -4447,7 +4552,7 @@ void MainWindow::closeEvent(QCloseEvent * e) void MainWindow::on_actionRelease_Notes_triggered () { - QDesktopServices::openUrl (QUrl {"https://wsjt.sourceforge.io/Release_Notes.txt"}); + QDesktopServices::openUrl (QUrl {"https://wsjtx.github.io/wsjtx/Release_Notes.txt"}); } void MainWindow::on_actionFT8_DXpedition_Mode_User_Guide_triggered() @@ -4861,6 +4966,7 @@ void MainWindow::on_actionOpen_triggered() //Open File void MainWindow::read_wav_file (QString const& fname) { + if (jttyDrainInProgress()) return; if (m_wav_load_coordinator.isLoading ()) return; if (m_mode=="FT8" && (m_multithreadFT8 or m_operatingFrequency.rx ()>45000000)) { @@ -4920,6 +5026,7 @@ void MainWindow::read_wav_file (QString const& fname) void MainWindow::wav_file_loaded () { + if (m_discardJttyWavLoad || jttyDrainInProgress()) { m_discardJttyWavLoad = false; return; } if (!m_valid) return; auto const result=m_wav_load_coordinator.result (); @@ -4940,7 +5047,17 @@ void MainWindow::wav_file_loaded () dec_data.params.newdat=0; } } + m_dataAvailable = result->valid && result->frames > 0; + if (result->valid) { + beginDecoderInput (); + // Opening another file supersedes retained audio even if monitoring resumes before decoding. + if (!decoderBusy ()) m_decoderSession.abort (); + } m_fileDateTime=result->fileDateTime; + if (m_mode == "JTTY") { + if (result->firstSampleUtc.isValid()) m_UTCdiskDateTime = result->firstSampleUtc; + beginJttyDisk(); + } diskDat (); if (!m_valid) return; } @@ -5005,6 +5122,16 @@ void MainWindow::diskDat() //diskDat() float db=m_config.degrade(); float bw=m_config.RxBandwidth(); if(db > 0.0) degrade_snr_(dec_data.d2,&dec_data.params.kin,&db,&bw); + if (m_mode == "JTTY") { + for (int first = 0; first < dec_data.params.kin; first += kstep) { + dataSink(std::min(first + kstep, dec_data.params.kin)); + qApp->processEvents(QEventLoop::ExcludeUserInputEvents); + if (!m_valid || m_mode != "JTTY" || !m_diskData || !jttyDiskActive()) { finishJttyDisk(); return; } + } + finishJttyDisk(); + finishDecodeUi(); + return; + } for(int n=1; n<=m_hsymStop; n++) { // Do the waterfall spectra k=n*kstep; if(k > dec_data.params.kin) break; @@ -5049,6 +5176,7 @@ void MainWindow::on_actionNone_triggered() //Save None m_saveDecoded=false; m_saveAll=false; ui->actionNone->setChecked(true); + updateJttySavePolicy(); } void MainWindow::on_actionSave_decoded_triggered() @@ -5056,6 +5184,7 @@ void MainWindow::on_actionSave_decoded_triggered() m_saveDecoded=true; m_saveAll=false; ui->actionSave_decoded->setChecked(true); + updateJttySavePolicy(); } void MainWindow::on_actionSave_all_triggered() //Save All @@ -5063,6 +5192,7 @@ void MainWindow::on_actionSave_all_triggered() //Save All m_saveDecoded=false; m_saveAll=true; ui->actionSave_all->setChecked(true); + updateJttySavePolicy(); } void MainWindow::on_actionKeyboard_shortcuts_triggered() @@ -5148,7 +5278,33 @@ void MainWindow::decode (Ft8MtdDecodeCoordinator::Stage ft8Stage, showStatusMessage (tr ("Decoder is starting; decode request skipped.")); return; } - if (usesJt9Process () && !dec_data.params.newdat && !m_jt9PayloadValid) + if (!m_dataAvailable || m_TRperiod == 0.0) + { + ui->DecodeButton->setChecked (false); + return; + } + if (usesJt9Process () && m_diskData + && m_decoderInput.inputId () != m_decoderSession.completedSnapshot ().metadata.input_id) + { + dec_data.params.newdat = true; + dec_data.params.nagain = false; + } + if (m_mode == "FST4W" && !m_diskData && !dec_data.params.newdat) + { + ui->DecodeButton->setChecked (false); + showStatusMessage (tr ("FST4W manual decoding is available only for WAV files.")); + return; + } + int const retainedMode = m_mode == "Q65" ? 66 : m_mode == "FST4" ? 240 + : m_mode == "FST4W" ? 241 : 0; + if (retainedMode && !dec_data.params.newdat + && !m_decoderSession.canReuseSamples (retainedMode, int (m_TRperiod))) + { + ui->DecodeButton->setChecked (false); + showStatusMessage (tr ("No completed %1 reception is available to decode again.").arg (m_mode)); + return; + } + if (usesJt9Process () && !dec_data.params.newdat && !m_decoderSession.samples ()) { dec_data.params.newdat = true; dec_data.params.nagain = false; @@ -5167,9 +5323,9 @@ void MainWindow::decode (Ft8MtdDecodeCoordinator::Stage ft8Stage, } else { dec_data.params.yymmdd=-1; } - if(!m_dataAvailable or m_TRperiod==0.0) return; ui->DecodeButton->setChecked (true); - if(!dec_data.params.nagain && m_diskData && m_TRperiod >= 60.) { + if(!dec_data.params.nagain && m_diskData && m_TRperiod >= 60. && m_mode != "Q65" + && m_mode != "FST4" && m_mode != "FST4W") { dec_data.params.nutc=dec_data.params.nutc/100; } if(dec_data.params.nagain==0 && dec_data.params.newdat==1 && (!m_diskData)) { @@ -5179,7 +5335,7 @@ void MainWindow::decode (Ft8MtdDecodeCoordinator::Stage ft8Stage, m_dateTimeSeqStart = qt_truncate_date_time_to (QDateTime::currentDateTimeUtc (), m_TRperiod * 1.e3); auto t = m_dateTimeSeqStart.time (); dec_data.params.nutc = t.hour () * 100 + t.minute (); - if (m_TRperiod < 60.) + if (m_TRperiod < 60. || m_mode == "Q65" || m_mode == "FST4" || m_mode == "FST4W") { dec_data.params.nutc = dec_data.params.nutc * 100 + t.second (); } @@ -5262,7 +5418,11 @@ void MainWindow::decode (Ft8MtdDecodeCoordinator::Stage ft8Stage, dec_data.params.nsubmode=m_nSubMode; dec_data.params.minw=0; dec_data.params.nclearave=m_nclearave; - if(m_nclearave!=0) { + if (m_mode == "JT65" && m_jt65ClearAveragesPending) dec_data.params.nclearave=1; + if (m_mode == "Q65") { + dec_data.params.nclearave = m_q65ClearAveragesPending ? 1 : 0; + } + if(dec_data.params.nclearave!=0 && m_mode != "Q65") { QFile f(m_config.temp_dir ().absoluteFilePath ("avemsg.txt")); f.remove(); } @@ -5358,7 +5518,8 @@ void MainWindow::decode (Ft8MtdDecodeCoordinator::Stage ft8Stage, dec_data.params.ntrperiod=int(m_TRperiod); dec_data.params.lwidedxcsearch=m_FT8WideDxCallSearch ? 1 : 0; } - ::memcpy(dec_data.params.datetime, m_dateTime.toLatin1()+" ", sizeof dec_data.params.datetime); + auto const dateTime = m_dateTime.toLatin1().leftJustified (sizeof dec_data.params.datetime, ' ', true); + ::memcpy(dec_data.params.datetime, dateTime.constData (), sizeof dec_data.params.datetime); ::memcpy(dec_data.params.mycall, (m_config.my_callsign()+" ").toLatin1(),12); ::memcpy(dec_data.params.mybcall, (Radio::base_callsign(m_config.my_callsign())+" ").toLatin1(),12); @@ -5428,6 +5589,11 @@ void MainWindow::decode (Ft8MtdDecodeCoordinator::Stage ft8Stage, auto const publishResult = publishDecodeRequest ( decoderParams.newdat, ft8Stage, ft8Period); + if (DecodePublishResult::Published == publishResult && m_mode == "JT65") + m_jt65ClearAveragesPending = false; + if (DecodePublishResult::Published == publishResult && m_mode == "Q65") { + m_q65ClearAveragesPending = false; + } if (DecodePublishResult::Published == publishResult && scheduledFt8) { if (m_ft8MtdDecodeCoordinator.published (ft8Stage, ft8Period)) @@ -5462,6 +5628,27 @@ void MainWindow::decode (Ft8MtdDecodeCoordinator::Stage ft8Stage, } #if defined (WSJT_ENABLE_LIVE_AUDIO_TEST) +bool MainWindow::startWavDecodeTest (QString const& path) +{ + auto const fixtureMode = ((m_mode == QStringLiteral ("JT4") + || m_mode == QStringLiteral ("JT9") + || m_mode == QStringLiteral ("JT65") + || m_mode == QStringLiteral ("Q65")) && m_TRperiod == 60.0) + || (m_mode == QStringLiteral ("FST4") && m_TRperiod == 15.0) + || (m_mode == QStringLiteral ("FST4W") && m_TRperiod == 120.0); + if (!m_automated_test || !m_config.is_dummy_rig () + || !fixtureMode || m_nSubMode != 0 || m_bFast9 || m_bFastMode + || decoderBusy () || !decoderBackendRunning () + || !ui->actionOpen->isEnabled () || m_wav_load_coordinator.isLoading ()) + return false; + monitor (false); + m_path = path; + m_diskData = true; + on_stopButton_clicked (); + read_wav_file (path); + return true; +} + bool MainWindow::configureLiveAudioTestDecodeRange () { // FT8's 1500/2048 Hz bins make 956 pixels at 4 bins/pixel span 200-3000 Hz. @@ -5584,20 +5771,7 @@ MainWindow::startLiveAudioTestFt8Transmit (qint64 targetPeriodStartMs) QString MainWindow::liveAudioTestFt8BackpressureDiagnostics () const { - qint32 ipcState {-1}; - qint32 ipcGeneration {-1}; - qint32 ipcProgress {-1}; - if (DecoderIpc::hasUsableSize (mem_jt9->size ()) && mem_jt9->data ()) - { - auto const * shared = reinterpret_cast<shared_dec_data_t const *> ( - mem_jt9->constData ()); - if (DECODER_IPC_VERSION == DecoderIpc::protocolVersion (*shared)) - { - ipcState = DecoderIpc::state (*shared); - ipcGeneration = DecoderIpc::generation (*shared); - ipcProgress = DecoderIpc::progress (*shared); - } - } + auto const ipc = m_decoderSession.diagnostics (); return QString {"degraded=%1 pending_final=%2 backoff_periods=%3 " "next_probe_period=%4 owner=%5 process_phase=%6 " @@ -5611,9 +5785,9 @@ QString MainWindow::liveAudioTestFt8BackpressureDiagnostics () const .arg (static_cast<int> (m_decodeOwner)) .arg (static_cast<int> (m_jt9ProcessPhase)) .arg (m_activeJt9Decode.generation) - .arg (ipcState) - .arg (ipcGeneration) - .arg (ipcProgress) + .arg (ipc.state) + .arg (ipc.generation) + .arg (ipc.progress) .arg (decoderDiagnosticElapsedMs ()) .arg (decoderDiagnosticIdleMs ()); } @@ -5625,7 +5799,6 @@ void::MainWindow::fast_decode_done() float t,tmax=-99.0; dec_data.params.nagain=false; dec_data.params.ndiskdat=false; - if(m_mode=="JTTY" && m_diskData) flushJttyDecodeLines(); for(int i=0; i<100 && m_msg[i][0]; i++) { QString message=QString::fromLatin1(m_msg[i], 80); m_msg[i][0]=0; @@ -5671,8 +5844,10 @@ void MainWindow::startDecoderProcess () : Jt9ProcessPhase::InitialStarting; m_activeJt9Decode = {}; m_decoderOutputFramer.reset (); + m_decoderSession.beginStartup (); QStringList jt9Args { - "-s", QApplication::applicationName (), // shared memory key, includes rig + "-s", m_decoderSession.name (), + "--ipc-lock", m_decoderSession.workerLockPath (), "-w", "1", // FFTW planning patience // The number of threads for FFTW specified here is chosen as // three because that gives the best throughput of the large @@ -5693,27 +5868,36 @@ void MainWindow::startDecoderProcess () proc_jt9.setProcessEnvironment (environment); proc_jt9.start (QDir::toNativeSeparators (QDir {m_appDir}.filePath ("jt9")), jt9Args, QIODevice::ReadWrite | QIODevice::Unbuffered); - if (replacement) m_decoderStartTimer.start (5000); + m_decoderStartTimer.start (5000); + updateDecodeControls (); +} + +void MainWindow::failDecoderStartup (QString const& reason) +{ + if (m_closing || Jt9ProcessPhase::Failed == m_jt9ProcessPhase) return; + m_decoderStartTimer.stop (); + m_jt9ProcessPhase = Jt9ProcessPhase::Failed; + m_decoderSession.beginStartup (); + m_valid = false; updateDecodeControls (); + qCritical () << "Decoder startup failed:" << reason; + Q_EMIT decoderBackendFailed (reason); + QTimer::singleShot (0, this, SLOT (close ())); + if (!m_automated_test) + MessageBox::critical_message (this, tr ("Decoder Error"), reason); } bool MainWindow::initializeDecoderSharedMemory () { - if (!DecoderIpc::hasUsableSize (mem_jt9->size ()) - || !mem_jt9->data ()) - { - return false; - } - auto * shared = reinterpret_cast<shared_dec_data_t *> (mem_jt9->data ()); - DecoderIpc::initialize (*shared); - return true; + return m_decoderSession.reset (); } DecodeOperatingContext MainWindow::currentDecodeOperatingContext () const { - auto const periodFrequency = m_freqNominalPeriod ? m_freqNominalPeriod - : m_operatingFrequency.rx (); - auto const periodBand = m_currentBandPeriod.isEmpty () + // WAV input is independent of the live period retained across a dial change. + auto const periodFrequency = !m_diskData && m_freqNominalPeriod ? m_freqNominalPeriod + : m_operatingFrequency.rx (); + auto const periodBand = m_diskData || m_currentBandPeriod.isEmpty () ? m_config.bands ()->find (periodFrequency) : m_currentBandPeriod; DecodeOperatingContext context; context.mode = m_mode; @@ -5721,6 +5905,8 @@ DecodeOperatingContext MainWindow::currentDecodeOperatingContext () const context.periodFrequency = periodFrequency; context.band = periodBand; context.sequenceStart = m_dateTimeSeqStart; + context.inputId = m_decoderInput.inputId (); + context.analysisId = m_decoderInput.analysisId (); context.trPeriod = m_TRperiod; context.submode = m_nSubMode; context.diskData = m_diskData; @@ -5770,6 +5956,11 @@ qint64 MainWindow::currentFt8DecodePeriod () const return QDateTime::currentMSecsSinceEpoch () / periodMs; } +void MainWindow::beginDecoderInput () +{ + m_decoderInput.beginInput (); +} + bool MainWindow::usesFt8MtdFinal () const { auto const standardFinalRequired = @@ -5788,19 +5979,23 @@ int MainWindow::configuredFt8MtdEarlyStageCount () const } std::unique_ptr<Ft8MtdDecodeCoordinator::PendingMtdDecode> -MainWindow::capturePendingFt8MtdDecode (qint64 period) const +MainWindow::capturePendingFt8MtdDecode (qint64 period) { auto pending = std::make_unique<Ft8MtdDecodeCoordinator::PendingMtdDecode> (); pending->period = period; - pending->context = currentDecodeOperatingContext (); { QMutexLocker payloadLock {&dec_data_mutex ()}; pending->payload.params = dec_data.params; + pending->payload.metadata = m_decoderInput.nextMetadata (dec_data.params); + pending->payload.metadata.valid_samples = std::min ( + pending->payload.metadata.valid_samples, + static_cast<qint32> (DecoderIpc::Ft8SampleCount)); Q_ASSERT (8 == pending->payload.params.nmode); Q_ASSERT (pending->payload.params.lmultift8); std::copy_n (dec_data.d2, DecoderIpc::Ft8SampleCount, pending->payload.samples.begin ()); } + pending->context = currentDecodeOperatingContext (); return pending; } @@ -5855,9 +6050,7 @@ MainWindow::DecodePublishResult MainWindow::publishDecodeRequest ( { return DecodePublishResult::Unavailable; } - if ((!copySamples && !m_jt9PayloadValid) - || !DecoderIpc::hasUsableSize (mem_jt9->size ()) - || !mem_jt9->data ()) + if (!copySamples && !m_decoderSession.samples ()) { return DecodePublishResult::Failed; } @@ -5868,24 +6061,25 @@ MainWindow::DecodePublishResult MainWindow::publishDecodeRequest ( m_currentBandPeriod = m_config.bands ()->find (m_operatingFrequency.rx ()); } - auto const generation = DecoderIpc::nextGeneration (m_nextDecoderGeneration); if (!beginDecode (DecodeOwner::Jt9)) { return DecodePublishResult::Failed; } m_activeJt9Decode = {}; - m_activeJt9Decode.generation = generation; m_activeJt9Decode.context = currentDecodeOperatingContext (); - m_activeJt9Decode.copiedSamples = copySamples; m_activeJt9Decode.ft8Stage = ft8Stage; m_activeJt9Decode.ft8Period = ft8Period; - bool published {false}; + DecoderIpc::Submission submitted; { QMutexLocker payloadLock {&dec_data_mutex ()}; - auto * shared = reinterpret_cast<shared_dec_data_t *> (mem_jt9->data ()); - published = DecoderIpc::publish (*shared, dec_data, copySamples, generation); - } - if (!published) + auto inputs = m_decoderInput; + auto const request = m_decoderSession.prepareRequest (dec_data, copySamples, inputs); + submitted = m_decoderSession.submit (request); + if (submitted) m_decoderInput = inputs; + m_activeJt9Decode.context.inputId = request.metadata ().input_id; + m_activeJt9Decode.context.analysisId = request.metadata ().analysis_id; + } + if (!submitted) { logDecoderAbnormalClear ("decode publication failed"); m_activeJt9Decode = {}; @@ -5893,7 +6087,7 @@ MainWindow::DecodePublishResult MainWindow::publishDecodeRequest ( return DecodePublishResult::Failed; } - m_nextDecoderGeneration = generation; + m_activeJt9Decode.generation = submitted.generation.value (); return DecodePublishResult::Published; } @@ -5913,27 +6107,18 @@ MainWindow::DecodePublishResult MainWindow::publishPendingFt8Decode () { return PendingPublishResult::Unavailable; } - if (!DecoderIpc::hasUsableSize (mem_jt9->size ()) || !mem_jt9->data ()) - { - return PendingPublishResult::Failed; - } - - auto const generation = DecoderIpc::nextGeneration ( - m_nextDecoderGeneration); if (!beginDecode (DecodeOwner::Jt9, &pending.payload.params, &pending.context)) { return PendingPublishResult::Unavailable; } m_activeJt9Decode = {}; - m_activeJt9Decode.generation = generation; m_activeJt9Decode.context = pending.context; - m_activeJt9Decode.copiedSamples = true; m_activeJt9Decode.ft8Stage = Ft8MtdDecodeCoordinator::Stage::Final; m_activeJt9Decode.ft8Period = pending.period; - auto * shared = reinterpret_cast<shared_dec_data_t *> (mem_jt9->data ()); - if (!DecoderIpc::publishFt8Mtd (*shared, pending.payload, generation)) + auto const submitted = m_decoderSession.submit (DecoderIpc::Request::ft8 (pending.payload)); + if (!submitted) { logDecoderAbnormalClear ("pending FT8 decode publication failed"); m_activeJt9Decode = {}; @@ -5941,11 +6126,11 @@ MainWindow::DecodePublishResult MainWindow::publishPendingFt8Decode () return PendingPublishResult::Failed; } - m_nextDecoderGeneration = generation; + m_activeJt9Decode.generation = submitted.generation.value (); emitFt8DecoderInvocation (pending.payload.params); qInfo () << "Published pending FT8 final decode" << "period:" << pending.period - << "generation:" << generation; + << "generation:" << submitted.generation.value (); return PendingPublishResult::Published; }); @@ -5984,12 +6169,7 @@ void MainWindow::requestDecoderRestart (QString const& reason) abortJt9Transaction (); updateDecodeControls (); - if (DecoderIpc::hasUsableSize (mem_jt9->size ()) - && mem_jt9->data ()) - { - auto * shared = reinterpret_cast<shared_dec_data_t *> (mem_jt9->data ()); - DecoderIpc::shutdown (*shared); - } + m_decoderSession.shutdown (); if (QProcess::NotRunning == proc_jt9.state ()) { @@ -6064,7 +6244,7 @@ void MainWindow::updateDecodeControls () auto const enabled = !decoderBusy () && backendReady && !m_wav_load_coordinator.isLoading (); ui->DecodeButton->setEnabled (enabled && "WSPR" != m_mode - && "FST4W" != m_mode && "Echo" != m_mode); + && ("FST4W" != m_mode || m_diskData) && "Echo" != m_mode); update_wav_file_actions (); statusUpdate (); } @@ -6075,7 +6255,7 @@ void MainWindow::abortJt9Transaction () m_ft8MtdDecodeCoordinator.publicationFailed ( m_activeJt9Decode.ft8Stage, m_activeJt9Decode.ft8Period); m_activeJt9Decode = {}; - m_jt9PayloadValid = false; + m_decoderSession.abort (); dec_data.params.nagain = false; dec_data.params.ndiskdat = false; m_nclearave = 0; @@ -6176,19 +6356,13 @@ void MainWindow::logDecoderProgress() { if(DecodeOwner::Jt9 != m_decodeOwner || !m_decoderDiagActive) return; - if (DecoderIpc::hasUsableSize (mem_jt9->size ()) && mem_jt9->data ()) + auto const ipc = m_decoderSession.diagnostics (); + if (m_decoderSession.accepts (ipc.generation)) { - auto const * shared = reinterpret_cast<shared_dec_data_t const *> ( - mem_jt9->constData ()); - if (DECODER_IPC_VERSION == DecoderIpc::protocolVersion (*shared) - && m_activeJt9Decode.generation == DecoderIpc::generation (*shared)) + if (ipc.progress != m_decoderDiagProgressCount) { - auto const progress = DecoderIpc::progress (*shared); - if (progress != m_decoderDiagProgressCount) - { - m_decoderDiagProgressCount = progress; - markDecoderProgress (); - } + m_decoderDiagProgressCount = ipc.progress; + markDecoderProgress (); } } @@ -6330,6 +6504,12 @@ void MainWindow::recoverDecoderAtBoundary (QString const& reason, bool manual) void MainWindow::finishDecodeUi () { + if (m_mode == "JTTY") { + ui->DecodeButton->setChecked(false); + if (m_diskData) m_startAnother = m_loopall; + update_wav_file_actions(); + return; + } if(m_mode=="Q65") m_wideGraph->drawRed(0,0); if ("FST4W" == m_mode) { @@ -6395,22 +6575,23 @@ void MainWindow::refreshPileupList() { // Update the ActiveStations display for Q65 pileup situation... int nlist=0; - char list[2000]; - char line[37]; + int capacity=MaxQ65PileupCallers; + char list[MaxQ65PileupCallers * Q65_CALLER_ROW_WIDTH]; + char line[Q65_CALLER_ROW_WIDTH]; list[0]=0; auto fname {QDir::toNativeSeparators(m_config.writeable_data_dir().absoluteFilePath("tsil.3q"))}; - get_q3list_(const_cast<char *> (fname.toLatin1().constData()), &m_diskData, &nlist, - &list[0], (FCL)fname.length(), (FCL)2000); + get_q3list_(const_cast<char *> (fname.toLatin1().constData()), &m_diskData, &capacity, &nlist, + &list[0], (FCL)fname.length(), (FCL)Q65_CALLER_ROW_WIDTH); QString t=""; QString t0=""; std::fill(m_callers.begin(), m_callers.end(), QString {}); for(int i=0; i<qMin(nlist, MaxQ65PileupCallers); i++) { - memcpy(line,&list[37*i],37); + memcpy(line,&list[Q65_CALLER_ROW_WIDTH*i],sizeof line); // Callsign is at offset 11 (6 chars); the final byte is the otherwise-unused terminating char(0), repurposed here for '#'. QString const call = QString::fromLatin1(line + 11, 6).trimmed (); if (m_q65PileupCopiedCallers.contains (call)) { - line[36] = '#'; + line[Q65_CALLER_ROW_WIDTH - 1] = '#'; } t0=QString::fromLatin1(line, sizeof line)+"\n"; @@ -6501,17 +6682,19 @@ void MainWindow::callSandP2(int n) m_specOp=m_config.special_op_id(); bool bCtrl = (n<0); n=qAbs(n)-1; - if(n<0 || n>=int(m_ready2call.size())) return; - if(m_mode!="Q65" and m_ready2call[n]=="") return; - QStringList w=m_ready2call[n].split(' ', SkipEmptyParts); - if(m_mode=="Q65" and m_specOp==SpecOp::Q65_PILEUP and n < MaxQ65PileupCallers) { + if(n<0) return; + QStringList w; + if(m_mode=="Q65" and m_specOp==SpecOp::Q65_PILEUP) { + if(n>=MaxQ65PileupCallers) return; // This code is for 6m EME DXpedition operator w=m_callers[n].split(' ', SkipEmptyParts); if(w.size() < 4) return; m_deCall=w[2]; if(bCtrl) { // Remove this call from q3list. - rm_q3list_(const_cast<char *> (m_deCall.toLatin1().constData()), m_deCall.size()); + auto const fname = QDir::toNativeSeparators(m_config.writeable_data_dir().absoluteFilePath("tsil.3q")).toLatin1(); + rm_q3list_(const_cast<char *>(fname.constData()), + const_cast<char *> (m_deCall.toLatin1().constData()), fname.size(), m_deCall.size()); refreshPileupList(); return; } @@ -6526,6 +6709,9 @@ void MainWindow::callSandP2(int n) if(m_transmitting) m_restart=true; return; } + if(n>=int(m_ready2call.size())) return; + if(m_mode!="Q65" and m_ready2call[n]=="") return; + w=m_ready2call[n].split(' ', SkipEmptyParts); bool frequency_changed = false; if(m_mode=="Q65") { @@ -6656,11 +6842,54 @@ void MainWindow::activeWorked(QString call, QString band) bool MainWindow::handleDecoderOutputEvent (DecoderOutputFramer::Event const& event, bool& decodeCompleted) { + if (m_closing || Jt9ProcessPhase::Failed == m_jt9ProcessPhase) return true; + auto const starting = Jt9ProcessPhase::InitialStarting == m_jt9ProcessPhase + || Jt9ProcessPhase::ReplacementStarting == m_jt9ProcessPhase; + if (DecoderOutputFramer::EventType::Ready == event.type) + { + if (!starting || DecoderIpc::Status::Ok != m_decoderSession.acceptReady (event.protocolVersion)) + { + failDecoderStartup (tr ("The decoder reported an incompatible or unexpected startup handshake (version %1).") + .arg (event.protocolVersion)); + return true; + } + m_decoderStartTimer.stop (); + m_decoderCompletedSinceStart = false; + m_jt9ProcessPhase = Jt9ProcessPhase::Ready; + updateDecodeControls (); + Q_EMIT decoderBackendStarted (); + QTimer::singleShot (0, this, [this] { + auto const pendingResult = publishPendingFt8Decode (); + if (DecodePublishResult::Failed == pendingResult) + requestDecoderRestart ("pending FT8 decode publication failed after restart"); + }); + return true; + } + if (DecoderOutputFramer::EventType::Error == event.type) + { + failDecoderStartup (tr ("The decoder rejected the shared-memory contract: %1.") + .arg (QString::fromLatin1 (event.errorStatus))); + return true; + } + if ((DecoderOutputFramer::EventType::Malformed == event.type + && (event.rawLine.startsWith ("<DecoderReady") + || event.rawLine.startsWith ("<DecoderError"))) + || (starting && DecoderOutputFramer::EventType::Malformed != event.type)) + { + failDecoderStartup (tr ("The decoder reported a malformed or out-of-order startup handshake.")); + return true; + } + if (DecoderOutputFramer::EventType::Rejected == event.type) + { + if (DecodeOwner::Jt9 == m_decodeOwner && m_decoderSession.accepts (event.generation)) + qCritical () << "Decoder request rejected" + << "generation:" << event.generation << event.rawLine.trimmed (); + return true; + } if (DecoderOutputFramer::EventType::Record == event.type) { if (DecodeOwner::Jt9 != m_decodeOwner - || !m_activeJt9Decode.generation - || event.generation != m_activeJt9Decode.generation) + || !m_decoderSession.accepts (event.generation)) { return true; } @@ -6699,8 +6928,7 @@ bool MainWindow::handleDecoderOutputEvent (DecoderOutputFramer::Event const& eve { auto const authoritative = Jt9ProcessPhase::Ready == m_jt9ProcessPhase && DecodeOwner::Jt9 == m_decodeOwner - && m_activeJt9Decode.generation - && event.generation == m_activeJt9Decode.generation; + && m_decoderSession.accepts (event.generation); if (!authoritative) { qWarning () << "Quarantining stale decoder output" @@ -6721,8 +6949,7 @@ bool MainWindow::handleDecoderOutputEvent (DecoderOutputFramer::Event const& eve auto const completion = event.completion; auto const authoritative = DecodeOwner::Jt9 == m_decodeOwner - && m_activeJt9Decode.generation - && event.generation == m_activeJt9Decode.generation; + && m_decoderSession.accepts (event.generation); if (!authoritative) { qWarning () << "Ignoring stale decoder completion" @@ -6738,24 +6965,12 @@ bool MainWindow::handleDecoderOutputEvent (DecoderOutputFramer::Event const& eve << "generation:" << event.generation; } - bool consumed {false}; - int state {-1}; - if (DecoderIpc::hasUsableSize (mem_jt9->size ()) - && mem_jt9->data ()) - { - auto * shared = reinterpret_cast<shared_dec_data_t *> (mem_jt9->data ()); - if (DECODER_IPC_VERSION == DecoderIpc::protocolVersion (*shared) - && completion.generation == DecoderIpc::generation (*shared)) - { - state = DecoderIpc::state (*shared); - consumed = DecoderIpc::consume (*shared, completion.generation); - } - } - if (!consumed) + auto const ipc = m_decoderSession.diagnostics (); + if (DecoderIpc::Status::Ok != m_decoderSession.complete (completion)) { qWarning () << "Unable to consume matching decoder completion" << "generation:" << completion.generation - << "state:" << state; + << "state:" << ipc.state; requestDecoderRestart ("matching decoder completion could not be consumed"); return true; } @@ -7225,7 +7440,6 @@ void MainWindow::readFromStdout() //readFromStdout m_ft8MtdDecodeCoordinator.completed ( m_activeJt9Decode.ft8Stage, m_activeJt9Decode.ft8Period); m_decoderCompletedSinceStart = true; - m_jt9PayloadValid = m_jt9PayloadValid || m_activeJt9Decode.copiedSamples; m_activeJt9Decode = {}; finishDecodeUi (); endDecode (DecodeOwner::Jt9); @@ -7307,15 +7521,12 @@ void MainWindow::rx_frequency_activity_cleared () { m_QSOText.clear(); set_dateTimeQSO(-1); // G4WJS: why do we do this? - // decodedTextBrowser2's document just lost every block; drop our cached - // JTTY per-transmission QTextBlock handles along with it. - m_jttyQsoLines.clear(); - m_jttyQsoGroupEndPosition = -1; } //------------------------------------------------------------- //guiUpdate() void MainWindow::guiUpdate() { + if (jttyDrainInProgress()) return; static char message[38]; static char msgsent[38]; double txDuration; @@ -8070,7 +8281,7 @@ void MainWindow::guiUpdate() } } - progressBar.setVisible(true); + progressBar.setVisible(m_mode != "JTTY"); // turn the progressbar red during transmission if(m_config.progressBar_red()) { if(m_transmitting) { @@ -8121,7 +8332,7 @@ void MainWindow::guiUpdate() if(m_transmitting or m_monitoring) n=int(m_s6)%3; progressBar.setValue(n); } - if(m_mode!="Echo") { + if(m_mode!="Echo" && m_mode!="JTTY") { if(m_monitoring or m_transmitting) { progressBar.setMaximum(m_TRperiod); int isec=int(fmod(tsec,m_TRperiod)); @@ -8166,6 +8377,12 @@ void MainWindow::guiUpdate() t=m_fm1.trimmed(); } if(m_mode=="FT4" or m_mode == "JTTY") t="Tx: "+ m_currentMessage; + if (m_mode == "JTTY") { + tx_status_label.setToolTip (t); + tx_status_label.setAccessibleDescription (t); + t = tx_status_label.fontMetrics ().elidedText ( + t, Qt::ElideRight, qMax (100, statusBar ()->width () / 4)); + } tx_status_label.setText(t.trimmed()); } } @@ -8211,7 +8428,7 @@ void MainWindow::guiUpdate() transmitDisplay(false); } else if (!m_diskData && !m_tx_watchdog) { tx_status_label.setStyleSheet(""); - tx_status_label.setText(""); + tx_status_label.setText(m_mode == "JTTY" ? tr("Stopped") : QString{}); } if (m_tx_inhibited && !m_tx_watchdog && !m_generated_message_error) { tx_status_label.setStyleSheet ( @@ -8267,13 +8484,15 @@ void MainWindow::useNextCall() bool MainWindow::startTx2() { + if (jttyDrainInProgress()) return false; + bool const jtty = m_jttyTxLifecycle.active () && !m_tune; if (m_mode == "JTTY" && !m_tune - && (!m_jttyTxActive || jttyTxCommittedSamples () <= 0)) { + && (!jtty || jttyTxCommittedSamples () <= 0)) { return false; } bool modulator_active; - bool const tci_active = (m_mode == "JTTY" && m_jttyTxActive) - ? m_jttyTxUsesTciAudio + bool const tci_active = jtty + ? m_jttyTxLifecycle.backend () == JttyTxLifecycle::Backend::Tci : m_tci_audio; if (tci_active) modulator_active=m_tci_mod_active; else modulator_active=m_modulator->isActive (); @@ -8407,21 +8626,48 @@ void MainWindow::noteTxStopReason (TxEvidence::TxStopReason reason) void MainWindow::noteTxModeChange (QString const& mode) { + if (m_mode == "JTTY" && mode != m_mode) { + bool const resume = m_monitoring; + // Drain the old stream before a timed mode can reuse reference-filter history. + drainJttyReceive(); + if (resume) QTimer::singleShot(0, this, [this, mode] { + if (!m_closing && m_mode == mode) monitor(true); + }); + } if (mode != m_mode) cancelPendingFt8Decode ("mode changed"); if (mode != m_mode && m_beaconTxController.active ()) { processBeaconActions (m_beaconTxController.exitMode ()); } - if (mode != m_mode && (m_transmitting || g_iptt == 1 || m_jttyTxActive)) + if (mode != m_mode && (m_transmitting || g_iptt == 1 + || m_jttyTxLifecycle.active () + || !m_jttyTransmitQueue.empty ())) { noteTxStopReason (TxEvidence::TxStopReason::ModeChange); + if (m_jttyTxLifecycle.active () || !m_jttyTransmitQueue.empty ()) stopTx (); + } +} + +void MainWindow::updateModeControlLock () +{ + bool enabled = !m_modeLocked && !m_transmitting + && !m_jttyTxLifecycle.active () && m_jttyTransmitQueue.empty (); +#ifdef WIN32 + enabled = enabled && !m_mmttyHandoff.active (); +#endif + ui->menuMode->setEnabled (enabled); + for (auto * button : {ui->houndButton, ui->ft8Button, ui->ft4Button, + ui->msk144Button, ui->q65Button, ui->jt65Button, + ui->echoButton}) + { + button->setEnabled (enabled); } } int MainWindow::txStopTailMs (bool tciAudio) const { return TxEvidence::TxPlaybackDiagnostics::decisionFor ( - m_pendingTxStopReason, tciAudio || m_mode == "JTTY").tail_ms; + m_pendingTxStopReason, tciAudio || m_jttyTxLifecycle.active ()).tail_ms; } void MainWindow::stopTxEvidence (int tailMs) @@ -8465,24 +8711,50 @@ void MainWindow::captureJttyTxEvidenceTotals (qint64 servedSamples, void MainWindow::stopTx() { - bool const tciAudio = (m_mode == "JTTY" && m_transmitting) - ? m_jttyTxUsesTciAudio - : m_tci_audio; + auto const jttyStop = m_jttyTxLifecycle.beginStop (); + bool const jttyTx = bool (jttyStop); +#ifdef WIN32 + bool const abnormalJttyStop = jttyTx + && m_pendingTxStopReason != TxEvidence::TxStopReason::NormalEnd; +#endif + bool const tciAudio = jttyTx + ? jttyStop->backend == JttyTxLifecycle::Backend::Tci : m_tci_audio; int const stopTxDelayMs = txStopTailMs (tciAudio); - if (m_mode == "JTTY" && m_jttyTxActive) { + if (jttyTx) { + m_delayedJttyStopContext = *jttyStop; interruptJttyTx(); + } else if (!m_jttyTransmitQueue.empty ()) { + auto const cancelled = m_jttyTransmitQueue.cancel (); + for (auto requestId : cancelled) { + Q_EMIT jttyTextRejected (requestId, JttyTxRejectReason::Aborted); + } + m_jttyQueueNotice = tr ("JTTY transmission cancelled; some text may already have transmitted."); + updateJttySendButton (); + if (!m_transmitting && g_iptt != 1) return; } if (tciAudio) Q_EMIT m_config.transceiver_modulator_stop(); else Q_EMIT endTransmitMessage (); - if (m_mode == "JTTY" && !tciAudio) { + if (jttyTx && !tciAudio) { Q_EMIT endJttyStream (); } + if (jttyTx) { + m_jttyTxWatchdog.stop (); + m_jttyEnqueueWatchdog.stop (); + m_jttyTxLifecycle.markBackendStopRouted (*jttyStop); + m_jttyTxLifecycle.reset (); + m_pendingJttyMessages.clear (); + } m_btxok = false; m_transmitting = false; g_iptt=0; + updateModeControlLock (); if (!m_tx_watchdog && !m_generated_message_error) { tx_status_label.setStyleSheet(""); tx_status_label.setText(""); + if (!m_tx_inhibited && m_mode == "JTTY") { + tx_status_label.setToolTip ({}); + tx_status_label.setAccessibleDescription ({}); + } } if (tciAudio) { ptt0Timer.start(stopTxDelayMs); @@ -8492,6 +8764,11 @@ void MainWindow::stopTx() statusUpdate (); } stopTxEvidence (stopTxDelayMs); +#ifdef WIN32 + if (abnormalJttyStop && !m_preserveMmttyOutputDuringStop) { + finalizeMmttyExternalAbort (); + } +#endif } void MainWindow::stopTx2() @@ -8500,7 +8777,11 @@ void MainWindow::stopTx2() // mode may no longer be the mode that started Tx or Tune. auto const beaconTxPlanId = m_beaconTxController.txPlanId (); auto const beaconTunePlanId = m_beaconTxController.tunePlanId (); - bool const tciAudio = (m_mode == "JTTY") ? m_jttyTxUsesTciAudio : m_tci_audio; + bool const delayedJtty = m_delayedJttyStopContext.backend + != JttyTxLifecycle::Backend::None; + bool const tciAudio = delayedJtty + ? m_delayedJttyStopContext.backend == JttyTxLifecycle::Backend::Tci + : m_tci_audio; if (tciAudio) { Q_EMIT m_config.transceiver_ptt (false); //Lower PTT monitor (true); @@ -8520,7 +8801,18 @@ void MainWindow::stopTx2() processBeaconActions (m_beaconTxController.tuneCompleted (beaconTunePlanId)); } keep_last_tx_label = true; - last_tx_label.setText(tr ("Last Tx: %1").arg (m_currentMessage.trimmed())); + QString const lastTx = tr ("Last Tx: %1").arg (m_currentMessage.trimmed()); + last_tx_label.setToolTip (lastTx); + last_tx_label.setAccessibleDescription (lastTx); + last_tx_label.setText (m_mode == "JTTY" + ? last_tx_label.fontMetrics ().elidedText ( + lastTx, Qt::ElideRight, qMax (150, statusBar ()->width () / 4)) + : lastTx); +#ifdef WIN32 + resumeMmttyHandoff (); +#endif + m_delayedJttyStopContext = {}; + if (m_mode == "JTTY") feedJttyTransmitQueue (); } QString MainWindow::expandTxMacros(QString const& message) const @@ -8737,7 +9029,10 @@ void MainWindow::handleDecodeSelection( } if(m_mode=="JTTY") { m_deCall = word; - ui->dxCallEntry->setText(m_deCall); + ui->dxCallEntry->setText(m_deCall); // clears m_jttyHisCallSnr via on_dxCallEntry_textChanged + // Capture the SNR of the decode actually selected, not whichever decoded last. + m_jttyHisCallSnr = jttySnrForSelectedWord( + word, selection_origin == DecodedMessageReaction::SelectionOrigin::ManualLeftPane); return; } DecodedText message {line.trimmed().left(61).remove("TU; ")}; @@ -9232,15 +9527,7 @@ void MainWindow::abortQSO() bool MainWindow::stdCall(QString const& w) { - static QRegularExpression standard_call_re { - R"( - ^\s* # optional leading spaces - ( [A-Z]{0,2} | [A-Z][0-9] | [0-9][A-Z] ) # part 1 - ( [0-9][A-Z]{0,3} ) # part 2 - (/R | /P)? # optional suffix - \s*$ # optional trailing spaces - )", QRegularExpression::CaseInsensitiveOption | QRegularExpression::ExtendedPatternSyntaxOption}; - return standard_call_re.match (w).hasMatch (); + return Radio::is_standard_callsign(w); } bool MainWindow::is77BitMode () const @@ -10009,6 +10296,7 @@ void MainWindow::on_dxCallEntry_textChanged (QString const& call) } set_dateTimeQSO (-1); // reset the QSO start time when DXCall changes m_hisCall = call; + if (m_mode=="JTTY") m_jttyHisCallSnr = -10; // stale SNR belonged to the previous DX call if(m_QSYMessageCreatorWidget) m_QSYMessageCreatorWidget->getDxBase(QString(Radio::base_callsign(call))); if (!blocked) ui->dxGridEntry->clear(); // conditional because not always useful with highlightDXCall/DXGrid feature if (ui->DX_Call_Button->isChecked() && !(m_mode=="FT8" && SpecOp::HOUND==m_specOp)) ui->DX_Call_Button->click (); @@ -10136,7 +10424,9 @@ void MainWindow::acceptQSO (QDateTime const& QSO_date_off, QString const& call, m_score++; m_EMEworked[call]=true; if(m_specOp==SpecOp::Q65_PILEUP) { - rm_q3list_(const_cast<char *> (m_deCall.toLatin1().constData()), m_deCall.size()); + auto const fname = QDir::toNativeSeparators(m_config.writeable_data_dir().absoluteFilePath("tsil.3q")).toLatin1(); + rm_q3list_(const_cast<char *>(fname.constData()), + const_cast<char *> (m_deCall.toLatin1().constData()), fname.size(), m_deCall.size()); refreshPileupList(); } m_ActiveStationsWidget->setRate(m_score); @@ -10685,6 +10975,7 @@ void MainWindow::setDecodeHeadings(QString const& lh, QString const& rh) void MainWindow::on_actionFST4_triggered() { + if (jttyDrainInProgress()) { ui->actionJTTY->setChecked(true); return; } noteTxModeChange (QStringLiteral ("FST4")); QTimer::singleShot (50, this, [=] { ui->TxFreqSpinBox->setValue(m_settings->value("TxFreq_old",1500).toInt()); @@ -10748,6 +11039,7 @@ void MainWindow::on_actionFST4_triggered() void MainWindow::on_actionFST4W_triggered() { + if (jttyDrainInProgress()) { ui->actionJTTY->setChecked(true); return; } noteTxModeChange (QStringLiteral ("FST4W")); m_mode="FST4W"; if(m_specOp==SpecOp::HOUND) { @@ -10783,6 +11075,7 @@ void MainWindow::on_actionFST4W_triggered() void MainWindow::on_actionFT4_triggered() { + if (jttyDrainInProgress()) { ui->actionJTTY->setChecked(true); return; } noteTxModeChange (QStringLiteral ("FT4")); if (m_mode=="MSK144") QTimer::singleShot (75, this, [=] {on_actionFT4_triggered();}); QTimer::singleShot (50, this, [=] { @@ -10836,6 +11129,7 @@ void MainWindow::on_actionFT4_triggered() void MainWindow::on_actionFT8_triggered() { + if (jttyDrainInProgress()) { ui->actionJTTY->setChecked(true); return; } noteTxModeChange (QStringLiteral ("FT8")); if (m_mode=="MSK144") QTimer::singleShot (75, this, [=] {on_actionFT8_triggered();}); QTimer::singleShot (50, this, [=] { @@ -11007,6 +11301,7 @@ void MainWindow::on_actionFT8_triggered() void MainWindow::on_actionJT4_triggered() { + if (jttyDrainInProgress()) { ui->actionJTTY->setChecked(true); return; } noteTxModeChange (QStringLiteral ("JT4")); QTimer::singleShot (50, this, [=] { ui->TxFreqSpinBox->setValue(m_settings->value("TxFreq_old",1500).toInt()); @@ -11075,6 +11370,7 @@ void MainWindow::on_actionJT4_triggered() void MainWindow::on_actionJT9_triggered() { + if (jttyDrainInProgress()) { ui->actionJTTY->setChecked(true); return; } noteTxModeChange (QStringLiteral ("JT9")); m_mode="JT9"; if(m_specOp==SpecOp::HOUND) { @@ -11164,6 +11460,7 @@ void MainWindow::on_actionJT9_triggered() void MainWindow::on_actionJT65_triggered() { + if (jttyDrainInProgress()) { ui->actionJTTY->setChecked(true); return; } noteTxModeChange (QStringLiteral ("JT65")); if (m_mode=="MSK144") QTimer::singleShot (75, this, [=] {on_actionJT65_triggered();}); QTimer::singleShot (50, this, [=] { @@ -11172,6 +11469,7 @@ void MainWindow::on_actionJT65_triggered() }); on_actionJT9_triggered(); m_mode="JT65"; + m_jt65ClearAveragesPending = true; if(m_specOp==SpecOp::HOUND) { m_config.setSpecial_None(); m_specOp=m_config.special_op_id(); @@ -11244,6 +11542,7 @@ void MainWindow::on_actionJT65_triggered() void MainWindow::on_actionQ65_triggered() { + if (jttyDrainInProgress()) { ui->actionJTTY->setChecked(true); return; } noteTxModeChange (QStringLiteral ("Q65")); if (m_mode=="MSK144") QTimer::singleShot (75, this, [=] {on_actionQ65_triggered();}); QTimer::singleShot (50, this, [=] { @@ -11324,6 +11623,7 @@ void MainWindow::on_actionQ65_triggered() void MainWindow::on_actionJTTY_triggered() { + if (jttyDrainInProgress()) { ui->actionJTTY->setChecked(true); return; } noteTxModeChange (QStringLiteral ("JTTY")); on_stopButton_clicked(); m_mode = "JTTY"; @@ -11340,7 +11640,7 @@ void MainWindow::on_actionJTTY_triggered() m_FFTSize = m_nsps / 2; if (m_tci_audio) Q_EMIT m_config.transceiver_blocksize (m_FFTSize); else Q_EMIT FFTSize (m_FFTSize); - m_TRperiod=180; //We need a nonzero setting for WideGraph plotter to work. + m_TRperiod=180; // Legacy timed interfaces; JTTY receive uses sample coordinates. m_hsymStop=620; m_wideGraph->setPeriod(m_TRperiod,m_nsps); m_detector->setTRPeriod(m_TRperiod); // marshals to the audio thread @@ -11353,6 +11653,8 @@ void MainWindow::on_actionJTTY_triggered() // state directly rather than relying on that signal to reach it. m_wideGraph->setRxFreq(ui->RxFreqSpinBox_2->value()); m_wideGraph->setTol(ui->sbFtol_2->value()); + m_fastGraph->hide(); + m_wideGraph->showNormal(); setDecodeHeadings("", ""); updateJttyDecodeHeadings(); setDecodeTitles(tr ("All Decodes"), tr ("QSO Frequency")); @@ -11374,6 +11676,7 @@ void MainWindow::on_actionJTTY_triggered() void MainWindow::on_actionMSK144_triggered() { + if (jttyDrainInProgress()) { ui->actionJTTY->setChecked(true); return; } m_hsymStop=105; m_TRperiod=ui->sbTR->value(); if(SpecOp::EU_VHF < m_specOp) { @@ -11466,6 +11769,7 @@ void MainWindow::on_actionMSK144_triggered() void MainWindow::on_actionWSPR_triggered() { + if (jttyDrainInProgress()) { ui->actionJTTY->setChecked(true); return; } noteTxModeChange (QStringLiteral ("WSPR")); m_mode="WSPR"; if(m_specOp==SpecOp::HOUND) { @@ -11502,6 +11806,7 @@ void MainWindow::on_actionWSPR_triggered() void MainWindow::on_actionEcho_triggered() { + if (jttyDrainInProgress()) { ui->actionJTTY->setChecked(true); return; } noteTxModeChange (QStringLiteral ("Echo")); int nd=int(m_ndepth&3); on_actionJT4_triggered(); @@ -11561,6 +11866,7 @@ void MainWindow::on_actionEcho_triggered() void MainWindow::on_actionFreqCal_triggered() { + if (jttyDrainInProgress()) { ui->actionJTTY->setChecked(true); return; } noteTxModeChange (QStringLiteral ("FreqCal")); on_actionJT9_triggered(); m_mode="FreqCal"; @@ -11602,6 +11908,8 @@ void MainWindow::switch_mode (Mode mode) // Sit just under the decoded-text panes, outside the per-mode // displayWidgets()/ModeUiControl mechanism -- only meaningful for JTTY. bool const jtty = m_mode=="JTTY"; + updateJttyReceivePolicy(jtty); + progressBar.setVisible(!jtty); ui->cbLowerCase->setVisible(jtty); ui->cbIncludeTime->setVisible(jtty); if (mode != Modes::MSK144) m_msk144basefreq = 0; @@ -11664,7 +11972,7 @@ void MainWindow::WSPR_config(bool b) ui->DX_controls_widget->setVisible (!b or (m_mode=="Echo")); ui->lh_decodes_title_label->setVisible(!b and ui->cbMenus->isChecked()); ui->logQSOButton->setVisible(!b); - ui->DecodeButton->setEnabled(!b); + updateDecodeControls (); bool bFST4W=(m_mode=="FST4W"); ui->sbTxPercent->setEnabled(!bFST4W or configuredRoundRobinPolicy ().kind == BeaconTx::RoundRobinPolicy::Kind::Random); @@ -12337,7 +12645,7 @@ void MainWindow::setXIT(int n, Frequency base) if (!(m_bSimplex || (SpecOp::FOX==m_specOp && m_config.superFox()))) { // m_bSimplex is false, so we can use split mode if requested if (m_config.split_mode () && (!m_config.enable_VHF_features () || - m_mode=="FT4" || m_mode == "FT8" || m_mode=="FST4")) { + m_mode=="FT4" || m_mode == "FT8" || m_mode=="FST4" || m_mode=="JTTY")) { // Don't use XIT for VHF & up requested_xit=(n/500)*500 - 1500; } @@ -12422,6 +12730,8 @@ void MainWindow::applyOperatingFrequencyTransition (OperatingFrequency::Transiti { if (transition.before.rx != transition.after.rx) { + if (m_mode == "JTTY") updateJttyReceiveContext(); + if (m_mode == "JT65") m_jt65ClearAveragesPending = true; cancelPendingFt8Decode ("dial frequency changed"); genCQMsg (); } @@ -12444,6 +12754,75 @@ void MainWindow::applyOperatingFrequencyTransition (OperatingFrequency::Transiti displayDialFrequency (); } +void MainWindow::updateRigMeters (Transceiver::TransceiverState const& s) +{ + bool const enabled = m_config.PWR_and_SWR (); + swr_label.setVisible (enabled && m_mode != "Echo"); + + if (enabled && s.online () && (s.ptt () || m_transmitting || m_tune)) + { + auto const power = round (s.power () / 1000.); + ui->label->setText (tr ("%1 W").arg (power)); + if (power >= 100) + { + auto const point_size = m_config.text_font ().pointSizeF (); + ui->label->setMinimumWidth (2.8 * point_size + 16); + ui->outAttenuation->setMinimumWidth (2.8 * point_size + 16); + } + } + else + { + ui->label->setText (tr ("Pwr")); + } + + auto const swr = enabled && s.online () ? s.swr () : 0; + QString style; + if (swr > 200) + { + style = "QLabel{color: #ffffff; background-color: #ff0000}"; + } + else if (swr > 150) + { + style = "QLabel{color: #000000; background-color: #ffff00}"; + } + if (swr_label.styleSheet () != style) swr_label.setStyleSheet (style); + swr_label.setText (swr ? tr ("SWR: %1").arg (swr / 100., 0, 'f', swr < 1000 ? 2 : 1) + : QString {}); +} + +bool MainWindow::stopForHighSWR (Transceiver::TransceiverState const& s) +{ + if (!m_config.PWR_and_SWR () || !m_config.check_SWR () || !s.online () + || s.swr () <= 250 + || !(s.ptt () || g_iptt == 1 || m_transmitting || m_tune + || m_tx_when_ready || ptt1Timer.isActive ())) + { + return false; + } + + requestTxStop (TxEvidence::TxStopReason::Error); + return true; +} + +void MainWindow::showHighSWRWarning (unsigned swr) +{ + if (m_swrWarning) return; + + auto * warning = new MessageBox {MessageBox::Warning, + tr ("SWR > 2.5 !!!\n\n" + "Transmission was stopped\n\n" + "Check your antenna"), MessageBox::Ok, this}; + warning->setInformativeText (tr ("SWR: %1").arg (swr / 100., 0, 'f', 2)); + m_swrWarning = warning; + warning->setDefaultButton (MessageBox::Ok); + warning->setWindowModality (Qt::ApplicationModal); + connect (warning, &QDialog::finished, this, [this, warning] { + m_swrWarning.clear (); + warning->deleteLater (); + }); + warning->show (); +} + void MainWindow::handle_transceiver_update (Transceiver::TransceiverState const& s) { if (!m_startup_rig_reported) @@ -12454,59 +12833,11 @@ void MainWindow::handle_transceiver_update (Transceiver::TransceiverState const& QString {"online=%1"}.arg (s.online () ? "true" : "false")); } Transceiver::TransceiverState old_state {m_rigState}; - //transmitDisplay (s.ptt ()); - if (s.ptt () // && !m_rigState.ptt () - ) { // safe to start audio - // (caveat - DX Lab Suite Commander) - startTxAudioAfterPttDelay (); - } - - // Display PWR and SWR - if(m_config.PWR_and_SWR()) { - if (!band_hopping_label.isVisible ()) { - statusBar ()->addPermanentWidget (&band_hopping_label); - band_hopping_label.setMinimumSize (QSize {80, 18}); - band_hopping_label.show(); - } - if (m_rigState.power() != s.power() && m_transmitting) { - ui->label->setText(QString {tr("%1 W")}.arg (round(s.power()/1000.))); - if (round(s.power()/1000.) >= 100) { - qreal pointSize = m_config.text_font().pointSizeF(); - - ui->label->setMinimumWidth (2.8*pointSize + 16); - ui->outAttenuation->setMinimumWidth (2.8*pointSize + 16); - } - } else { - ui->label->setText(tr ("Pwr")); - } - if (m_rigState.swr() != s.swr()) { - static bool s_alreadyShowingSWRAlert = false; - if (s.swr() > 0) { - if (s.swr()>150) band_hopping_label.setStyleSheet ("QLabel{color: #000000; background-color: #ffff00}"); - if (s.swr()>200) band_hopping_label.setStyleSheet ("QLabel{color: #ffffff; background-color: #ff0000}"); - if (s.swr()>250 && m_config.check_SWR()) { - if (!s_alreadyShowingSWRAlert) { // avoid recursion - on_stopTxButton_clicked(); - s_alreadyShowingSWRAlert = true; - MessageBox::warning_message (this, tr ("SWR > 2.5 !!!\n\n" - "Transmission was stopped\n\n" - "Check your antenna")); - s_alreadyShowingSWRAlert = false; - } - } - if (s.swr()<1000) { - band_hopping_label.setText(QString {"SWR: %1"}.arg (s.swr()/100.,0,'f',2)); - } else { - band_hopping_label.setText(QString {"SWR: %1"}.arg (s.swr()/100.,0,'f',1)); - } - } else { - if (!s_alreadyShowingSWRAlert) { // retain value and color if SWR was > 2.5 - band_hopping_label.setText(""); - band_hopping_label.setStyleSheet(""); - } - } + bool const high_swr = stopForHighSWR (s); + if (s.ptt () && !high_swr) + { + startTxAudioAfterPttDelay (); } - } m_rigState = s; auto const transition = m_operatingFrequency.reconcile ( @@ -12539,6 +12870,8 @@ void MainWindow::handle_transceiver_update (Transceiver::TransceiverState const& update_dynamic_property (ui->readFreq, "state", "ok"); ui->readFreq->setEnabled (false); ui->readFreq->setText (s.split () ? "S" : ""); + updateRigMeters (s); + if (high_swr) showHighSWRWarning (s.swr ()); } void MainWindow::handle_transceiver_closing (bool failed) @@ -12548,20 +12881,32 @@ void MainWindow::handle_transceiver_closing (bool failed) m_receiveConsumer.invalidate (); m_receiveQueue.clear (); } - if (m_closing || m_mode != "JTTY" || !m_jttyTxActive - || !m_jttyTxUsesTciAudio) + if (!m_jttyTxLifecycle.active () + || m_jttyTxLifecycle.backend () != JttyTxLifecycle::Backend::Tci) { return; } noteTxStopReason (failed ? TxEvidence::TxStopReason::Error : TxEvidence::TxStopReason::UserHalt); + rejectPendingJttyMessages (JttyTxRejectReason::NotAvailable); + m_jttyTxLifecycle.failAll (); + m_pendingJttyMessages.clear (); + m_jttyEnqueueWatchdog.stop (); stopTx (); +#ifdef WIN32 + finalizeMmttyExternalAbort (); +#endif } void MainWindow::handle_transceiver_failure (QString const& reason) { noteTxStopReason (TxEvidence::TxStopReason::Error); + if (m_jttyTxLifecycle.active () || !m_jttyTransmitQueue.empty ()) { + stopTx (); + m_jttyQueueNotice = tr ("The audio backend stopped: %1").arg (reason); + updateJttySendButton (); + } m_beaconTxController.setAutoEnabled (false); if (m_beaconTxController.txLifecycle () == BeaconTx::TxLifecycle::Decided || m_beaconTxController.txLifecycle () == BeaconTx::TxLifecycle::StartRequested) @@ -12583,6 +12928,9 @@ void MainWindow::handle_transceiver_failure (QString const& reason) reset_transmit_controls_after_stop (); rigFailure (reason); rigFailed = true; +#ifdef WIN32 + finalizeMmttyExternalAbort (); +#endif } void MainWindow::rigFailure (QString const& reason) @@ -12638,7 +12986,8 @@ void MainWindow::rigFailure (QString const& reason) void MainWindow::dispatchTxRequest (TxEvidence::TxRequest const& request) { bool const useTciAudio = request.mode == QStringLiteral ("JTTY") - ? m_jttyTxUsesTciAudio : m_tci_audio; + ? m_jttyTxLifecycle.backend () == JttyTxLifecycle::Backend::Tci + : m_tci_audio; if (useTciAudio) { if (!request.tuning && rigTuneTimer.isActive ()) @@ -12665,20 +13014,23 @@ void MainWindow::dispatchTxRequest (TxEvidence::TxRequest const& request) void MainWindow::transmit (double snr) { + bool const jttyTx = m_jttyTxLifecycle.active () && !m_tune + && jttyTxCommittedSamples () > 0; qint64 const jttyCommittedSamples = jttyTxCommittedSamples (); - beginTxEvidenceGeneration (m_mode == "JTTY" && jttyCommittedSamples > 0 + beginTxEvidenceGeneration (jttyTx ? jttyCommittedSamples - 1 : -1, false); auto const txSessionId = m_txEvidenceSourceSession; auto const txGeneration = m_txEvidenceGeneration; TxEvidence::TxRequest request; - request.mode = m_mode; + request.mode = jttyTx ? QStringLiteral ("JTTY") : m_mode; request.channel = m_config.audio_output_channel (); request.snr_db = snr; request.tr_period_s = m_TRperiod; request.session_id = txSessionId; request.generation = txGeneration; - request.queue_epoch = m_jttyTxQueueEpoch; + request.queue_epoch = jttyTx ? m_jttyTxLifecycle.epoch () + : TxAudioQueueEpoch::invalid (); request.tuning = m_tune; int const cwSymbols = qBound (0, int (icw[0]), NUM_CW_SYMBOLS - 1); request.cw_id.reserve (cwSymbols); @@ -12737,13 +13089,14 @@ void MainWindow::transmit (double snr) dispatchTxRequest (request); } - if (m_mode == "JTTY") { + if (request.mode == "JTTY") { + m_jttyTxLifecycle.markTransmitting (); m_dateTimeSentTx3=QDateTime::currentDateTimeUtc(); toneSpacing=-2.0; //Transmit a pre-computed, filtered waveform. double txt=m_nsym_jtty*384.0/12000.0; request.symbols_length = m_nsym_jtty; request.frames_per_symbol = 384.0; - request.frequency_hz = 1500.0; + request.frequency_hz = ui->TxFreqSpinBox_2->value () - m_XIT; request.tone_spacing = toneSpacing; request.synchronize = false; request.tr_period_s = txt; @@ -13026,7 +13379,7 @@ void MainWindow::transmitDisplay (bool transmitting) } // the following are always disallowed in transmit - ui->menuMode->setEnabled (!transmitting && !m_modeLocked); + updateModeControlLock (); } } @@ -13794,7 +14147,9 @@ void MainWindow::astroUpdate () } auto correction = m_astroWidget->astroUpdate(QDateTime::currentDateTimeUtc (), - m_config.my_grid(), m_hisGrid,m_operatingFrequency.rx (),"Echo" == m_mode, + m_config.my_grid(), m_hisGrid, m_config.has_precise_home_coordinates (), + m_config.home_latitude (), m_config.home_longitude (), + m_operatingFrequency.rx (),"Echo" == m_mode, m_transmitting,m_auto,!m_config.tx_frequency_corrections_allowed (),m_TRperiod); m_fDop=correction.dop; m_fSpread=correction.width; @@ -13862,7 +14217,7 @@ RigFrequencyChangePolicy::Activity MainWindow::rigFrequencyActivity () const m_tx_when_ready, m_transmitting, m_tune, - m_jttyTxActive, + m_jttyTxLifecycle.active (), ptt1Timer.isActive (), ptt0Timer.isActive (), m_rigState.ptt (), @@ -13915,11 +14270,13 @@ bool MainWindow::dispatchNominalFrequency (Frequency corrected, bool MainWindow::requestNominalFrequencyChange (Frequency frequency, FrequencyRequestOrigin origin) { + auto const previous = m_operatingFrequency.rx(); if (!m_operatingFrequency.requestNominal (frequency, m_astroCorrection.rx, [this, origin] (Frequency corrected) { return dispatchNominalFrequency (corrected, origin, m_monitoring); })) return false; + if (m_mode == "JTTY" && previous != m_operatingFrequency.rx()) updateJttyReceiveContext(); genCQMsg (); if (m_astroWidget) { @@ -14170,6 +14527,10 @@ void MainWindow::tx_watchdog (bool triggered) tx_status_label.setText (tr (" Runaway Tx watchdog ")); QApplication::alert (this); if (SpecOp::HOUND == m_specOp) ui->txrb1->click (); // Go back to Tx1 + if (m_jttyTxLifecycle.active ()) stopTx (); +#ifdef WIN32 + finalizeMmttyExternalAbort (); +#endif } else { @@ -17416,12 +17777,6 @@ void MainWindow::set_mode_from_command_line(const QString& mode, bool lock_mode) if (lock_mode) { m_modeLocked = true; - ui->menuMode->setEnabled(false); - ui->ft8Button->setEnabled(false); - ui->ft4Button->setEnabled(false); - ui->msk144Button->setEnabled(false); - ui->q65Button->setEnabled(false); - ui->jt65Button->setEnabled(false); - ui->houndButton->setEnabled(false); + updateModeControlLock (); } } diff --git a/widgets/mainwindow.h b/widgets/mainwindow.h index fdc0d444..52d7fdc0 100644 --- a/widgets/mainwindow.h +++ b/widgets/mainwindow.h @@ -49,6 +49,7 @@ class QHBoxLayout; #include "Audio/TxRequest.hpp" #include "Audio/WavLoadCoordinator.hpp" #include "commons.h" +#include "lib/qra/q65/q65_limits.h" #include "FastDecode.hpp" #include "ReferenceSpectrum.hpp" #include "Radio.hpp" @@ -57,6 +58,9 @@ class QHBoxLayout; #include "models/FrequencyList.hpp" #include "Configuration.hpp" #include "JttyN1mmOutput.hpp" +#include "JttyReceiveAudio.hpp" +#include "JttyMmttyHandoff.hpp" +#include "JttyTxLifecycle.hpp" #include "WSPR/WSPRBandHopping.hpp" #include "Transceiver/Transceiver.hpp" #include "DisplayManual.hpp" @@ -75,7 +79,8 @@ class QHBoxLayout; #include "AutoRespondScoring.hpp" #include "AutoRespondPeriod.hpp" #include "HoundTransmissionPolicy.hpp" -#include "JttyDraftAcceptanceTracker.hpp" +#include "JttyLiveEntry.hpp" +#include "JttyTransmitQueue.hpp" #include "QsoProgress.hpp" #include "DecodeOperatingContext.hpp" #include "DecoderOutputFramer.hpp" @@ -184,7 +189,8 @@ public: QueueFull, BackendRejected, Aborted, - NotAvailable + NotAvailable, + BackendTimedOut }; Q_ENUM(JttyTxRejectReason) @@ -193,7 +199,7 @@ public: static QRegularExpression const non_r_db_regexp; explicit MainWindow(QDir const& temp_directory, bool multiple, MultiSettings *, - QSharedMemory *shdmem, unsigned downSampleFactor, + DecoderIpc::Session& decoderSession, unsigned downSampleFactor, QSplashScreen *, QProcessEnvironment const&, bool automated_test, QString base_style_sheet, std::unique_ptr<AudioInputSource> audio_input_source = {}, @@ -208,7 +214,7 @@ public: #endif bool decoderBusy () const - {return m_fastDecodePending || DecodeOwner::None != m_decodeOwner || m_ft8MtdDecodeCoordinator.hasPending ();} + {return m_fastDecodePending || DecodeOwner::None != m_decodeOwner || m_ft8MtdDecodeCoordinator.hasPending () || jttyReviewBusy();} void set_mode_from_command_line(const QString& mode, bool lock_mode = false); bool decoderBackendRunning () const; bool diskDataActive () const {return m_diskData;} @@ -230,18 +236,27 @@ public: static constexpr int liveAudioTestDecodeLowFrequency () {return 200;} static constexpr int liveAudioTestDecodeHighFrequency () {return 3000;} bool configureLiveAudioTestDecodeRange (); + bool startWavDecodeTest (QString const& path); bool prepareLiveAudioTestFt8InputCompletion (); QString completeLiveAudioTestFt8Input (qint64 frames); bool configureLiveAudioTestHandoff (); quint64 liveAudioTestPublishedDecoderGeneration () const { return m_automated_test && DecodeOwner::Jt9 == m_decodeOwner - && m_activeJt9Decode.generation == m_nextDecoderGeneration + && m_decoderSession.accepts (m_activeJt9Decode.generation) ? m_activeJt9Decode.generation : 0; } quint64 liveAudioTestDecodeCycleGeneration () const {return m_decodeCycleGeneration;} quint64 liveAudioTestReceiveEpoch () const {return m_receiveConsumer.epoch ();} bool liveAudioTestReceivingAudio () const {return m_receivingAudio;} + QString checkLiveAudioTestJttyFrequencyChanges(); + bool startLiveAudioTestJttyWav(QString const& path); + QString checkLiveAudioTestJttyMailboxOverflow(); + QString checkLiveAudioTestJttyDrain(); + bool liveAudioTestJttyStreamActive () const + { + return m_jttyTxStream && m_jttyTxStream->isActive (); + } LiveAudioTestFt8TransmitRequest startLiveAudioTestFt8Transmit ( qint64 targetPeriodStartMs); #endif @@ -306,7 +321,7 @@ public: void msgAvgDecode2(); void fastPick(int x0, int x1, int y); void skedFreq(double sf); - void jttyDecodeAgainAt(float secondsAgo); + void jttyDecodeAgainAtSample(quint64 reception, qint64 sample); private: enum class DecodeOwner @@ -330,6 +345,7 @@ private: Terminating, Killing, ReplacementStarting, + Failed, Closing }; @@ -344,15 +360,13 @@ private: { qint32 generation {0}; DecodeOperatingContext context; - bool copiedSamples {false}; bool obsolete {false}; Ft8MtdDecodeCoordinator::Stage ft8Stage {Ft8MtdDecodeCoordinator::Stage::None}; qint64 ft8Period {-1}; }; static constexpr int MaxActiveStationRows = 50; - // Keep this matched with MAX_CALLERS in the Q65 q3list Fortran helpers. - static constexpr int MaxQ65PileupCallers = 50; + static constexpr int MaxQ65PileupCallers = Q65_CALLER_CAPACITY; void change_layout (std::size_t) override; void keyPressEvent (QKeyEvent *) override; @@ -619,6 +633,7 @@ private slots: void on_cbMenus_toggled(bool b); void on_cbAutoSeq_toggled(bool b); void on_cbIncludeTime_toggled(bool b); + void on_cbLowerCase_toggled(bool); void networkError (QString const&); void on_ClrAvgButton_clicked(); void on_actionWSPR_triggered(); @@ -645,6 +660,7 @@ private slots: void on_sbTR_FST4W_valueChanged (int); void on_sbFtol_valueChanged (int); void on_sbFtol_2_valueChanged (int); + void on_comboBoxJttyStyle_currentIndexChanged (int index); void on_cbFast9_clicked(bool b); void on_sbCQTxFreq_valueChanged(int n); void on_cbCQTx_toggled(bool b); @@ -683,7 +699,6 @@ private slots: void on_rbEchoCW_toggled(bool b); void on_leEchoMessage_textChanged(); void on_pbSendMessage_clicked(); - void on_Tx_Message_returnPressed(); void on_pbF1_clicked(); void on_pbF2_clicked(); @@ -759,6 +774,10 @@ private: Q_SIGNAL void sendMessage (TxEvidence::TxRequest, SoundOutput *) const; Q_SIGNAL void startJttyStream (TxEvidence::TxRequest, SoundOutput *); Q_SIGNAL void endJttyStream () const; + Q_SIGNAL void clearJttyStream (TxAudioQueueEpoch epoch) const; + Q_SIGNAL void enqueueJttyStream (QByteArray const& samples, + TxAudioQueueEpoch epoch, + qint64 enqueueId) const; Q_SIGNAL void outAttenuationChanged (qreal) const; Q_SIGNAL void toggleShorthand () const; Q_SIGNAL void reset_audio_input_stream (bool report_dropped_frames) const; @@ -772,7 +791,9 @@ private: void recordTxSourceCommit (TxEvidence::TxStartSnapshot const& snapshot); void recordRawTxPlayout (TxEvidence::TxRawPlayoutSnapshot const& snapshot); void noteTxStopReason (TxEvidence::TxStopReason reason); + void requestTxStop (TxEvidence::TxStopReason reason); void noteTxModeChange (QString const& mode); + void updateModeControlLock (); int txStopTailMs (bool tciAudio) const; void stopTxEvidence (int tailMs); void captureJttyTxEvidenceTotals (qint64 servedSamples, qint64 totalSamples, @@ -796,7 +817,22 @@ private: void abortSuperFoxTxStart(); void displayFoxTxMsgs(); void jtty_tx(QString message); - void submitJttyDraft(QString message); + void commitJttyLiveEntry(); + void startJttyLiveStream(); + void autoAdvanceJttyLiveEntry(); + void idleFlushJttyLiveEntry(); + bool commitJttyLiveEntryPlan(bool forceFlush, int holdbackWords, bool isFinal); + void sendJttyFillerPadding(); + void clearJttyLiveEntry(); + void insertJttyLiveEntryText(QString const& text); + void insertJttyChatOpener(); + void insertJttyChatSignoff(); + void applyJttyLiveEntryFormatting(); + void guardJttyLiveEntryLock(); + void updateJttyLiveEntryFrameLabel(); + double jttyRequestSentFraction(qint64 requestId) const; + int jttyRequestFramesDone(qint64 requestId) const; + int countJttyTransmitFrames(QString const& preparedMessage) const; #ifdef WIN32 void handleMmttyTxString(QString message); void handleMmttyStartTx(); @@ -808,45 +844,68 @@ private: void handleMmttyJttySessionDrained(qint64 sessionId); void completeMmttyJttyOutput(bool drained = false); void startPendingMmttyJttyTx(); + void beginMmttyHandoff(); + void resumeMmttyHandoff(); + void handleMmttyHandoffTimeout(); + void finalizeMmttyExternalAbort(); + bool mmttyNeedsHandoff() const; QString jttyRejectReasonText(JttyTxRejectReason reason) const; #endif - void execute_jtty_tx(qint64 requestId, QString message); + void execute_jtty_tx(qint64 requestId, QString message, bool isFinal = true); void execute_jtty_tones(qint64 requestId, QString const& message, - int const itone[], int nsym); - void advanceJttyTxQueueEpoch(); + int const itone[], int nsym, int frequency = -1); + void enqueueJttySegments(qint64 requestId, QVector<Jtty::TransmitSegment> segments); + void enqueueJttyToneSegment(qint64 requestId, QString const& message, + int const tones[], int toneCount); + void feedJttyTransmitQueue(); + void updateJttyTransmitDisplay(qint64 servedSamples); + void updateJttySendButton(); + void onJttyBackendProgress(TxAudioQueueProgress progress); qint64 jttyTxCommittedSamples() const; void completeJttyTxEnqueue(qint64 requestId, QString const& message, TxAudioQueueProgress progress, bool newSession, bool useTciAudio); - void recordAcceptedJttyTextRequest(qint64 requestId, qint64 endSample); - QVector<qint64> takeCompletedJttyTextRequests(TxAudioQueueEpoch epoch, - qint64 totalAtDrain); - void clearAcceptedJttyTextRequests(TxAudioQueueEpoch epoch); void handleJttyContestSerial(QString const& message); void abort_jtty_tx(); void interruptJttyTx(); - void rejectPendingJttyTciMessages(JttyTxRejectReason reason); + void rejectPendingJttyMessages(JttyTxRejectReason reason); void sync_tci_tx_volume (bool force = false); void onJttyBackendDrained(TxAudioQueueDrainState drain); + void finishJttyDrain(JttyTxLifecycle::Drain const& drain); void onJttyBackendEnqueueAccepted(qint64 enqueueId, qint64 sampleCount, TxAudioQueueProgress progress); - void onJttyBackendEnqueueFailed(TxAudioQueueEpoch epoch, qint64 enqueueId); + void onJttyBackendEnqueueFailed(TxAudioQueueEpoch epoch, qint64 enqueueId, + TxAudioQueueEnqueueFailure failure); + void handleJttyEnqueueTimeout(); void handleJttyTxWatchdog(); - void resetJttyTxState(); void startJttyTxWatchdog(int durationMs); - void jtty_save_wav(); bool jtty_key_struck(QKeyEvent * e); bool sendJttyFunctionKey(int index); - // istart0/istop (sample indices into dec_data.d2) bound the Fortran scan - // to a window instead of the whole buffer; -1/-1 (the default) means - // unwindowed, matching the original behavior exactly. Returns true when - // this call delivers a completed message admitted to the QSO history. - bool jtty_decode(int k, int istart0 = -1, int istop = -1); - void renderJttyAllFreqLines(); - void renderJttyQsoLines(); + struct JttyReceiveState; + std::shared_ptr<JttyReceiveState> m_jttyReceive; + void initializeJttyReceive(); + void consumeJttyAudio(JttyReceiveMailboxPtr mailbox); + void pumpJttyReceive(); + void refreshJttyReceiveLines(); + void cancelJttyReview(); + void finishJttyReception(); + void restartJttyReception(); + void startJttyReview(quint64 reception, qint64 sample, bool picked); + void decodeJttyDisk(int k); + void finishJttyDisk(); + void updateJttyReceivePolicy(bool continuous); + void updateJttyReceiveContext(); + void updateJttySavePolicy(); + void beginJttyDisk(); + bool jttyReviewBusy() const; + bool jttyDrainInProgress() const; + bool jttyDiskActive() const; + void closeAfterJttyDrain(); + bool m_discardJttyWavLoad = false; + void drainJttyReceive(); void jtty_again(); - void flushJttyDecodeLines(); QString jtty_msg_expand(QString msg); + int jttySnrForSelectedWord(QString const& word, bool leftPane) const; QString specOpLabel() const; void initializeFFT(int nsps); void initializeFFT(int nsps, int fftSize); @@ -917,6 +976,7 @@ private: QScopedPointer<CabrilloLogWindow> m_contestLogWindow; QScopedPointer<ColorHighlighting> m_colorHighlighting; Transceiver::TransceiverState m_rigState; + QPointer<MessageBox> m_swrWarning; Frequency m_lastDialFreq; QString m_lastBand; QString m_lastCallsign; @@ -1006,6 +1066,8 @@ private: qint32 m_idleMinutes; qint32 m_nSubMode; qint32 m_nclearave; + bool m_jt65ClearAveragesPending {true}; + bool m_q65ClearAveragesPending {true}; qint32 m_minSync; qint32 m_dBm; qint32 m_nWSPRdecodes; @@ -1048,7 +1110,7 @@ private: qint32 m_position; qint64 m_decoderDiagSequence=0; qint64 m_decoderDiagActiveSequence=0; - qint32 m_nextDecoderGeneration=0; + DecoderIpc::InputState m_decoderInput; qint32 m_decoderDiagStartIhsym=0; qint32 m_decoderDiagStartHsymStop=0; qint32 m_decoderDiagStartNzhsym=0; @@ -1074,7 +1136,6 @@ private: bool m_decoderDiagHardHangLogged=false; bool m_decoderDiagAbnormalClear=false; bool m_decoderCompletedSinceStart=false; - bool m_jt9PayloadValid=false; bool m_closing=false; bool m_txFirst; bool m_tx1_enabled_preference {true}; @@ -1194,6 +1255,7 @@ private: QLabel last_tx_label; QLabel auto_tx_label; QLabel band_hopping_label; + QLabel swr_label; QLabel ndecodes_label; QProgressBar progressBar; QLabel watchdog_label; @@ -1247,6 +1309,7 @@ private: QTimer splashTimer; QTimer p1Timer; QTimer m_jttyTxWatchdog; + QTimer m_jttyEnqueueWatchdog; QTimer m_refSpecTimer; AutoRespondSelectionLatch m_autoRespondSelectionLatch; AutoRespondScores m_autoRespondScores; @@ -1257,6 +1320,8 @@ private: QString m_baseCall; QString m_hisCall; QString m_hisGrid; + int m_jttyHisCallSnr = -10; // SNR of the decode selected as DX call, for %R; cleared when the DX call changes + int m_jttyMessageStyle = 0; // Jtty::MessageStyle: 0=Contest, 1=Ft8 (see JttyMessages.hpp) QString m_appDir; QString m_cqStr; QString m_palette; @@ -1378,7 +1443,7 @@ private: QDateTime m_dateTimeBestSP; QDateTime m_dateTimeSeqStart; //Nominal start time of Rx sequence about to be decoded - QSharedMemory *mem_jt9; + DecoderIpc::Session& m_decoderSession; QString m_QSOText; unsigned m_downSampleFactor; QThread::Priority m_audioThreadPriority; @@ -1401,11 +1466,9 @@ private: qint64 m_liveAudioTestFt8StartSessionId {-1}; qint64 m_liveAudioTestFt8StartGeneration {-1}; #endif - bool m_jttyTxActive; - bool m_jttyTxUsesTciAudio; - TxAudioQueueEpoch m_jttyTxQueueEpoch; - TxAudioQueueProgress m_jttyTxQueueProgress; - struct PendingJttyTciMessage + JttyTxLifecycle m_jttyTxLifecycle; + JttyTxLifecycle::StopContext m_delayedJttyStopContext; + struct PendingJttyMessage { TxAudioQueueEpoch epoch; qint64 enqueueId; @@ -1414,48 +1477,38 @@ private: QString message; bool newSession; }; - QVector<PendingJttyTciMessage> m_pendingJttyTciMessages; - struct AcceptedJttyTxRequest - { - TxAudioQueueEpoch epoch; - qint64 requestId; - qint64 endSample; - }; - QVector<AcceptedJttyTxRequest> m_acceptedJttyTxRequests; - JttyDraftAcceptanceTracker m_jttyDraftAcceptanceTracker; + QVector<PendingJttyMessage> m_pendingJttyMessages; + Jtty::TransmitQueue m_jttyTransmitQueue; + TxAudioQueueProgress m_jttyQueueProgress; + bool m_feedingJttyTransmitQueue {false}; + qint64 m_jttyDisplayedEndSample {0}; + QString m_jttyQueueNotice; + bool m_jttyLiveEntryArmed {false}; + bool m_guardingJttyLiveEntryLock {false}; + int m_jttyLiveEntryCommitted {0}; // Tx_Message chars already sent/queued; locked against edits. + QString m_jttyLiveEntryLockedText; // cached committed prefix, to detect edits that touch it + struct PendingLiveEntryCommit { qint64 requestId; int start, end; int totalFrames {0}; }; + // Committed spans not yet confirmed fully transmitted; drives progressive sent/queued coloring and reject-triggered unlocking. + QVector<PendingLiveEntryCommit> m_jttyLiveEntryPending; + // Frames from commits that have fully drained since the box was last cleared; the frame-count label adds this to still-pending progress. + int m_jttyLiveEntryFramesSent {0}; + // Fires a batch flush of whatever's safely committable after a short typing pause, so auto-advance doesn't wait indefinitely for kJttyAutoAdvanceBatchWords to pile up on a short message. + QTimer m_jttyAutoAdvanceIdleTimer; qint64 m_jttyTxRequestId; - qint64 m_jttyTciEnqueueId; - struct JttyQsoLine - { - qint64 messageId {0}; - float frequency {0.f}; - QString text; - float sequenceStart {0.f}; - QDateTime messageStartUtc; - }; - QVector<JttyQsoLine> m_jttyQsoLines; - QTextBlock m_jttyQsoGroupStart; - QTextBlock m_jttyQsoGroupEnd; - int m_jttyQsoGroupEndPosition {-1}; - bool m_jttyQsoRenderedLowerCase {false}; - bool m_jttyQsoRenderedIncludeTime {false}; - struct JttyDecodeLine - { - qint64 messageId {0}; - float frequency {0.f}; - QString text; - float sequenceStart {0.f}; - QDateTime messageStartUtc; - bool complete {false}; - bool written {false}; - DecodeOperatingContext context; - }; - QVector<JttyDecodeLine> m_jttyAllFreqLines; - int m_jttyLastAllFreqsK = -1; // detects a restarted decode (new WAV, or "decode again") - qint32 m_jttyLastSavedWavK0 = -1; // m_k0 at last JTTY WAV save; skips saving unchanged audio again - QTextBlock m_jttyAllFreqsGroupStart; // start of decodedTextBrowser's currently-growing group + qint64 m_jttyEnqueueId; #ifdef WIN32 Jtty::N1mmOutput m_mmttyJttyOutput; + struct PendingMmttyJttyMessage + { + qint64 requestId; + QString message; + QVector<int> tones; + bool literal {false}; + }; + QVector<PendingMmttyJttyMessage> m_pendingMmttyJttyMessages; + Jtty::MmttyHandoff m_mmttyHandoff; + QTimer m_mmttyHandoffWatchdog; + bool m_preserveMmttyOutputDuringStop {false}; #endif bool m_block_pwr_tooltip; bool m_PwrBandSetOK; @@ -1488,6 +1541,9 @@ private: quint32 hold_rx, quint32 release_rx, quint32 expiries, quint32 invalid); void startTxAudioAfterPttDelay (); + void updateRigMeters (Transceiver::TransceiverState const&); + bool stopForHighSWR (Transceiver::TransceiverState const&); + void showHighSWRWarning (unsigned swr); void updateStatusBar(); void updateMainWindowAccessibility(); void registerMainWindowFocusControls(); @@ -1664,10 +1720,11 @@ private: DecodePublishResult publishPendingFt8Decode (); void decode (Ft8MtdDecodeCoordinator::Stage stage, qint64 ft8Period = -1); qint64 currentFt8DecodePeriod () const; + void beginDecoderInput (); bool usesFt8MtdFinal () const; int configuredFt8MtdEarlyStageCount () const; std::unique_ptr<Ft8MtdDecodeCoordinator::PendingMtdDecode> - capturePendingFt8MtdDecode (qint64 period) const; + capturePendingFt8MtdDecode (qint64 period); void cancelPendingFt8Decode (QString const& reason); void reportFt8BackpressureDecision ( Ft8MtdDecodeCoordinator::Decision const& decision, qint64 period); @@ -1683,6 +1740,7 @@ private: bool activeDecodeOperatingContextMatchesCurrent() const; bool initializeDecoderSharedMemory(); void startDecoderProcess(); + void failDecoderStartup(QString const& reason); bool beginDecode( DecodeOwner owner, decoder_params_t const * diagnosticParams = nullptr, DecodeOperatingContext const * diagnosticContext = nullptr); diff --git a/widgets/mainwindow.ui b/widgets/mainwindow.ui index 0353de83..719aecae 100644 --- a/widgets/mainwindow.ui +++ b/widgets/mainwindow.ui @@ -3976,6 +3976,33 @@ Double-click to reset to the standard 73 message</string> </item> <item row="2" column="0" colspan="3"> <layout class="QGridLayout" name="gridLayout_4"> + <item row="0" column="0"> + <widget class="QLabel" name="label_jttyStyle"> + <property name="text"> + <string>Message style </string> + </property> + <property name="alignment"> + <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set> + </property> + </widget> + </item> + <item row="0" column="1"> + <widget class="QComboBox" name="comboBoxJttyStyle"> + <property name="toolTip"> + <string>Choose the F1-F8 message template set: Contest style (exchange-oriented) or FT8 style (chat-QSO-oriented).</string> + </property> + <item> + <property name="text"> + <string>Contest</string> + </property> + </item> + <item> + <property name="text"> + <string>FT8</string> + </property> + </item> + </widget> + </item> <item row="8" column="0"> <spacer name="verticalSpacer_8"> <property name="orientation"> @@ -4037,20 +4064,34 @@ Double-click to reset to the standard 73 message</string> </widget> </item> <item row="1" column="0"> - <widget class="QPushButton" name="pbSendMessage"> - <property name="minimumSize"> - <size> - <width>0</width> - <height>0</height> - </size> - </property> - <property name="toolTip"> - <string>Send and clear the message. Press Enter in the field.</string> - </property> - <property name="text"> - <string>Send message</string> - </property> - </widget> + <layout class="QVBoxLayout" name="verticalLayout_jttySend"> + <item> + <widget class="QPushButton" name="pbSendMessage"> + <property name="minimumSize"> + <size> + <width>0</width> + <height>0</height> + </size> + </property> + <property name="toolTip"> + <string>Send and clear the message. Press Enter in the field.</string> + </property> + <property name="text"> + <string>Send message</string> + </property> + </widget> + </item> + <item> + <widget class="QLabel" name="labelJttyFrameCount"> + <property name="alignment"> + <set>Qt::AlignHCenter</set> + </property> + <property name="toolTip"> + <string>JTTY frames sent / total frames required for the current message.</string> + </property> + </widget> + </item> + </layout> </item> <item row="2" column="0"> <widget class="QLabel" name="label_3"> @@ -4075,9 +4116,18 @@ Double-click to reset to the standard 73 message</string> </widget> </item> <item row="1" column="1" colspan="4"> - <widget class="QLineEdit" name="Tx_Message"> + <widget class="QPlainTextEdit" name="Tx_Message"> + <property name="maximumSize"> + <size> + <width>16777215</width> + <height>60</height> + </size> + </property> + <property name="tabChangesFocus"> + <bool>true</bool> + </property> <property name="toolTip"> - <string>Press Enter to send and clear the message.</string> + <string>Ctrl+K sends now (one-shot). Alt+J starts a live session that keeps sending as you type, until Alt+K signs off. Ctrl+Shift+K clears the box. Ctrl+H inserts a chat opener.</string> </property> </widget> </item> diff --git a/widgets/mainwindow_jtty.cpp b/widgets/mainwindow_jtty.cpp index 91058f4d..bd19b584 100644 --- a/widgets/mainwindow_jtty.cpp +++ b/widgets/mainwindow_jtty.cpp @@ -1,1176 +1,1479 @@ -#include "mainwindow.h" -#include "ui_mainwindow.h" -#include "widegraph.h" -#include "commons.h" -#include "JttyMessages.hpp" -#include "JttyN1mm.hpp" -#include "JttyReplay.hpp" -#include "Logger.hpp" -#include <QByteArray> -#include <QDateTime> -#include "Modulator/Modulator.hpp" -#include <algorithm> -#include <array> -#include <iostream> -#include <vector> -#ifdef WIN32 -#include "MMTTYIF.hpp" -#undef MessageBox -#endif - - -extern dec_data_t& dec_data; -extern qint32 g_iptt; - -namespace -{ - Jtty::NativeExchangeProfile jttyExchangeProfile(Configuration const& configuration) - { - switch (configuration.special_op_id()) { - case Configuration::SpecialOperatingActivity::FIELD_DAY: - return Jtty::NativeExchangeProfile::FieldDay; - case Configuration::SpecialOperatingActivity::RTTY: - return Jtty::NativeExchangeProfile::RttyRoundup; - default: - return Jtty::NativeExchangeProfile::None; - } - } - - Jtty::NativeMacroContext jttyNativeMacroContext( - Configuration const& configuration, QString const& hisCall, int serialNumber) - { - Jtty::NativeMacroContext context; - context.myCall = configuration.my_callsign(); - context.hisCall = hisCall; - context.serialNumber = serialNumber; - context.grid = configuration.my_grid(); - context.exchangeProfile = jttyExchangeProfile(configuration); - - switch (context.exchangeProfile) { - case Jtty::NativeExchangeProfile::FieldDay: - context.configuredExchange = Jtty::normalizedFieldDayExchange( - configuration.Field_Day_Exchange()); - break; - case Jtty::NativeExchangeProfile::RttyRoundup: - context.configuredExchange = configuration.RTTY_Exchange(); - break; - default: - break; - } - return context; - } - - QString jttyNativeEncodeError(int status) - { - if (status == static_cast<int>(Jtty::NativeEncodeStatus::UnknownSection)) { - return QStringLiteral("Field Day section is not registered in the ARRL/RAC table"); - } - return QStringLiteral("native atom encoding failed"); - } -} - -#define FCL fortran_charlen_t - -namespace -{ - constexpr int jttyMaxUpdates = 30; - constexpr int jttyMessageSize = Jtty::maxMessageLength; - constexpr int jttyUpdateBufferSize = jttyMaxUpdates * jttyMessageSize; - - QString formatJttyDecodeLine (float frequency, QString const& message) - { - QString const frequencyText = QStringLiteral("%1").arg(qRound(frequency), 4); - return message.isEmpty() ? frequencyText : frequencyText + QStringLiteral(" ") + message; - } -} - -extern "C" { - void rjtty_sub_(short int d2[], int* k, int* nsps, int* nfa, int*nfb, - float* f0, float* ftol); - - // Bounds the scan to [istart0,istop] (sample indices into d2) instead of - // the whole buffer -- see MainWindow::jtty_decode_windowed(). - void rjtty_sub_windowed_(short int d2[], int* k, int* nsps, int* nfa, int*nfb, - float* f0, float* ftol, int* istart0, int* istop); - - void jtty_get_updates_(char text_blocks[], qint64 message_ids[], - float frequencies[], float start_tsync[], bool eom[], - int* count, fortran_charlen_t); - - void genjtty_profile_(char * msg, int const* exchange_profile, - int itone[], int* nsym, fortran_charlen_t); - void genjtty_atoms_c(Jtty::NativeAtomDescriptor const atoms[], int natoms, - int itone[], int* nsym, int* status); - - void gen_jttywave_(int itone[], int* nsym, int* nsps, float* bt, float* fsample, float* f0, - float xjunk[], float wave[], int* icmplx, int* nwave); -} - -#ifdef WIN32 -static QString append_separator(QString message) { - if (!message.isEmpty()) { - QChar lastChar = message.at(message.length() - 1); - if (lastChar != '\r' && lastChar != '\n' && lastChar != ' ') { - message += "\r\n"; - } - } - return message; -} -#endif - -void MainWindow::jtty_save_wav() -{ - // Reject callers that arrive before a real JTTY capture exists; m_k0 is - // still the initial sentinel, or is stale from an earlier interval. - if (!Jtty::wavCaptureValid (m_k0)) return; - if (m_k0 == m_jttyLastSavedWavK0) return; //Guard against re-saving same audio under a new timestamp - m_jttyLastSavedWavK0 = m_k0; - - //Save JTTY data to a .wav file - QDateTime now {QDateTime::currentDateTimeUtc ()}; - qint64 ms = m_k0/12; - auto const& tstart=now.addMSecs(-ms); - m_fnameWE=m_config.save_directory().absoluteFilePath (tstart.toString("yyMMdd_hhmmss")); - int samples=m_k0; - QString dgrd = "jtty"; - save_wave_file (m_fnameWE, samples, m_freqNominalPeriod, dgrd); - // "Save decoded" keeps the file only if something was decoded; give the - // decoder a further 3 seconds to finish before killWaveFile() decides. - if (m_saveDecoded) killFileTimer.start (3000); -} - -void MainWindow::updateJttyDecodeHeadings() -{ - QString const prefix = ui->cbIncludeTime->isChecked() - ? QStringLiteral(" UTC Freq ") : QStringLiteral("Freq "); - ui->lh_decodes_headings_label->setText(prefix + tr ("Message")); - ui->rh_decodes_headings_label->setText(prefix + tr ("Message")); -} - -void MainWindow::on_cbIncludeTime_toggled(bool) -{ - if (m_mode == "JTTY") { - updateJttyDecodeHeadings(); - renderJttyAllFreqLines(); - renderJttyQsoLines(); - } -} - -void MainWindow::renderJttyAllFreqLines() -{ - if (m_jttyAllFreqLines.isEmpty()) return; - - QStringList displayLines; - for (auto const& line : m_jttyAllFreqLines) { - QString displayLine = formatJttyDecodeLine ( - line.frequency, Jtty::wrapMessage (line.text)); - if (ui->cbLowerCase->isChecked ()) displayLine = displayLine.toLower (); - if (ui->cbIncludeTime->isChecked ()) { - QString const time = Jtty::jttyLineTimeLabel (line.messageStartUtc); - if (!time.isEmpty ()) displayLine = time + " " + displayLine; - } - displayLines.append (displayLine); - } - - QTextCharFormat format; - format.setFont (ui->decodedTextBrowser->contentFont ()); - - QTextCursor cursor = ui->decodedTextBrowser->textCursor (); - if (m_jttyAllFreqsGroupStart.isValid ()) { - cursor.setPosition (m_jttyAllFreqsGroupStart.position ()); - cursor.movePosition (QTextCursor::End, QTextCursor::KeepAnchor); - cursor.removeSelectedText (); - } else { - cursor.movePosition (QTextCursor::End); - if (cursor.position () > 0) cursor.insertBlock (); - } - m_jttyAllFreqsGroupStart = cursor.block (); - cursor.insertText (displayLines.join (QChar {'\n'}), format); - ui->decodedTextBrowser->setTextCursor (cursor); - ui->decodedTextBrowser->ensureCursorVisible (); -} - -void MainWindow::renderJttyQsoLines() -{ - if (m_jttyQsoLines.isEmpty ()) { - m_jttyQsoRenderedLowerCase = ui->cbLowerCase->isChecked (); - m_jttyQsoRenderedIncludeTime = ui->cbIncludeTime->isChecked (); - return; - } - - QTextCursor cursor = ui->decodedTextBrowser2->textCursor (); - if (m_jttyQsoGroupStart.isValid () && m_jttyQsoGroupEnd.isValid () - && m_jttyQsoGroupEndPosition >= m_jttyQsoGroupStart.position ()) { - cursor.setPosition (m_jttyQsoGroupStart.position ()); - cursor.setPosition (m_jttyQsoGroupEndPosition, QTextCursor::KeepAnchor); - cursor.removeSelectedText (); - } else { - cursor.movePosition (QTextCursor::End); - if (cursor.position () > 0) cursor.insertBlock (); - } - - QTextCharFormat format; - format.setFont (ui->decodedTextBrowser2->contentFont ()); - m_jttyQsoGroupStart = cursor.block (); - QStringList renderedLines; - for (auto const& line : m_jttyQsoLines) { - QString display = formatJttyDecodeLine ( - line.frequency, Jtty::wrapMessage (line.text)); - if (ui->cbLowerCase->isChecked ()) display = display.toLower (); - if (ui->cbIncludeTime->isChecked ()) { - QString const time = Jtty::jttyLineTimeLabel (line.messageStartUtc); - if (!time.isEmpty ()) display = time + " " + display; - } - renderedLines.append (display); - } - cursor.insertText (renderedLines.join (QChar {'\n'}), format); - m_jttyQsoGroupEnd = cursor.block (); - m_jttyQsoGroupEndPosition = cursor.position (); - ui->decodedTextBrowser2->setTextCursor (cursor); - m_jttyQsoRenderedLowerCase = ui->cbLowerCase->isChecked (); - m_jttyQsoRenderedIncludeTime = ui->cbIncludeTime->isChecked (); -} - -bool MainWindow::jtty_decode(int k, int istart0, int istop) -{ - auto jttyLineDateTimeUtc = [this, k] (float tsync) -> QDateTime { - if (m_diskData && m_UTCdiskDateTime.isValid()) { - return m_UTCdiskDateTime.addMSecs(qRound64(1000.0 * tsync)).toUTC(); - } - double const elapsed = qMax(0.0, double(k) / 12000.0 - double(tsync)); - return QDateTime::currentDateTimeUtc().addMSecs(-qRound64(1000.0 * elapsed)); - }; - auto jttyLineDisplayDateTimeUtc = [this, &jttyLineDateTimeUtc] (float tsync) -> QDateTime { - if (m_diskData) { - return Jtty::jttyLineStartTimeUtc (m_UTCdiskDateTime, m_UTCdisk, tsync); - } - return jttyLineDateTimeUtc (tsync); - }; - int nsps=384; - // A non-advancing sample position starts a distinct displayed decode session. - bool const newAllFreqsSession = (k <= m_jttyLastAllFreqsK); - m_jttyLastAllFreqsK = k; - if (newAllFreqsSession) { - flushJttyDecodeLines(); - m_jttyAllFreqsGroupStart = QTextBlock(); - m_jttyQsoGroupStart = QTextBlock(); - m_jttyQsoGroupEnd = QTextBlock(); - m_jttyQsoGroupEndPosition = -1; - m_jttyQsoLines.clear(); - m_jttyAllFreqLines.clear(); - m_bDecoded = false; - m_jttyLastSavedWavK0 = -1; - } - float f0 = ui->RxFreqSpinBox_2->value(); - float ftol = ui->sbFtol_2->value(); - int nfa = m_wideGraph->nStartFreq(); - int nfb = m_wideGraph->Fmax(); - - if (istart0 < 0) { - rjtty_sub_(dec_data.d2,&k,&nsps,&nfa,&nfb,&f0,&ftol); - } else { - rjtty_sub_windowed_(dec_data.d2,&k,&nsps,&nfa,&nfb,&f0,&ftol,&istart0,&istop); - } - - QVector<Jtty::MessageUpdate> updates; - int updateCount {0}; - do { - std::array<char, jttyUpdateBufferSize> textBlocks {}; - std::array<qint64, jttyMaxUpdates> messageIds {}; - std::array<float, jttyMaxUpdates> frequencies {}; - std::array<float, jttyMaxUpdates> sequenceStarts {}; - std::array<bool, jttyMaxUpdates> complete {}; - jtty_get_updates_(textBlocks.data(), messageIds.data(), frequencies.data(), - sequenceStarts.data(), complete.data(), &updateCount, - (FCL)jttyUpdateBufferSize); - for (int i = 0; i < updateCount; ++i) { - QString const text = QString::fromLatin1( - textBlocks.data() + i * jttyMessageSize, jttyMessageSize).trimmed(); - if (messageIds[i] <= 0) continue; - updates.append({messageIds[i], frequencies[i], text, - sequenceStarts[i], complete[i]}); - } - } while (updateCount == jttyMaxUpdates); - - bool const allHistoryChanged = Jtty::mergeMessageUpdates( - m_jttyAllFreqLines, updates, - [this, &jttyLineDateTimeUtc, &jttyLineDisplayDateTimeUtc] (Jtty::MessageUpdate const& update) { - JttyDecodeLine decodeLine; - decodeLine.messageId = update.messageId; - decodeLine.frequency = update.frequency; - decodeLine.text = update.text; - decodeLine.sequenceStart = update.sequenceStart; - decodeLine.messageStartUtc = jttyLineDisplayDateTimeUtc (update.sequenceStart); - decodeLine.complete = update.complete; - decodeLine.context = currentDecodeOperatingContext(); - decodeLine.context.sequenceStart = jttyLineDateTimeUtc(update.sequenceStart); - return decodeLine; - }); - - if (allHistoryChanged) renderJttyAllFreqLines (); - - for (auto& known : m_jttyAllFreqLines) { - if (known.complete && !known.written) { - write_all("Rx", formatJttyDecodeLine(known.frequency, known.text), &known.context); - known.written = true; - } - } - - bool const qsoDisplayOptionsChanged = !m_jttyQsoLines.isEmpty() - && (m_jttyQsoRenderedLowerCase != ui->cbLowerCase->isChecked() - || m_jttyQsoRenderedIncludeTime != ui->cbIncludeTime->isChecked()); - bool anyEom {false}; - bool anyLineChanged {false}; - for (auto const& update : updates) { - auto known = std::find_if(m_jttyQsoLines.begin(), m_jttyQsoLines.end(), - [&update] (JttyQsoLine const& line) { - return line.messageId == update.messageId; - }); - bool const alreadyPresent = known != m_jttyQsoLines.end(); - if (!Jtty::shouldApplyToQsoHistory( - alreadyPresent, update.frequency, f0, ftol)) { - continue; - } - if (update.complete) anyEom = true; - - QString delta; -#ifdef WIN32 - bool startNew{false}; //Set to "true" when N1MM should start display of text on a new line -#endif - if (alreadyPresent) { - auto const change = Jtty::compareMessages(known->text, update.text); - bool const frequencyChanged = known->frequency != update.frequency; - if (!change.messageChanged && !frequencyChanged) continue; - if (change.messageChanged) { - if (change.extendsMessage) { - delta = change.appendedText; -#ifdef WIN32 - startNew = change.startsMessage; -#endif - } else { - delta = update.text; -#ifdef WIN32 - startNew = true; -#endif - } - } - known->frequency = update.frequency; - known->text = update.text; - } else { -#ifdef WIN32 - startNew = true; -#endif - delta = update.text; - auto const allLine = std::find_if ( - m_jttyAllFreqLines.cbegin (), m_jttyAllFreqLines.cend (), - [&update] (JttyDecodeLine const& line) { - return line.messageId == update.messageId; - }); - QDateTime const messageStartUtc = allLine != m_jttyAllFreqLines.cend () - ? allLine->messageStartUtc - : jttyLineDisplayDateTimeUtc (update.sequenceStart); - m_jttyQsoLines.append({update.messageId, update.frequency, update.text, - update.sequenceStart, messageStartUtc}); - } - anyLineChanged = true; - m_bDecoded = true; - -#ifdef WIN32 - if (m_mmttyif && !delta.isEmpty()) { -// m_mmttyif->echo_message_to_n1mm(append_separator(delta)); - if(ui->cbLowerCase->isChecked()) delta = delta.toLower(); - if(startNew) delta = "\r\n" + delta; - m_mmttyif->echo_message_to_n1mm(delta); - } -#endif - } - - if (anyLineChanged || qsoDisplayOptionsChanged) renderJttyQsoLines (); - return anyEom; -} - -void MainWindow::jtty_tx(QString message) -{ - // Render and enqueue immediately; the shared transmit buffer chains messages - // gaplessly while playback is underway. - submitJttyText(message); -} - -qint64 MainWindow::submitJttyText(QString message) -{ - qint64 const requestId = ++m_jttyTxRequestId; - execute_jtty_tx(requestId, message); - return requestId; -} - -void MainWindow::submitJttyDraft(QString message) -{ - if (m_jttyDraftAcceptanceTracker.hasPendingSubmissionForCurrentDraft ()) { - ui->Tx_Message->selectAll (); - return; - } - - qint64 const requestId = ++m_jttyTxRequestId; - m_jttyDraftAcceptanceTracker.trackSubmission (requestId); - execute_jtty_tx (requestId, message); - if (m_jttyDraftAcceptanceTracker.isPending (requestId)) { - ui->Tx_Message->selectAll (); - } -} - -void MainWindow::execute_jtty_tx(qint64 requestId, QString message) -{ - int itone[944]; - // Captured before anything below can change m_jttyTxActive: true means - // this message is being queued behind one still transmitting, not - // starting a fresh session. - bool const isChainedMessage = m_jttyTxActive; - if(ui->cbLowerCase->isChecked()) message = message.toLower(); - - auto const preparedMessage = Jtty::prepareTransmitText(message); - if (preparedMessage.changed()) { - LOG_WARN("JTTY transmit message was normalized or shortened before encoding"); - } - message = preparedMessage.text; - if (message.isEmpty()) { - Q_EMIT jttyTextRejected(requestId, JttyTxRejectReason::Empty); - return; - } - - // Keep message as the logical text; the chained leading space is only - // transport spacing and must not leak into logging, display, or the contest - // serial check in completeJttyTxEnqueue. - auto transmitFrame = Jtty::transmitFrame(message, isChainedMessage).toLatin1(); - - int nsym=0; - int const exchangeProfile = static_cast<int>(jttyExchangeProfile(m_config)); - genjtty_profile_(transmitFrame.data(), &exchangeProfile, - &itone[0], &nsym, (FCL)80); - if (nsym <= 0) { - LOG_WARN("JTTY transmit message could not be encoded"); - Q_EMIT jttyTextRejected(requestId, JttyTxRejectReason::EncodingFailed); - return; - } - - message = QString::fromLatin1(transmitFrame).trimmed(); - execute_jtty_tones(requestId, message, itone, nsym); -} - -void MainWindow::execute_jtty_tones(qint64 requestId, QString const& message, - int const itone[], int nsym) -{ - m_nsym_jtty=nsym; - - int nsps4=4*384; - float bt=2.0; - float fsample=48000.0; - float f0=ui->TxFreqSpinBox_2->value (); - int icmplx=0; - int nwave=nsps4*m_nsym_jtty; - - bool const newSession = !m_jttyTxActive; - if (newSession) { - advanceJttyTxQueueEpoch(); - m_jttyTxUsesTciAudio = m_tci_audio; - } - bool const useTciAudio = m_jttyTxUsesTciAudio; - - std::vector<float> wave(nwave > 0 ? nwave : 1); - gen_jttywave_(const_cast<int *>(itone), &m_nsym_jtty, &nsps4, &bt, &fsample, &f0, - wave.data(), wave.data(), &icmplx, &nwave); - - QVector<qint16> samples; - samples.reserve(nwave); - for(int i=0; i<nwave; ++i) { - float v = wave[i] * 32767.0f; - if(v > 32767.0f) v = 32767.0f; - if(v < -32768.0f) v = -32768.0f; - samples.append(static_cast<qint16>(qRound(v))); - } - if (samples.isEmpty()) { - Q_EMIT jttyTextRejected(requestId, JttyTxRejectReason::EncodingFailed); - return; - } - - if (newSession) { - // A fresh JTTY session starts a new FIFO accounting baseline even after a - // natural drain, so drain totals remain session-relative. - if (useTciAudio) { - Q_EMIT m_config.transceiver_clear_jtty_pcm(m_jttyTxQueueEpoch); - } else { - m_jttyTxQueue->clear(m_jttyTxQueueEpoch); - } - } - - bool enqueued {false}; - TxAudioQueueProgress enqueueProgress; - if(useTciAudio) { - // TCI enqueue is asynchronous. MainWindow can reject a message that can - // never fit; backend occupancy failures reject only the submitted enqueue. - if (samples.size () <= TxAudioQueue::defaultCapacity ()) { - QByteArray bytes(reinterpret_cast<char const *> (samples.constData ()), - samples.size () * int (sizeof (qint16))); - qint64 const enqueueId = ++m_jttyTciEnqueueId; - m_pendingJttyTciMessages.append(PendingJttyTciMessage { - m_jttyTxQueueEpoch, - enqueueId, - requestId, - samples.size (), - message, - newSession - }); - m_jttyTxActive = true; - Q_EMIT m_config.transceiver_enqueue_jtty_pcm(bytes, m_jttyTxQueueEpoch, - enqueueId); - return; - } else { - LOG_WARN("JTTY TCI transmit FIFO capacity precheck failed; rejecting PCM enqueue"); - Q_EMIT jttyTextRejected(requestId, JttyTxRejectReason::QueueFull); - } - } else { - auto const result = m_jttyTxQueue->enqueue(samples, m_jttyTxQueueEpoch); - enqueued = result.accepted; - enqueueProgress = result.progress; - if (!enqueued) { - LOG_WARN("JTTY transmit FIFO overflow; rejecting PCM enqueue"); - } - } - - if (!enqueued) { - if (!useTciAudio) { - Q_EMIT jttyTextRejected(requestId, JttyTxRejectReason::QueueFull); - } - if (newSession) { - advanceJttyTxQueueEpoch(); - } - return; - } - - completeJttyTxEnqueue(requestId, message, enqueueProgress, newSession, useTciAudio); -} - -void MainWindow::advanceJttyTxQueueEpoch() -{ - m_jttyTxQueueEpoch = TxAudioQueueEpoch {m_jttyTxQueueEpoch.value () + 1}; - m_jttyTxQueueProgress = {}; - m_jttyTxQueueProgress.epoch = m_jttyTxQueueEpoch; -} - -qint64 MainWindow::jttyTxCommittedSamples() const -{ - return m_jttyTxQueueProgress.total_samples; -} - -void MainWindow::completeJttyTxEnqueue(qint64 requestId, QString const& message, - TxAudioQueueProgress progress, - bool newSession, bool useTciAudio) -{ - if (newSession) { - beginTxEvidenceSession (); - } - m_currentMessage = message; - qint64 const endSample = progress.total_samples; - recordAcceptedJttyTextRequest(requestId, endSample); - m_jttyTxQueueProgress = progress; - if (m_txEvidenceGeneration.isValid () && - m_txEvidenceSourceSession == m_txEvidenceSession) { - m_txPlaybackDiagnostics.commitTarget (m_txEvidenceSession, - m_txEvidenceGeneration, - progress.total_samples - 1, false); - auto const sessionId = m_txEvidenceSession; - auto const generation = m_txEvidenceGeneration; - auto const totalSamples = progress.total_samples; - QTimer::singleShot (0, this, [this, sessionId, generation, totalSamples] { - LOG_INFO (QString ("TX playout evidence JTTY target commit session=%1 generation=%2 total=%3\n%4") - .arg (sessionId.value ()).arg (generation.value ()) - .arg (totalSamples).arg (m_txPlaybackDiagnostics.diagnosticDump ())); - }); - } - m_jttyTxActive = true; - m_transmitting = true; - write_all("Tx", message); - Q_EMIT jttyTextAccepted(requestId); - - ui->decodedTextBrowser2->insertText(" "); - QTextCursor cursor = ui->decodedTextBrowser2->textCursor(); - QTextCharFormat format = cursor.charFormat(); - format.setBackground(QBrush(QColor(Qt::yellow))); - cursor.setCharFormat(format); - cursor.insertText(Jtty::wrapMessage(message)); - format.setBackground(QBrush(QColor(Qt::white))); - cursor.setCharFormat(format); - - handleJttyContestSerial(message); - - // Fault-detector watchdog: generous margin over all audio still to play (the - // whole queued session, not just this message). The happy path completes via - // the backend drain signal well before this fires. - qint64 const pendingSamples = useTciAudio - ? progress.total_samples : progress.queued_samples; - int pendingMs = int(pendingSamples / 48); - startJttyTxWatchdog(pendingMs + 1000 * m_config.txDelay() + 10000); - - monitor(false); - if(!m_diskData && (m_saveAll || m_saveDecoded) && Jtty::wavCaptureValid (m_k0)) { - jtty_save_wav(); - } - -#ifdef WIN32 - if (m_mmttyif) { - m_mmttyif->report_ptt_state(true); - } -#endif - -#ifdef WIN32 - if (m_mmttyif) { - m_mmttyif->echo_message_to_n1mm(append_separator(message)); - } -#endif - - // Only a new session starts transmit; a message appended to an already-active - // session chains gaplessly (soundcard) via the enqueue above. When PTT is not - // yet up, guiUpdate keys it and ptt1Timer -> startTx2 -> transmit starts the - // stream with the normal lead. - if (newSession && g_iptt == 1 && !m_modulator->isActive()) { - startTx2(); - } -} - -void MainWindow::recordAcceptedJttyTextRequest(qint64 requestId, qint64 endSample) -{ - m_acceptedJttyTxRequests.append(AcceptedJttyTxRequest { - m_jttyTxQueueEpoch, - requestId, - endSample - }); -} - -QVector<qint64> MainWindow::takeCompletedJttyTextRequests( - TxAudioQueueEpoch epoch, qint64 totalAtDrain) -{ - // Backends report only final drain, so per-text completion is observed when - // the accepted text's containing JTTY session has drained. - QVector<qint64> completedRequestIds; - for (int i = 0; i < m_acceptedJttyTxRequests.size ();) { - auto const accepted = m_acceptedJttyTxRequests.at (i); - if (accepted.epoch == epoch && accepted.endSample <= totalAtDrain) { - completedRequestIds.append(accepted.requestId); - m_acceptedJttyTxRequests.remove (i); - } else { - ++i; - } - } - return completedRequestIds; -} - -void MainWindow::clearAcceptedJttyTextRequests(TxAudioQueueEpoch epoch) -{ - for (int i = 0; i < m_acceptedJttyTxRequests.size ();) { - if (m_acceptedJttyTxRequests.at (i).epoch == epoch) { - m_acceptedJttyTxRequests.remove (i); - } else { - ++i; - } - } -} - -void MainWindow::handleJttyContestSerial(QString const& message) -{ - if(message.left(3).compare("TU ", Qt::CaseInsensitive) == 0) { - logQSOTimer.start(0); - int nr = ui->sbSerialNumber_2->value(); - m_xSent = QString::number(nr); - ui->sbSerialNumber_2->setValue(nr+1); - } -} - -void MainWindow::abort_jtty_tx() -{ - noteTxStopReason (TxEvidence::TxStopReason::UserHalt); - interruptJttyTx(); - -#ifdef WIN32 - if (m_mmttyif) { - m_mmttyif->report_ptt_state(false); - } -#endif - - stopTx(); -} - -void MainWindow::interruptJttyTx() -{ - if (m_mode != "JTTY" || !m_jttyTxActive) { - return; - } - - auto const interruptedEpoch = m_jttyTxQueueEpoch; - if (!m_jttyTxUsesTciAudio) { - auto const progress = m_jttyTxQueue->progress (); - captureJttyTxEvidenceTotals (progress.served_samples, - progress.total_samples, - QStringLiteral ("JTTY source totals captured before abort")); - } else { - captureJttyTxEvidenceTotals (-1, m_jttyTxQueueProgress.total_samples, - QStringLiteral ("TCI JTTY committed total captured before abort")); - } - advanceJttyTxQueueEpoch(); - clearAcceptedJttyTextRequests(interruptedEpoch); - rejectPendingJttyTciMessages(JttyTxRejectReason::Aborted); - m_pendingJttyTciMessages.clear(); - if (m_jttyTxUsesTciAudio) { - Q_EMIT m_config.transceiver_clear_jtty_pcm(m_jttyTxQueueEpoch); - } else { - m_jttyTxQueue->clear(m_jttyTxQueueEpoch); - } - resetJttyTxState(); -} - -void MainWindow::onJttyBackendDrained(TxAudioQueueDrainState drain) -{ - if (m_mode != "JTTY" || !m_jttyTxActive) { - return; - } - - if (drain.epoch != m_jttyTxQueueEpoch - || drain.total_at_drain != jttyTxCommittedSamples ()) { - return; - } - - qint64 const servedAtDrain = m_jttyTxUsesTciAudio - ? drain.total_at_drain : m_jttyTxQueue->progress ().served_samples; - captureJttyTxEvidenceTotals (servedAtDrain, drain.total_at_drain, - QStringLiteral ("JTTY source totals captured at drain")); - - auto const completedRequestIds = takeCompletedJttyTextRequests( - drain.epoch, drain.total_at_drain); - resetJttyTxState(); - stopTx(); - for (auto const requestId : completedRequestIds) { - Q_EMIT jttyTextCompleted(requestId); - } - Q_EMIT jttySessionDrained(drain.epoch.value ()); -} - -void MainWindow::onJttyBackendEnqueueAccepted(qint64 enqueueId, qint64 sampleCount, - TxAudioQueueProgress progress) -{ - if (m_mode != "JTTY" || !m_jttyTxActive - || progress.epoch != m_jttyTxQueueEpoch) { - return; - } - - for (int i = 0; i < m_pendingJttyTciMessages.size (); ++i) { - auto const pending = m_pendingJttyTciMessages.at (i); - if (pending.epoch != progress.epoch || pending.enqueueId != enqueueId) { - continue; - } - - m_pendingJttyTciMessages.remove (i); - if (sampleCount != pending.sampleCount) { - LOG_WARN("JTTY transmit backend accepted unexpected PCM sample count"); - } - bool const startsSession = pending.newSession - || m_jttyTxQueueProgress.total_samples <= 0; - completeJttyTxEnqueue(pending.requestId, pending.message, progress, - startsSession, true); - return; - } -} - -void MainWindow::onJttyBackendEnqueueFailed(TxAudioQueueEpoch epoch, - qint64 enqueueId) -{ - if (m_mode != "JTTY" || !m_jttyTxActive - || epoch != m_jttyTxQueueEpoch) { - return; - } - - LOG_WARN("JTTY transmit backend rejected PCM enqueue"); - for (int i = 0; i < m_pendingJttyTciMessages.size (); ++i) { - auto const pending = m_pendingJttyTciMessages.at (i); - if (pending.epoch != epoch || pending.enqueueId != enqueueId) { - continue; - } - m_pendingJttyTciMessages.remove (i); - Q_EMIT jttyTextRejected(pending.requestId, JttyTxRejectReason::QueueFull); - if (pending.newSession && m_jttyTxQueueProgress.total_samples <= 0) { - for (int j = 0; j < m_pendingJttyTciMessages.size (); ++j) { - if (m_pendingJttyTciMessages[j].epoch == epoch) { - m_pendingJttyTciMessages[j].newSession = true; - return; - } - } - resetJttyTxState(); - } - return; - } -} - -void MainWindow::rejectPendingJttyTciMessages(JttyTxRejectReason reason) -{ - for (auto const& pending : m_pendingJttyTciMessages) { - Q_EMIT jttyTextRejected(pending.requestId, reason); - } -} - -void MainWindow::handleJttyTxWatchdog() -{ - if (m_mode != "JTTY" || !m_jttyTxActive) { - return; - } - - LOG_WARN("JTTY transmit completion watchdog expired"); - noteTxStopReason (TxEvidence::TxStopReason::Watchdog); - interruptJttyTx(); -#ifdef WIN32 - if (m_mmttyif) { - m_mmttyif->report_ptt_state(false); - } -#endif - stopTx(); -} - -void MainWindow::resetJttyTxState() -{ - m_jttyTxWatchdog.stop(); - m_jttyTxActive = false; - m_jttyTxQueueProgress = {}; - m_jttyTxQueueProgress.epoch = m_jttyTxQueueEpoch; - m_pendingJttyTciMessages.clear(); - m_acceptedJttyTxRequests.clear(); -} - -void MainWindow::startJttyTxWatchdog(int durationMs) -{ - if (durationMs > 0) { - m_jttyTxWatchdog.start(durationMs); - } -} - -void MainWindow::jtty_again() -{ - ui->DecodeButton->setChecked (true); - qApp->processEvents(); //Update the DecodeButton highlight - replayJttyFrames (dec_data.params.kin, [this] (int k) { - jtty_decode(k); - return false; - }); - flushJttyDecodeLines(); - finishDecodeUi(); -} - -// Triggered by double-clicking WideGraph's waterfall in JTTY mode: starts -// the rescan jttyPickLookbackSecs before the clicked time (a message can -// start just before the click) and stops as soon as jtty_decode reports a -// completed (EOM) message, rather than scanning a fixed window. A safety -// cap (jttyPickSafetyCapSecs forward of istart0) bounds how long it keeps -// looking if nothing ever completes -- e.g. the click landed on noise, or -// sync was lost partway through. secondsAgo is relative to m_k0 (the -// buffer position at the last processed block, i.e. "now"). Calls where k -// hasn't yet reached istart0 are cheap no-ops on the Fortran side, so the -// outer loop doesn't need to special-case its own starting point. -void MainWindow::jttyDecodeAgainAt(float secondsAgo) -{ - constexpr int jttyPickLookbackSecs = 5; - constexpr int jttyPickSafetyCapSecs = 40; - qint64 const center = qint64(m_k0) - qint64(qMax(0.0f, secondsAgo) * 12000.0f); - int const istart0 = int(qMax(qint64(1), center - qint64(jttyPickLookbackSecs) * 12000)); - int const frames = snapshotJttyFrames (dec_data.params.kin); - int const istop = int(qMin(qint64(frames), - qint64(istart0) + qint64(jttyPickSafetyCapSecs) * 12000)); - if (istop < istart0) return; // clicked time is no longer in the buffer at all - - ui->DecodeButton->setChecked (true); - qApp->processEvents(); //Update the DecodeButton highlight - replayJttyFrames (frames, [this, istart0, istop] (int k) { - bool const eom = jtty_decode(k, istart0, istop); - return eom || k >= istop; - }); - flushJttyDecodeLines(); - finishDecodeUi(); -} - -void MainWindow::flushJttyDecodeLines() -{ - // Called at a definite session end (new session starting, or true end of file); unconditional. - for (auto& line : m_jttyAllFreqLines) { - if (line.written) continue; - QString const text = line.text.trimmed(); - if (text.isEmpty()) continue; - write_all("Rx", formatJttyDecodeLine(line.frequency, text), &line.context); - line.written = true; - } -} - -bool MainWindow::jtty_key_struck(QKeyEvent * e) -{ - if(e->key() == Qt::Key_Escape) { - abort_jtty_tx(); - return true; - } - int const functionKey=e->key()-Qt::Key_F1+1; - if(functionKey < 1 || functionKey > 8) return false; - return sendJttyFunctionKey(functionKey); -} - -bool MainWindow::sendJttyFunctionKey(int index) -{ - QString macro; - switch(index) { - case 1: macro=ui->msg1->text(); break; - case 2: macro=ui->msg2->text(); break; - case 3: macro=ui->msg3->text(); break; - case 4: macro=ui->msg4->text(); break; - case 5: macro=ui->msg5->text(); break; - case 6: macro=ui->msg6->text(); break; - case 7: macro=ui->msg7->text(); break; - case 8: macro=ui->msg8->text(); break; - default: return false; - } - if(macro.simplified().isEmpty()) return false; - - auto const context = jttyNativeMacroContext( - m_config, m_hisCall, ui->sbSerialNumber_2->value()); - auto const compiled=Jtty::compileNativeMacro(macro,context); - if(compiled.status == Jtty::NativeMacroStatus::LiteralFallback) { - jtty_tx(compiled.text); - return true; - } - - qint64 const requestId=++m_jttyTxRequestId; - if(compiled.status == Jtty::NativeMacroStatus::InvalidRuntime) { - LOG_WARN(QStringLiteral("JTTY native macro rejected: %1").arg(compiled.error)); - Q_EMIT jttyTextRejected(requestId,JttyTxRejectReason::EncodingFailed); - return true; - } - - int itone[944]; - int nsym=0; - int encodeStatus=static_cast<int>(Jtty::NativeEncodeStatus::InvalidDescriptor); - genjtty_atoms_c(compiled.atoms.constData(),compiled.atoms.size(),itone,&nsym, - &encodeStatus); - if(nsym <= 0) { - LOG_WARN(QStringLiteral("JTTY native macro rejected: %1") - .arg(jttyNativeEncodeError(encodeStatus))); - Q_EMIT jttyTextRejected(requestId,JttyTxRejectReason::EncodingFailed); - return true; - } - execute_jtty_tones(requestId,compiled.text,itone,nsym); - return true; -} - -QString MainWindow::jtty_msg_expand(QString t) -{ - auto const context = jttyNativeMacroContext( - m_config, m_hisCall, ui->sbSerialNumber_2->value()); - return Jtty::expandLiteralMacro(t, context); -} - -void MainWindow::on_RxFreqSpinBox_2_valueChanged(int n) -{ - ui->RxFreqSpinBox->setValue(n); -} - -void MainWindow::on_TxFreqSpinBox_2_valueChanged(int n) -{ - ui->TxFreqSpinBox->setValue(n); -} - -void MainWindow::on_sbFtol_2_valueChanged (int n) -{ - m_wideGraph->setTol(n); -} - -#ifdef WIN32 -void MainWindow::logText(const QString &text) { - LOG_INFO(text); -} - -QString MainWindow::jttyRejectReasonText(JttyTxRejectReason reason) const -{ - switch (reason) { - case JttyTxRejectReason::Empty: return QStringLiteral("empty"); - case JttyTxRejectReason::EncodingFailed: return QStringLiteral("encoding failed"); - case JttyTxRejectReason::QueueFull: return QStringLiteral("queue full"); - case JttyTxRejectReason::BackendRejected: return QStringLiteral("backend rejected"); - case JttyTxRejectReason::Aborted: return QStringLiteral("aborted"); - case JttyTxRejectReason::NotAvailable: return QStringLiteral("not available"); - } - return QStringLiteral("unknown"); -} - -void MainWindow::handleMmttyTxString(QString message) -{ - auto const context = jttyNativeMacroContext( - m_config, m_hisCall, ui->sbSerialNumber_2->value()); - auto const compiled = Jtty::compileN1mmMessage(message, context); - if (m_mode != "JTTY") { - if (compiled.status == Jtty::N1mmCompileStatus::Literal) { - jtty_tx(compiled.literalText); - return; - } - - qint64 const requestId = ++m_jttyTxRequestId; - m_mmttyJttyOutput.submit(requestId); - QString const reason = compiled.status == Jtty::N1mmCompileStatus::Error - ? compiled.error : QStringLiteral("tagged JTTY actions require JTTY mode"); - logText(QStringLiteral("MMTTY/N1MM tagged JTTY request %1 rejected: %2") - .arg(requestId).arg(reason)); - Q_EMIT jttyTextRejected(requestId, JttyTxRejectReason::NotAvailable); - return; - } - - if (m_mmttyJttyOutput.finishRequested()) { - logText(QStringLiteral("MMTTY/N1MM JTTY text ignored after graceful OFF")); - return; - } - - qint64 const requestId = ++m_jttyTxRequestId; - m_mmttyJttyOutput.submit(requestId); - if (compiled.status == Jtty::N1mmCompileStatus::Literal) { - execute_jtty_tx(requestId, compiled.literalText); - return; - } - if (compiled.status == Jtty::N1mmCompileStatus::Error) { - logText(QStringLiteral("MMTTY/N1MM tagged JTTY request %1 rejected: %2") - .arg(requestId).arg(compiled.error)); - Q_EMIT jttyTextRejected(requestId, JttyTxRejectReason::EncodingFailed); - return; - } - - int itone[944]; - int nsym = 0; - int encodeStatus = static_cast<int>(Jtty::NativeEncodeStatus::InvalidDescriptor); - genjtty_atoms_c(compiled.atoms.constData(), compiled.atoms.size(), itone, &nsym, - &encodeStatus); - if (nsym <= 0) { - logText(QStringLiteral("MMTTY/N1MM tagged JTTY request %1 rejected: %2") - .arg(requestId).arg(jttyNativeEncodeError(encodeStatus))); - Q_EMIT jttyTextRejected(requestId, JttyTxRejectReason::EncodingFailed); - return; - } - execute_jtty_tones(requestId, compiled.canonicalText, itone, nsym); -} - -void MainWindow::handleMmttyStartTx() -{ - if (m_mode != "JTTY" && !m_mmttyJttyOutput.pending()) { - startTx2(); - return; - } - - m_mmttyJttyOutput.start(); - startPendingMmttyJttyTx(); -} - -void MainWindow::handleMmttyStopTx() -{ - if (m_mode != "JTTY") { - noteTxStopReason (TxEvidence::TxStopReason::UserHalt); - stopTx(); - if (!m_mmttyJttyOutput.pending()) return; - } - - m_mmttyJttyOutput.finish(); - logText(QStringLiteral("MMTTY/N1MM JTTY OFF requested; waiting for backend drain")); - completeMmttyJttyOutput(); -} - -void MainWindow::handleMmttyAbortTx() -{ - m_mmttyJttyOutput.abort(); - abort_jtty_tx(); -} - -void MainWindow::handleMmttyJttyAccepted(qint64 requestId) -{ - if (!m_mmttyJttyOutput.accept(requestId)) return; - - logText(QStringLiteral("MMTTY/N1MM JTTY request %1 accepted").arg(requestId)); - startPendingMmttyJttyTx(); -} - -void MainWindow::handleMmttyJttyRejected(qint64 requestId, JttyTxRejectReason reason) -{ - if (!m_mmttyJttyOutput.resolve(requestId)) return; - - logText(QStringLiteral("MMTTY/N1MM JTTY request %1 rejected: %2") - .arg(requestId) - .arg(jttyRejectReasonText(reason))); - // Backend rejection may reset the audio session after emitting this signal. - QTimer::singleShot(0, this, [this] { completeMmttyJttyOutput(); }); -} - -void MainWindow::handleMmttyJttyCompleted(qint64 requestId) -{ - if (!m_mmttyJttyOutput.resolve(requestId)) return; - - logText(QStringLiteral("MMTTY/N1MM JTTY request %1 completed").arg(requestId)); -} - -void MainWindow::handleMmttyJttySessionDrained(qint64 sessionId) -{ - Q_UNUSED(sessionId) - completeMmttyJttyOutput(true); -} - -void MainWindow::completeMmttyJttyOutput(bool drained) -{ - if (m_mmttyJttyOutput.takeCompletion(m_jttyTxActive, drained) && m_mmttyif) { - m_mmttyif->report_output_complete(); - } -} - -void MainWindow::startPendingMmttyJttyTx() -{ - if (m_mode != "JTTY" || !m_mmttyJttyOutput.startRequested()) return; - - if (!m_jttyTxActive || jttyTxCommittedSamples () <= 0) { - logText(QStringLiteral("MMTTY/N1MM JTTY start deferred until text is accepted")); - return; - } - - if (g_iptt == 1) { - logText(QStringLiteral("MMTTY/N1MM JTTY start ignored; transmitter is already keyed")); - m_mmttyJttyOutput.started(); - return; - } - - m_mmttyJttyOutput.started(); - startTx2(); -} - -void MainWindow::initMMTTY(quint16 port) { - if (!m_mmttyif) { - m_mmttyif = new MMTTYIF(this); - } - - m_mmttyif->initialize(port); - - connect(m_mmttyif, &MMTTYIF::log_message, this, &MainWindow::logText); - connect(m_mmttyif, &MMTTYIF::app_tx_string, this, &MainWindow::handleMmttyTxString); - connect(m_mmttyif, &MMTTYIF::app_start_tx, this, &MainWindow::handleMmttyStartTx); - connect(m_mmttyif, &MMTTYIF::app_stop_tx, this, &MainWindow::handleMmttyStopTx); - connect(m_mmttyif, &MMTTYIF::app_abort_tx, this, &MainWindow::handleMmttyAbortTx); - connect(this, &MainWindow::jttyTextAccepted, this, &MainWindow::handleMmttyJttyAccepted); - connect(this, &MainWindow::jttyTextRejected, this, &MainWindow::handleMmttyJttyRejected); - connect(this, &MainWindow::jttyTextCompleted, this, &MainWindow::handleMmttyJttyCompleted); - connect(this, &MainWindow::jttySessionDrained, this, &MainWindow::handleMmttyJttySessionDrained); - - connect(m_mmttyif, &MMTTYIF::inactivity_timeout, qApp, &QCoreApplication::quit); - connect(m_mmttyif, &MMTTYIF::app_is_quitting, this, [this]() { - abort_jtty_tx(); - close(); - }); - - // Auto-switch to JTTY mode after MMTTY connects - QTimer::singleShot(3000, this, [this]() { - set_mode("JTTY"); - }); -} - -MMTTYIF *MainWindow::getMmttyIf() const { - return m_mmttyif; -} -#endif +#include "mainwindow.h"
+#include "ui_mainwindow.h"
+#include "widegraph.h"
+#include "commons.h"
+#include "JttyMessages.hpp"
+#include "JttyN1mm.hpp"
+#include "JttyReceiveLine.hpp"
+#include "Logger.hpp"
+#include "models/DecodeHighlightingModel.hpp"
+#include <QByteArray>
+#include <QDateTime>
+#include <QSettings>
+#include <QTextCharFormat>
+#include <QTextCursor>
+#include <algorithm>
+#include "Modulator/Modulator.hpp"
+#include <vector>
+#ifdef WIN32
+#include "MMTTYIF.hpp"
+#undef MessageBox
+#endif
+
+
+extern qint32 g_iptt;
+
+namespace
+{
+ Jtty::NativeExchangeProfile jttyExchangeProfile(Configuration const& configuration)
+ {
+ switch (configuration.special_op_id()) {
+ case Configuration::SpecialOperatingActivity::FIELD_DAY:
+ return Jtty::NativeExchangeProfile::FieldDay;
+ case Configuration::SpecialOperatingActivity::RTTY:
+ return Jtty::NativeExchangeProfile::RttyRoundup;
+ default:
+ return Jtty::NativeExchangeProfile::None;
+ }
+ }
+
+ Jtty::NativeMacroContext jttyNativeMacroContext(
+ Configuration const& configuration, QString const& hisCall, int serialNumber,
+ int snr)
+ {
+ Jtty::NativeMacroContext context;
+ context.myCall = configuration.my_callsign();
+ context.hisCall = hisCall;
+ context.serialNumber = serialNumber;
+ context.grid = configuration.my_grid();
+ context.snr = snr;
+ context.exchangeProfile = jttyExchangeProfile(configuration);
+
+ switch (context.exchangeProfile) {
+ case Jtty::NativeExchangeProfile::FieldDay:
+ context.configuredExchange = Jtty::normalizedFieldDayExchange(
+ configuration.Field_Day_Exchange());
+ break;
+ case Jtty::NativeExchangeProfile::RttyRoundup:
+ context.configuredExchange = configuration.RTTY_Exchange();
+ break;
+ default:
+ break;
+ }
+ return context;
+ }
+
+ QString jttyNativeEncodeError(int status)
+ {
+ if (status == static_cast<int>(Jtty::NativeEncodeStatus::UnknownSection)) {
+ return QStringLiteral("Field Day section is not registered in the ARRL/RAC table");
+ }
+ return QStringLiteral("native atom encoding failed");
+ }
+}
+
+#define FCL fortran_charlen_t
+
+// Mirrors lib/jtty/jtty_mod.f90's MAX_FRAMES.
+constexpr int kMaxJttyFrames = 16;
+
+// Backstop cap: batches at least this many words per auto-advance burst even if the operator never pauses (the idle timer below normally fires first).
+constexpr int kJttyAutoAdvanceBatchWords = 5;
+
+// A typing pause this long, with anything safely committable pending, flushes it rather than waiting for kJttyAutoAdvanceBatchWords to fill up.
+constexpr int kJttyAutoAdvanceIdleMs = 1500;
+
+extern "C" {
+ void genjtty_profile_(char * msg, int const* exchange_profile,
+ int itone[], int* nsym, int frame_starts[],
+ int const* is_final, fortran_charlen_t);
+ void genjtty_atoms_c(Jtty::NativeAtomDescriptor const atoms[], int natoms,
+ int itone[], int* nsym, int* status);
+
+ void gen_jttywave_(int itone[], int* nsym, int* nsps, float* bt, float* fsample, float* f0,
+ float xjunk[], float wave[], int* icmplx, int* nwave);
+}
+
+#ifdef WIN32
+static QString append_separator(QString message) {
+ if (!message.isEmpty()) {
+ QChar lastChar = message.at(message.length() - 1);
+ if (lastChar != '\r' && lastChar != '\n' && lastChar != ' ') {
+ message += "\r\n";
+ }
+ }
+ return message;
+}
+#endif
+
+
+
+void MainWindow::updateJttyDecodeHeadings()
+{
+ QString const prefix = ui->cbIncludeTime->isChecked()
+ ? QStringLiteral(" UTC Freq dB ") : QStringLiteral("Freq dB ");
+ ui->lh_decodes_headings_label->setText(prefix + tr ("Message"));
+ ui->rh_decodes_headings_label->setText(prefix + tr ("Message"));
+}
+
+void MainWindow::on_cbIncludeTime_toggled(bool)
+{
+ if (m_mode == "JTTY") {
+ updateJttyDecodeHeadings();
+ refreshJttyReceiveLines();
+ }
+}
+
+void MainWindow::jtty_tx(QString message)
+{
+ // Render and enqueue immediately; the shared transmit buffer chains messages
+ // gaplessly while playback is underway.
+ submitJttyText(message);
+}
+
+qint64 MainWindow::submitJttyText(QString message)
+{
+ qint64 const requestId = ++m_jttyTxRequestId;
+ execute_jtty_tx(requestId, message);
+ return requestId;
+}
+
+// Ctrl+K / Send button: one-shot send -- force-flushes, marks final (EOM), and disarms; typing more afterward needs another explicit Alt+J or Ctrl+K, nothing auto-advances.
+void MainWindow::commitJttyLiveEntry()
+{
+ if (m_mode != "JTTY") return;
+ m_jttyAutoAdvanceIdleTimer.stop ();
+ commitJttyLiveEntryPlan (/*forceFlush=*/true, Jtty::maxCompactAtomWords, /*isFinal=*/true);
+ m_jttyLiveEntryArmed = false;
+}
+
+// Alt+J: force-flushes like Ctrl+K but never marks final, and arms auto-advance/idle-flush; stays open (continuously filler-padded by finishJttyDrain) until Alt+K signs off or Halt Tx/Esc cancels it.
+void MainWindow::startJttyLiveStream()
+{
+ if (m_mode != "JTTY") return;
+ m_jttyLiveEntryArmed = true;
+ m_jttyAutoAdvanceIdleTimer.stop ();
+ commitJttyLiveEntryPlan (/*forceFlush=*/true, Jtty::maxCompactAtomWords, /*isFinal=*/false);
+}
+
+// Once armed, batches several words per commit rather than firing per word (each commit is its own transmission, and one-word bursts showed up as one decode line per word); fires on kJttyAutoAdvanceBatchWords piling up, or a pause via idleFlushJttyLiveEntry.
+void MainWindow::autoAdvanceJttyLiveEntry()
+{
+ if (m_mode != "JTTY" || !m_jttyLiveEntryArmed || m_guardingJttyLiveEntryLock) return;
+ QString const uncommitted = ui->Tx_Message->toPlainText ().mid (m_jttyLiveEntryCommitted);
+ int const completeWords = Jtty::completeWordCount (uncommitted);
+ if (completeWords - Jtty::maxCompactAtomWords >= kJttyAutoAdvanceBatchWords) {
+ m_jttyAutoAdvanceIdleTimer.stop ();
+ commitJttyLiveEntryPlan (/*forceFlush=*/false, Jtty::maxCompactAtomWords, /*isFinal=*/false);
+ return;
+ }
+ // Arms on any uncommitted content, complete word or not -- idleFlushJttyLiveEntry releases even a trailing not-yet-space-terminated word once the pause happens.
+ if (!uncommitted.trimmed ().isEmpty ()) {
+ m_jttyAutoAdvanceIdleTimer.start (kJttyAutoAdvanceIdleMs);
+ } else {
+ m_jttyAutoAdvanceIdleTimer.stop ();
+ }
+}
+
+// Force-flushes everything typed, including a trailing word with no trailing space yet, but isFinal=false unlike Ctrl+K, so the message stays open; a detected pause means no keystroke is coming to extend an atom or a partial word, so the usual holdback/complete-word protections no longer apply. Doesn't queue filler itself -- finishJttyDrain keeps the session continuously padded for as long as it's armed.
+void MainWindow::idleFlushJttyLiveEntry()
+{
+ if (m_mode != "JTTY" || !m_jttyLiveEntryArmed || m_guardingJttyLiveEntryLock) return;
+ commitJttyLiveEntryPlan (/*forceFlush=*/true, Jtty::maxCompactAtomWords, /*isFinal=*/false);
+}
+
+void MainWindow::sendJttyFillerPadding()
+{
+ qint64 const requestId = ++m_jttyTxRequestId;
+ execute_jtty_tx (requestId, Jtty::jttyFillerText, /*isFinal=*/false);
+}
+
+bool MainWindow::commitJttyLiveEntryPlan(bool forceFlush, int holdbackWords, bool isFinal)
+{
+ QString const uncommitted = ui->Tx_Message->toPlainText ().mid (m_jttyLiveEntryCommitted);
+ auto const plan = Jtty::planIncrementalCommit (uncommitted, forceFlush, holdbackWords);
+ if (plan.text.trimmed ().isEmpty ()) return false;
+
+ QString expanded = jtty_msg_expand (plan.text);
+ if (ui->cbLowerCase->isChecked ()) expanded = expanded.toLower ();
+ expanded = Jtty::prepareTransmitText (expanded).text;
+
+ m_guardingJttyLiveEntryLock = true;
+ QTextCursor replace (ui->Tx_Message->document ());
+ replace.setPosition (m_jttyLiveEntryCommitted);
+ replace.setPosition (m_jttyLiveEntryCommitted + plan.length, QTextCursor::KeepAnchor);
+ replace.insertText (expanded);
+ qint64 const requestId = ++m_jttyTxRequestId;
+ m_jttyLiveEntryPending.append ({requestId, m_jttyLiveEntryCommitted,
+ m_jttyLiveEntryCommitted + expanded.size ()});
+ m_jttyLiveEntryCommitted += expanded.size ();
+ applyJttyLiveEntryFormatting ();
+ m_guardingJttyLiveEntryLock = false;
+
+ execute_jtty_tx (requestId, expanded, isFinal);
+
+ for (auto& pending : m_jttyLiveEntryPending) {
+ if (pending.requestId != requestId) continue;
+ for (auto const& request : m_jttyTransmitQueue.requests ()) {
+ if (request.id != requestId) continue;
+ for (auto const& segment : request.segments) {
+ pending.totalFrames += segment.tones.size () / 59;
+ }
+ break;
+ }
+ break;
+ }
+ updateJttyLiveEntryFrameLabel ();
+ return true;
+}
+
+// Ctrl+Shift+K: clears the whole box, including locked/sent text, cancelling anything of it still queued/in flight.
+void MainWindow::clearJttyLiveEntry()
+{
+ if (m_mode != "JTTY") return;
+ m_jttyAutoAdvanceIdleTimer.stop ();
+ if (m_jttyTxLifecycle.active () || !m_jttyTransmitQueue.empty ()) {
+ abort_jtty_tx ();
+ }
+ m_jttyLiveEntryPending.clear ();
+ m_jttyLiveEntryCommitted = 0;
+ m_jttyLiveEntryFramesSent = 0;
+ m_jttyLiveEntryArmed = false;
+ m_jttyLiveEntryLockedText.clear ();
+ m_guardingJttyLiveEntryLock = true;
+ ui->Tx_Message->clear ();
+ ui->Tx_Message->setCurrentCharFormat (QTextCharFormat {});
+ m_guardingJttyLiveEntryLock = false;
+ updateJttySendButton ();
+ updateJttyLiveEntryFrameLabel ();
+}
+
+// Inserts text at the cursor like ordinary typing, redirecting to the end first if the cursor (or its selection) reaches into the locked prefix.
+void MainWindow::insertJttyLiveEntryText(QString const& text)
+{
+ if (m_mode != "JTTY") return;
+ QTextCursor cursor = ui->Tx_Message->textCursor ();
+ if (qMin (cursor.position (), cursor.anchor ()) < m_jttyLiveEntryCommitted) {
+ cursor.movePosition (QTextCursor::End);
+ }
+ cursor.insertText (text);
+ ui->Tx_Message->setTextCursor (cursor);
+}
+
+// Ctrl+H: chat-style opener identifying both stations ("<hisCall> <myCall> "), expanded like any other macro at commit time.
+void MainWindow::insertJttyChatOpener()
+{
+ insertJttyLiveEntryText (QStringLiteral ("%H %M "));
+}
+
+// Alt+K: sign-off ("DE <myCall> K "), then finalizes (marks EOM) and disarms, so finishJttyDrain stops topping up with filler and PTT drops once this finishes playing.
+void MainWindow::insertJttyChatSignoff()
+{
+ insertJttyLiveEntryText (QStringLiteral ("DE %M K "));
+ m_jttyAutoAdvanceIdleTimer.stop ();
+ commitJttyLiveEntryPlan (/*forceFlush=*/true, Jtty::maxCompactAtomWords, /*isFinal=*/true);
+ m_jttyLiveEntryArmed = false;
+}
+
+// Fraction (0..1) of a pending commit that should show as sent, stepping one JTTY frame at a time using pack_jtty's own frame_starts boundaries (segment.frameCharStarts) rather than an even split, which put the boundary mid-atom; falls back to an even split if a segment's boundaries weren't captured. Each frame is a fixed 59*1536 samples (genjtty_frames, lib/jtty/genjtty.f90). Returns 0 for a requestId not yet enqueued (not started, never "finished").
+double MainWindow::jttyRequestSentFraction(qint64 requestId) const
+{
+ qint64 const samplesPerFrame = 59LL * 1536;
+ for (auto const& request : m_jttyTransmitQueue.requests ()) {
+ if (request.id != requestId) continue;
+ int totalChars = 0;
+ double doneChars = 0.0;
+ for (auto const& segment : request.segments) {
+ int const chars = segment.text.size ();
+ totalChars += chars;
+ int const nframes = segment.tones.size () / 59;
+ if (nframes <= 0 || chars <= 0 || !segment.endSample) continue;
+ if (m_jttyQueueProgress.served_samples >= segment.endSample) {
+ doneChars += chars;
+ continue;
+ }
+ qint64 const startSample = segment.endSample - segment.sampleCount ();
+ qint64 const elapsed = m_jttyQueueProgress.served_samples - startSample;
+ if (elapsed <= 0) continue;
+ int const framesDone = int (qMin (qint64 (nframes), elapsed / samplesPerFrame));
+ if (framesDone <= 0) continue;
+ if (segment.frameCharStarts.size () == nframes) {
+ doneChars += framesDone < nframes
+ ? segment.frameCharStarts.at (framesDone) : chars;
+ } else {
+ doneChars += chars * (double (framesDone) / nframes);
+ }
+ }
+ return totalChars > 0 ? doneChars / totalChars : 0.0;
+ }
+ return 0.0;
+}
+
+// Same elapsed-sample accounting as jttyRequestSentFraction, as a frame count for the label rather than a char fraction for the highlight.
+int MainWindow::jttyRequestFramesDone(qint64 requestId) const
+{
+ qint64 const samplesPerFrame = 59LL * 1536;
+ for (auto const& request : m_jttyTransmitQueue.requests ()) {
+ if (request.id != requestId) continue;
+ int doneFrames = 0;
+ for (auto const& segment : request.segments) {
+ int const nframes = segment.tones.size () / 59;
+ if (nframes <= 0 || !segment.endSample) continue;
+ if (m_jttyQueueProgress.served_samples >= segment.endSample) {
+ doneFrames += nframes;
+ continue;
+ }
+ qint64 const startSample = segment.endSample - segment.sampleCount ();
+ qint64 const elapsed = m_jttyQueueProgress.served_samples - startSample;
+ if (elapsed <= 0) continue;
+ doneFrames += int (qMin (qint64 (nframes), elapsed / samplesPerFrame));
+ }
+ return doneFrames;
+ }
+ return 0;
+}
+
+// Dry-run of execute_jtty_tx's segmentation/encoding, without enqueuing, to preview an uncommitted message's frame count.
+int MainWindow::countJttyTransmitFrames(QString const& preparedMessage) const
+{
+ if (preparedMessage.trimmed ().isEmpty ()) return 0;
+ int const exchangeProfile = static_cast<int>(jttyExchangeProfile (m_config));
+ int totalFrames = 0;
+ auto const lines = preparedMessage.split (QLatin1Char ('\n'));
+ for (auto const& line : lines) {
+ auto const encoded = Jtty::encodeTransmitLine (line, [&] (QString const& text) {
+ auto frame = Jtty::transmitFrame (text).toLatin1 ();
+ QVector<int> tones (944);
+ int nsym = 0;
+ int frameStarts[kMaxJttyFrames] = {};
+ int const finalFlag = 1; // irrelevant to frame count, which EOM doesn't affect
+ genjtty_profile_ (frame.data (), &exchangeProfile, tones.data (),
+ &nsym, frameStarts, &finalFlag, (FCL)80);
+ totalFrames += nsym / 59;
+ return nsym > 0;
+ });
+ if (!encoded) return 0;
+ }
+ return totalFrames;
+}
+
+// Updates the "Frames: sent/total" label: drained history plus pending commits' exact/live-progress totals, plus a dry-run estimate for the uncommitted tail.
+void MainWindow::updateJttyLiveEntryFrameLabel()
+{
+ if (m_mode != "JTTY") {
+ ui->labelJttyFrameCount->clear ();
+ return;
+ }
+
+ int sentFrames = m_jttyLiveEntryFramesSent;
+ int committedFrames = m_jttyLiveEntryFramesSent;
+ for (auto const& pending : m_jttyLiveEntryPending) {
+ committedFrames += pending.totalFrames;
+ sentFrames += jttyRequestFramesDone (pending.requestId);
+ }
+
+ QString const uncommitted =
+ ui->Tx_Message->toPlainText ().mid (m_jttyLiveEntryCommitted);
+ int uncommittedFrames = 0;
+ if (!uncommitted.trimmed ().isEmpty ()) {
+ QString probe = jtty_msg_expand (uncommitted);
+ if (ui->cbLowerCase->isChecked ()) probe = probe.toLower ();
+ probe = Jtty::prepareTransmitText (probe).text;
+ uncommittedFrames = countJttyTransmitFrames (probe);
+ }
+
+ int const totalFrames = committedFrames + uncommittedFrames;
+ if (totalFrames <= 0) {
+ ui->labelJttyFrameCount->clear ();
+ } else {
+ ui->labelJttyFrameCount->setText (
+ tr ("Frames: %1/%2").arg (sentFrames).arg (totalFrames));
+ }
+}
+
+// Repaints committed text sent/queued by pending-span progress and resets everything past it to plain formatting, including the about-to-be-typed char format (so new text never inherits the preceding run). Caller must already hold m_guardingJttyLiveEntryLock.
+void MainWindow::applyJttyLiveEntryFormatting()
+{
+ auto * document = ui->Tx_Message->document ();
+ QTextCursor all (document);
+ all.select (QTextCursor::Document);
+ all.setCharFormat (QTextCharFormat {});
+
+ // "Sent" uses the same Tx highlight as an echoed Tx line in the QSO Frequency pane, distinct from plain-gray "queued."
+ auto const resolved = DecodeHighlightingModel::resolve_colors (
+ m_config.decode_highlighting ().items (),
+ {DecodeHighlightingModel::Highlight::Tx}, QColor (Qt::yellow),
+ QColor (Qt::black));
+ QTextCharFormat sentFormat;
+ sentFormat.setBackground (resolved.background_);
+ sentFormat.setForeground (resolved.foreground_);
+ QTextCharFormat queuedFormat;
+ queuedFormat.setForeground (QColor (Qt::gray));
+
+ auto paintSent = [&] (int from, int to) {
+ if (to <= from) return;
+ QTextCursor cursor (document);
+ cursor.setPosition (from);
+ cursor.setPosition (to, QTextCursor::KeepAnchor);
+ cursor.setCharFormat (sentFormat);
+ };
+
+ int paintedTo = 0;
+ for (auto const& pending : m_jttyLiveEntryPending) {
+ paintSent (paintedTo, pending.start);
+ double const fraction = jttyRequestSentFraction (pending.requestId);
+ int const split = pending.start + qBound (
+ 0, qRound ((pending.end - pending.start) * fraction),
+ pending.end - pending.start);
+ paintSent (pending.start, split);
+ if (pending.end > split) {
+ QTextCursor queued (document);
+ queued.setPosition (split);
+ queued.setPosition (pending.end, QTextCursor::KeepAnchor);
+ queued.setCharFormat (queuedFormat);
+ }
+ paintedTo = pending.end;
+ }
+ paintSent (paintedTo, m_jttyLiveEntryCommitted);
+
+ m_jttyLiveEntryLockedText = ui->Tx_Message->toPlainText ().left (m_jttyLiveEntryCommitted);
+ ui->Tx_Message->setCurrentCharFormat (QTextCharFormat {});
+}
+
+// Reverts any edit that reached into the locked/committed prefix, however it got there (typing, backspace, paste, drag-drop).
+void MainWindow::guardJttyLiveEntryLock()
+{
+ if (m_guardingJttyLiveEntryLock || m_mode != "JTTY"
+ || m_jttyLiveEntryCommitted <= 0) return;
+ if (ui->Tx_Message->toPlainText ().left (m_jttyLiveEntryCommitted)
+ == m_jttyLiveEntryLockedText) return;
+ m_guardingJttyLiveEntryLock = true;
+ ui->Tx_Message->undo ();
+ m_guardingJttyLiveEntryLock = false;
+}
+
+// isFinal marks EOM only on the very last segment of the very last line; every other segment stays non-final since more of the same commit follows, except an earlier line's own last segment, always final since a newline is a hard break. A non-final segment shows up at the receiver as a still-growing line (jtty_mdecode.f90's continuation matching stitches the next segment onto it) rather than its own completed message.
+void MainWindow::execute_jtty_tx(qint64 requestId, QString message, bool isFinal)
+{
+ if (ui->cbLowerCase->isChecked()) message = message.toLower();
+ auto const prepared = Jtty::prepareTransmitText(message);
+ message = prepared.text;
+ if (message.trimmed().isEmpty()) {
+ Q_EMIT jttyTextRejected(requestId, JttyTxRejectReason::Empty);
+ return;
+ }
+
+ int const exchangeProfile = static_cast<int>(jttyExchangeProfile(m_config));
+ // One-shot encode; empty tones mean the text did not encode. Used for the initial non-final pass and to re-bake a line's true last segment once its real EOM status is known.
+ auto encodeOnce = [&] (QString const& text, bool segmentIsFinal) {
+ Jtty::TransmitSegment segment;
+ auto frame = Jtty::transmitFrame(text).toLatin1();
+ segment.tones.resize(944);
+ int nsym = 0;
+ int frameStarts[kMaxJttyFrames] = {};
+ int const finalFlag = segmentIsFinal ? 1 : 0;
+ genjtty_profile_(frame.data(), &exchangeProfile, segment.tones.data(),
+ &nsym, frameStarts, &finalFlag, (FCL)80);
+ if (nsym > 0) {
+ segment.tones.resize(nsym);
+ segment.text = QString::fromLatin1(frame).trimmed();
+ int const nframes = nsym / 59;
+ segment.frameCharStarts.reserve(nframes);
+ for (int i = 0; i < nframes; ++i) {
+ // Fortran gives 1-indexed columns; store 0-indexed offsets.
+ segment.frameCharStarts.append(frameStarts[i] - 1);
+ }
+ } else {
+ segment.tones.clear();
+ }
+ return segment;
+ };
+ auto refuseUnencodable = [&] {
+ showStatusMessage(tr("JTTY text not sent: a line does not fit in one message once encoded; shorten it and send again"));
+ Q_EMIT jttyTextRejected(requestId, JttyTxRejectReason::EncodingFailed);
+ };
+
+ QVector<Jtty::TransmitSegment> segments;
+ // Newlines force a new segment; split them out before nextTransmitTextSegment (space-only breaks).
+ auto const lines = message.split(QLatin1Char('\n'));
+ for (int lineIndex = 0; lineIndex < lines.size(); ++lineIndex) {
+ auto const& line = lines[lineIndex];
+ int const lineStart = segments.size();
+ auto const encoded = Jtty::encodeTransmitLine(line, [&] (QString const& text) {
+ auto segment = encodeOnce(text, /*segmentIsFinal=*/false);
+ if (segment.tones.isEmpty()) return false;
+ segment.frequency = ui->TxFreqSpinBox_2->value();
+ segments.append(std::move(segment));
+ return true;
+ });
+ if (!encoded) {
+ refuseUnencodable();
+ return;
+ }
+ if (segments.size() == lineStart) continue;
+ bool const lineIsFinal = lineIndex + 1 < lines.size() || isFinal;
+ if (!lineIsFinal) continue;
+ auto& last = segments.last();
+ auto final_ = encodeOnce(last.text, /*segmentIsFinal=*/true);
+ if (final_.tones.isEmpty()) {
+ refuseUnencodable();
+ return;
+ }
+ final_.frequency = last.frequency;
+ last = std::move(final_);
+ }
+
+ m_jttyQueueNotice = prepared.substituted
+ ? tr("Unsupported characters were replaced. Hover over Send to review the text.")
+ : QString {};
+ enqueueJttySegments(requestId, std::move(segments));
+}
+
+void MainWindow::enqueueJttySegments(
+ qint64 requestId, QVector<Jtty::TransmitSegment> segments)
+{
+ if (m_mode != "JTTY" || m_closing || jttyDrainInProgress()
+ || segments.isEmpty()) {
+ Q_EMIT jttyTextRejected(requestId, JttyTxRejectReason::NotAvailable);
+ return;
+ }
+ m_jttyTransmitQueue.append(requestId, std::move(segments));
+ updateJttySendButton();
+ feedJttyTransmitQueue();
+}
+
+void MainWindow::enqueueJttyToneSegment(qint64 requestId,
+ QString const& message,
+ int const tones[], int toneCount)
+{
+ Jtty::TransmitSegment segment;
+ segment.text = message;
+ segment.tones.reserve (toneCount);
+ for (int i = 0; i < toneCount; ++i) segment.tones.append (tones[i]);
+ segment.frequency = ui->TxFreqSpinBox_2->value ();
+ enqueueJttySegments (requestId, {std::move (segment)});
+}
+
+void MainWindow::feedJttyTransmitQueue()
+{
+ if (m_feedingJttyTransmitQueue || m_closing || m_mode != "JTTY"
+ || jttyDrainInProgress() || m_jttyTxLifecycle.hasPending ()
+ || m_delayedJttyStopContext.backend != JttyTxLifecycle::Backend::None
+ || ptt0Timer.isActive ()) return;
+ auto const next = m_jttyTransmitQueue.nextSegment();
+ if (!next) return;
+
+ auto progress = m_jttyQueueProgress;
+ if (m_jttyTxLifecycle.active ()
+ && m_jttyTxLifecycle.backend () == JttyTxLifecycle::Backend::Local) {
+ progress = m_jttyTxQueue->progress ();
+ }
+ if (m_jttyTxLifecycle.active ()
+ && (progress.epoch != m_jttyTxLifecycle.epoch ()
+ || progress.queued_samples + next->sampleCount ()
+ > TxAudioQueue::defaultCapacity ())) return;
+ if (next->sampleCount () > TxAudioQueue::defaultCapacity ()) {
+ auto const cancelled = m_jttyTransmitQueue.cancel ();
+ for (auto id : cancelled) {
+ Q_EMIT jttyTextRejected (id, JttyTxRejectReason::QueueFull);
+ }
+ m_jttyQueueNotice = tr ("A JTTY segment exceeds the audio queue capacity.");
+ updateJttySendButton ();
+ return;
+ }
+
+ m_feedingJttyTransmitQueue = true;
+ execute_jtty_tones (m_jttyTransmitQueue.nextRequestId (), next->text,
+ next->tones.constData (), next->tones.size (),
+ next->frequency);
+ m_feedingJttyTransmitQueue = false;
+}
+
+void MainWindow::execute_jtty_tones(qint64 requestId, QString const& message,
+ int const itone[], int nsym, int frequency)
+{
+ if (jttyDrainInProgress()) {
+ Q_EMIT jttyTextRejected(requestId, JttyTxRejectReason::NotAvailable);
+ return;
+ }
+ m_nsym_jtty=nsym;
+
+ int nsps4=4*384;
+ float bt=2.0;
+ float fsample=48000.0;
+ float f0=(frequency >= 0 ? frequency : ui->TxFreqSpinBox_2->value ()) - m_XIT;
+ int icmplx=0;
+ int nwave=nsps4*m_nsym_jtty;
+
+ std::vector<float> wave(nwave > 0 ? nwave : 1);
+ gen_jttywave_(const_cast<int *>(itone), &m_nsym_jtty, &nsps4, &bt, &fsample, &f0,
+ wave.data(), wave.data(), &icmplx, &nwave);
+
+ QVector<qint16> samples;
+ samples.reserve(nwave);
+ for(int i=0; i<nwave; ++i) {
+ float v = wave[i] * 32767.0f;
+ if(v > 32767.0f) v = 32767.0f;
+ if(v < -32768.0f) v = -32768.0f;
+ samples.append(static_cast<qint16>(qRound(v)));
+ }
+ if (samples.isEmpty()) {
+ Q_EMIT jttyTextRejected(requestId, JttyTxRejectReason::EncodingFailed);
+ return;
+ }
+
+ if (samples.size () > TxAudioQueue::defaultCapacity ()) {
+ LOG_WARN("JTTY transmit FIFO capacity precheck failed; rejecting PCM enqueue");
+ Q_EMIT jttyTextRejected(requestId, JttyTxRejectReason::QueueFull);
+ return;
+ }
+
+ bool const newSession = !m_jttyTxLifecycle.active ();
+ if (newSession) {
+ auto const backend = m_tci_audio ? JttyTxLifecycle::Backend::Tci
+ : JttyTxLifecycle::Backend::Local;
+ auto const epoch = m_jttyTxLifecycle.begin (backend);
+ if (!epoch.isValid ()) {
+ Q_EMIT jttyTextRejected(requestId, JttyTxRejectReason::NotAvailable);
+ return;
+ }
+ if (backend == JttyTxLifecycle::Backend::Tci) {
+ Q_EMIT m_config.transceiver_clear_jtty_pcm(epoch);
+ } else {
+ Q_EMIT clearJttyStream(epoch);
+ }
+ m_jttyQueueProgress = {};
+ m_jttyQueueProgress.epoch = epoch;
+ m_jttyDisplayedEndSample = 0;
+ }
+
+ QByteArray bytes(reinterpret_cast<char const *> (samples.constData ()),
+ samples.size () * int (sizeof (qint16)));
+ auto const epoch = m_jttyTxLifecycle.epoch ();
+ qint64 const enqueueId = ++m_jttyEnqueueId;
+ bool const firstPending = !m_jttyTxLifecycle.hasPending ();
+ if (!m_jttyTxLifecycle.addPending (enqueueId, requestId)) {
+ Q_EMIT jttyTextRejected(requestId, JttyTxRejectReason::Aborted);
+ return;
+ }
+ m_pendingJttyMessages.append(PendingJttyMessage {
+ epoch, enqueueId, requestId, samples.size (), message, newSession
+ });
+ m_jttyTxWatchdog.stop ();
+ if (firstPending) {
+ m_jttyEnqueueWatchdog.start (
+ int (m_jttyTxLifecycle.preacceptanceTimeout ().count ()));
+ }
+ updateModeControlLock ();
+
+ if (m_jttyTxLifecycle.backend () == JttyTxLifecycle::Backend::Tci) {
+ Q_EMIT m_config.transceiver_enqueue_jtty_pcm(bytes, epoch, enqueueId);
+ } else {
+ Q_EMIT enqueueJttyStream(bytes, epoch, enqueueId);
+ }
+}
+
+qint64 MainWindow::jttyTxCommittedSamples() const
+{
+ return m_jttyTxLifecycle.committedTotal ();
+}
+
+void MainWindow::completeJttyTxEnqueue(qint64 requestId, QString const& message,
+ TxAudioQueueProgress progress,
+ bool newSession, bool useTciAudio)
+{
+ if (newSession) {
+ beginTxEvidenceSession ();
+ }
+ bool const firstSegment = m_jttyTransmitQueue.commitNext (progress.total_samples);
+ m_jttyQueueProgress = progress;
+ if (m_txEvidenceGeneration.isValid () &&
+ m_txEvidenceSourceSession == m_txEvidenceSession) {
+ m_txPlaybackDiagnostics.commitTarget (m_txEvidenceSession,
+ m_txEvidenceGeneration,
+ progress.total_samples - 1, false);
+ auto const sessionId = m_txEvidenceSession;
+ auto const generation = m_txEvidenceGeneration;
+ auto const totalSamples = progress.total_samples;
+ QTimer::singleShot (0, this, [this, sessionId, generation, totalSamples] {
+ LOG_INFO (QString ("TX playout evidence JTTY target commit session=%1 generation=%2 total=%3\n%4")
+ .arg (sessionId.value ()).arg (generation.value ())
+ .arg (totalSamples).arg (m_txPlaybackDiagnostics.diagnosticDump ()));
+ });
+ }
+ updateModeControlLock ();
+ if (!m_transmitting) {
+ m_transmitting = true;
+ transmitDisplay (true);
+ }
+ updateJttyTransmitDisplay (progress.served_samples);
+ updateJttySendButton ();
+ if (firstSegment) {
+ handleJttyContestSerial (message);
+ Q_EMIT jttyTextAccepted (requestId);
+ }
+
+ // Fault-detector watchdog: generous margin over all audio still to play (the
+ // whole queued session, not just this message). The happy path completes via
+ // the backend drain signal well before this fires.
+ qint64 const pendingSamples = useTciAudio
+ ? progress.total_samples : progress.queued_samples;
+ int pendingMs = int(pendingSamples / 48);
+ if (!m_jttyTxLifecycle.hasPending ()) {
+ startJttyTxWatchdog(pendingMs + 1000 * m_config.txDelay() + 10000);
+ }
+
+ if (m_monitoring && !ui->actionFull_Duplex_Mode->isChecked())
+ monitor(false);
+
+#ifdef WIN32
+ if (m_mmttyif) {
+ m_mmttyif->report_ptt_state(true);
+ }
+#endif
+
+ // Only a new session starts transmit; a message appended to an already-active
+ // session chains gaplessly (soundcard) via the enqueue above. When PTT is not
+ // yet up, guiUpdate keys it and ptt1Timer -> startTx2 -> transmit starts the
+ // stream with the normal lead.
+ if (newSession && g_iptt == 1 && !m_modulator->isActive()) {
+ startTx2();
+ }
+ feedJttyTransmitQueue ();
+}
+
+void MainWindow::onJttyBackendProgress(TxAudioQueueProgress progress)
+{
+ if (!m_jttyTxLifecycle.active ()
+ || progress.epoch != m_jttyTxLifecycle.epoch ()
+ || progress.served_samples < m_jttyQueueProgress.served_samples
+ || progress.total_samples != m_jttyTxLifecycle.committedTotal ()) return;
+ m_jttyQueueProgress = progress;
+ updateJttyTransmitDisplay (progress.served_samples);
+ feedJttyTransmitQueue ();
+ updateJttySendButton ();
+ if (m_mode == "JTTY" && !m_jttyLiveEntryPending.isEmpty ()) {
+ m_guardingJttyLiveEntryLock = true;
+ applyJttyLiveEntryFormatting ();
+ m_guardingJttyLiveEntryLock = false;
+ updateJttyLiveEntryFrameLabel ();
+ }
+}
+
+void MainWindow::updateJttyTransmitDisplay(qint64 servedSamples)
+{
+ for (auto const& request : m_jttyTransmitQueue.requests ()) {
+ for (auto const& segment : request.segments) {
+ if (!segment.endSample || segment.endSample <= m_jttyDisplayedEndSample
+ || segment.endSample - segment.sampleCount () >= servedSamples) continue;
+ m_jttyDisplayedEndSample = segment.endSample;
+ if (Jtty::isJttyFillerText (segment.text)) continue; // idle-padding; never shown
+ m_currentMessage = segment.text;
+ write_all ("Tx", segment.text);
+ auto const resolved = DecodeHighlightingModel::resolve_colors (
+ m_config.decode_highlighting ().items (),
+ {DecodeHighlightingModel::Highlight::Tx}, QColor (Qt::yellow),
+ QColor (Qt::black));
+ JttyReceiveLine::Presentation const presentation {
+ 0, request.id, QDateTime::currentDateTimeUtc (), 0.0,
+ segment.frequency, segment.text, -10, true,
+ resolved.background_, resolved.foreground_};
+ JttyReceiveLine::Options const options {
+ ui->cbLowerCase->isChecked (), ui->cbIncludeTime->isChecked ()};
+ JttyReceiveLine txLine;
+ auto const cursor = txLine.render (*ui->decodedTextBrowser2->document (),
+ presentation, options, ui->decodedTextBrowser2->contentFont ());
+ if (!cursor.isNull ()) {
+ ui->decodedTextBrowser2->setTextCursor (cursor);
+ ui->decodedTextBrowser2->ensureCursorVisible ();
+ }
+#ifdef WIN32
+ if (m_mmttyif) m_mmttyif->echo_message_to_n1mm (append_separator (segment.text));
+#endif
+ }
+ }
+}
+
+void MainWindow::updateJttySendButton()
+{
+ int const left = m_jttyTransmitQueue.remainingSegments (
+ m_jttyQueueProgress.served_samples);
+ QString text = tr ("Send message");
+ QString tooltip = tr ("Ctrl+K sends now (one-shot); Alt+J starts a live session until Alt+K signs off. Ctrl+Shift+K clears the box. Halt Tx or Esc cancels pending text.");
+ if (!m_jttyTransmitQueue.empty ()) {
+ text = left ? tr ("Send (%1 left)").arg (left) : tr ("Send (finishing)");
+ tooltip += "\n\n" + tr ("Pending text:") + "\n"
+ + m_jttyTransmitQueue.pendingText (m_jttyQueueProgress.served_samples);
+ }
+ if (!m_jttyQueueNotice.isEmpty ()) tooltip += "\n\n" + m_jttyQueueNotice;
+ if (ui->pbSendMessage->text () != text) ui->pbSendMessage->setText (text);
+ if (ui->pbSendMessage->toolTip () != tooltip) {
+ ui->pbSendMessage->setToolTip (tooltip);
+ ui->pbSendMessage->setAccessibleDescription (tooltip);
+ }
+ updateModeControlLock ();
+}
+
+void MainWindow::handleJttyContestSerial(QString const& message)
+{
+ if(message.left(3).compare("TU ", Qt::CaseInsensitive) == 0) {
+ logQSOTimer.start(0);
+ int nr = ui->sbSerialNumber_2->value();
+ m_xSent = QString::number(nr);
+ ui->sbSerialNumber_2->setValue(nr+1);
+ }
+}
+
+void MainWindow::abort_jtty_tx()
+{
+ noteTxStopReason (TxEvidence::TxStopReason::UserHalt);
+ stopTx();
+
+#ifdef WIN32
+ if (m_mmttyif) {
+ m_mmttyif->report_ptt_state(false);
+ }
+ finalizeMmttyExternalAbort ();
+#endif
+}
+
+void MainWindow::interruptJttyTx()
+{
+ auto const stop = m_jttyTxLifecycle.stopContext ();
+ if (!stop) {
+ return;
+ }
+ // Halt Tx/Esc is a decisive stop -- don't let a still-armed session silently resurrect a new transmission later; resuming needs another explicit Alt+J or Ctrl+K.
+ m_jttyLiveEntryArmed = false;
+ m_jttyAutoAdvanceIdleTimer.stop ();
+
+ if (stop->backend == JttyTxLifecycle::Backend::Local) {
+ auto const progress = m_jttyTxQueue->progress ();
+ captureJttyTxEvidenceTotals (progress.served_samples,
+ stop->progress.total_samples,
+ QStringLiteral ("JTTY source totals captured before abort"));
+ } else {
+ captureJttyTxEvidenceTotals (-1, stop->progress.total_samples,
+ QStringLiteral ("TCI JTTY committed total captured before abort"));
+ }
+ rejectPendingJttyMessages(JttyTxRejectReason::Aborted);
+ auto const cancelled = m_jttyTransmitQueue.cancel ();
+ for (auto requestId : cancelled) {
+ bool const awaitingBackend = std::any_of (
+ m_pendingJttyMessages.cbegin (), m_pendingJttyMessages.cend (),
+ [requestId] (PendingJttyMessage const& pending) {
+ return pending.requestId == requestId;
+ });
+ if (!awaitingBackend) {
+ Q_EMIT jttyTextRejected (requestId, JttyTxRejectReason::Aborted);
+ }
+ }
+ m_jttyQueueNotice = tr ("JTTY transmission cancelled; some text may already have transmitted.");
+ updateJttySendButton ();
+ m_jttyTxLifecycle.failAll ();
+ m_pendingJttyMessages.clear();
+ m_jttyEnqueueWatchdog.stop ();
+ auto const resetEpoch = TxAudioQueueEpoch {stop->epoch.value () + 1};
+ if (stop->backend == JttyTxLifecycle::Backend::Tci) {
+ Q_EMIT m_config.transceiver_clear_jtty_pcm(resetEpoch);
+ } else {
+ Q_EMIT clearJttyStream(resetEpoch);
+ }
+}
+
+void MainWindow::onJttyBackendDrained(TxAudioQueueDrainState drain)
+{
+ feedJttyTransmitQueue ();
+ if (m_jttyTxLifecycle.hasPending ()
+ || m_jttyTransmitQueue.hasUncommitted ()) return;
+ auto const ready = m_jttyTxLifecycle.observeDrain (drain.epoch,
+ drain.total_at_drain);
+ if (ready) finishJttyDrain (*ready);
+}
+
+void MainWindow::finishJttyDrain(JttyTxLifecycle::Drain const& drain)
+{
+ auto const backend = m_jttyTxLifecycle.backend ();
+ qint64 const servedAtDrain = backend == JttyTxLifecycle::Backend::Tci
+ ? drain.total : m_jttyTxQueue->progress ().served_samples;
+ captureJttyTxEvidenceTotals (servedAtDrain, drain.total,
+ QStringLiteral ("JTTY source totals captured at drain"));
+
+ updateJttyTransmitDisplay (drain.total);
+ auto const completedRequestIds = m_jttyTransmitQueue.complete (drain.total);
+ for (auto requestId : completedRequestIds) {
+ Q_EMIT jttyTextCompleted (requestId);
+ }
+ if (!m_jttyTransmitQueue.empty ()) {
+ feedJttyTransmitQueue ();
+ updateJttySendButton ();
+ return;
+ }
+ // Still armed: top up with more filler instead of dropping PTT, keeping the same transmission going rather than ending it and re-keying whenever real content does arrive.
+ if (m_mode == "JTTY" && m_jttyLiveEntryArmed) {
+ sendJttyFillerPadding ();
+ updateJttySendButton ();
+ return;
+ }
+ stopTx();
+ m_jttyQueueNotice = tr ("JTTY transmission complete.");
+ updateJttySendButton ();
+ Q_EMIT jttySessionDrained(drain.epoch.value ());
+}
+
+void MainWindow::onJttyBackendEnqueueAccepted(qint64 enqueueId, qint64 sampleCount,
+ TxAudioQueueProgress progress)
+{
+ for (int i = 0; i < m_pendingJttyMessages.size (); ++i) {
+ auto const pending = m_pendingJttyMessages.at (i);
+ if (pending.epoch != progress.epoch || pending.enqueueId != enqueueId) {
+ continue;
+ }
+
+ auto const previousTotal = m_jttyTxLifecycle.committedTotal ();
+ auto const resolved = m_jttyTxLifecycle.accept (progress.epoch, enqueueId,
+ progress);
+ if (!resolved.pending) return;
+ m_pendingJttyMessages.remove (i);
+ if (!m_jttyTxLifecycle.hasPending ()) m_jttyEnqueueWatchdog.stop ();
+ if (sampleCount != pending.sampleCount) {
+ LOG_WARN("JTTY transmit backend accepted unexpected PCM sample count");
+ }
+ bool const startsSession = pending.newSession || previousTotal <= 0;
+ completeJttyTxEnqueue(pending.requestId, pending.message, progress,
+ startsSession,
+ m_jttyTxLifecycle.backend () == JttyTxLifecycle::Backend::Tci);
+ if (resolved.drain) finishJttyDrain (*resolved.drain);
+ return;
+ }
+}
+
+void MainWindow::onJttyBackendEnqueueFailed(TxAudioQueueEpoch epoch,
+ qint64 enqueueId,
+ TxAudioQueueEnqueueFailure failure)
+{
+ LOG_WARN("JTTY transmit backend rejected PCM enqueue");
+ for (int i = 0; i < m_pendingJttyMessages.size (); ++i) {
+ auto const pending = m_pendingJttyMessages.at (i);
+ if (pending.epoch != epoch || pending.enqueueId != enqueueId) {
+ continue;
+ }
+ auto const resolved = m_jttyTxLifecycle.fail (epoch, enqueueId);
+ if (!resolved.pending) return;
+ m_pendingJttyMessages.remove (i);
+ if (!m_jttyTxLifecycle.hasPending ()) m_jttyEnqueueWatchdog.stop ();
+ JttyTxRejectReason reason {JttyTxRejectReason::BackendRejected};
+ switch (failure) {
+ case TxAudioQueueEnqueueFailure::Capacity:
+ reason = JttyTxRejectReason::QueueFull;
+ break;
+ case TxAudioQueueEnqueueFailure::BackendUnavailable:
+ reason = JttyTxRejectReason::NotAvailable;
+ break;
+ case TxAudioQueueEnqueueFailure::StaleEpoch:
+ reason = JttyTxRejectReason::Aborted;
+ break;
+ case TxAudioQueueEnqueueFailure::None:
+ break;
+ }
+ Q_EMIT jttyTextRejected(pending.requestId, reason);
+ auto const cancelled = m_jttyTransmitQueue.cancel ();
+ for (auto requestId : cancelled) {
+ if (requestId != pending.requestId) {
+ Q_EMIT jttyTextRejected (requestId, JttyTxRejectReason::Aborted);
+ }
+ }
+ m_jttyQueueNotice = tr ("The audio backend rejected a JTTY segment.");
+ updateJttySendButton ();
+ if (resolved.drain) {
+ finishJttyDrain (*resolved.drain);
+ } else if (!m_jttyTxLifecycle.hasPending ()
+ && m_jttyTxLifecycle.committedTotal () <= 0) {
+ stopTx ();
+ } else if (!m_jttyTxLifecycle.hasPending ()) {
+ auto progress = m_jttyTxLifecycle.progress ();
+ if (m_jttyTxLifecycle.backend () == JttyTxLifecycle::Backend::Local) {
+ progress = m_jttyTxQueue->progress ();
+ }
+ qint64 const pendingSamples =
+ m_jttyTxLifecycle.backend () == JttyTxLifecycle::Backend::Tci
+ ? progress.total_samples : progress.queued_samples;
+ startJttyTxWatchdog (
+ int (pendingSamples / 48) + 1000 * m_config.txDelay () + 10000);
+ }
+ return;
+ }
+}
+
+void MainWindow::rejectPendingJttyMessages(JttyTxRejectReason reason)
+{
+ for (auto const& pending : m_pendingJttyMessages) {
+ Q_EMIT jttyTextRejected(pending.requestId, reason);
+ }
+}
+
+void MainWindow::handleJttyEnqueueTimeout()
+{
+ if (!m_jttyTxLifecycle.hasPending ()) return;
+
+ LOG_WARN("JTTY transmit backend enqueue acknowledgement timed out");
+ noteTxStopReason (TxEvidence::TxStopReason::Watchdog);
+ QVector<qint64> timedOutRequests;
+ for (auto const& pending : m_pendingJttyMessages) {
+ if (!timedOutRequests.contains (pending.requestId)) {
+ timedOutRequests.append (pending.requestId);
+ }
+ }
+ rejectPendingJttyMessages(JttyTxRejectReason::BackendTimedOut);
+ auto const cancelled = m_jttyTransmitQueue.cancel ();
+ for (auto requestId : cancelled) {
+ if (!timedOutRequests.contains (requestId)) {
+ Q_EMIT jttyTextRejected (requestId, JttyTxRejectReason::Aborted);
+ }
+ }
+ m_jttyQueueNotice = tr ("The JTTY audio backend timed out.");
+ updateJttySendButton ();
+ m_jttyTxLifecycle.failAll ();
+ m_pendingJttyMessages.clear ();
+ stopTx ();
+#ifdef WIN32
+ if (m_mmttyif) m_mmttyif->report_ptt_state(false);
+ finalizeMmttyExternalAbort ();
+#endif
+}
+
+void MainWindow::handleJttyTxWatchdog()
+{
+ if (!m_jttyTxLifecycle.active ()) {
+ return;
+ }
+
+ LOG_WARN("JTTY transmit completion watchdog expired");
+ noteTxStopReason (TxEvidence::TxStopReason::Watchdog);
+ stopTx();
+#ifdef WIN32
+ if (m_mmttyif) {
+ m_mmttyif->report_ptt_state(false);
+ }
+ finalizeMmttyExternalAbort ();
+#endif
+}
+
+void MainWindow::startJttyTxWatchdog(int durationMs)
+{
+ if (durationMs > 0) {
+ m_jttyTxWatchdog.start(durationMs);
+ }
+}
+
+void MainWindow::jtty_again()
+{
+ startJttyReview(0, 0, false);
+}
+
+void MainWindow::jttyDecodeAgainAtSample(quint64 reception, qint64 sample)
+{
+ startJttyReview(reception, sample, true);
+}
+
+bool MainWindow::jtty_key_struck(QKeyEvent * e)
+{
+ if(e->key() == Qt::Key_Escape) {
+ abort_jtty_tx();
+ return true;
+ }
+ int const functionKey=e->key()-Qt::Key_F1+1;
+ if(functionKey < 1 || functionKey > 8) return false;
+ return sendJttyFunctionKey(functionKey);
+}
+
+bool MainWindow::sendJttyFunctionKey(int index)
+{
+ QString macro;
+ switch(index) {
+ case 1: macro=ui->msg1->text(); break;
+ case 2: macro=ui->msg2->text(); break;
+ case 3: macro=ui->msg3->text(); break;
+ case 4: macro=ui->msg4->text(); break;
+ case 5: macro=ui->msg5->text(); break;
+ case 6: macro=ui->msg6->text(); break;
+ case 7: macro=ui->msg7->text(); break;
+ case 8: macro=ui->msg8->text(); break;
+ default: return false;
+ }
+ if(macro.simplified().isEmpty()) return false;
+
+ auto const context = jttyNativeMacroContext(
+ m_config, m_hisCall, ui->sbSerialNumber_2->value(), m_jttyHisCallSnr);
+ auto const compiled=Jtty::compileNativeMacro(macro,context);
+ if(compiled.status == Jtty::NativeMacroStatus::LiteralFallback) {
+ jtty_tx(compiled.text);
+ return true;
+ }
+
+ qint64 const requestId=++m_jttyTxRequestId;
+ if(compiled.status == Jtty::NativeMacroStatus::InvalidRuntime) {
+ LOG_WARN(QStringLiteral("JTTY native macro rejected: %1").arg(compiled.error));
+ Q_EMIT jttyTextRejected(requestId,JttyTxRejectReason::EncodingFailed);
+ return true;
+ }
+
+ int itone[944];
+ int nsym=0;
+ int encodeStatus=static_cast<int>(Jtty::NativeEncodeStatus::InvalidDescriptor);
+ genjtty_atoms_c(compiled.atoms.constData(),compiled.atoms.size(),itone,&nsym,
+ &encodeStatus);
+ if(nsym <= 0) {
+ LOG_WARN(QStringLiteral("JTTY native macro rejected: %1")
+ .arg(jttyNativeEncodeError(encodeStatus)));
+ Q_EMIT jttyTextRejected(requestId,JttyTxRejectReason::EncodingFailed);
+ return true;
+ }
+ enqueueJttyToneSegment(requestId, compiled.text, itone, nsym);
+ return true;
+}
+
+QString MainWindow::jtty_msg_expand(QString t)
+{
+ auto const context = jttyNativeMacroContext(
+ m_config, m_hisCall, ui->sbSerialNumber_2->value(), m_jttyHisCallSnr);
+ return Jtty::expandLiteralMacro(t, context);
+}
+
+void MainWindow::on_RxFreqSpinBox_2_valueChanged(int n)
+{
+ ui->RxFreqSpinBox->setValue(n);
+}
+
+void MainWindow::on_TxFreqSpinBox_2_valueChanged(int n)
+{
+ ui->TxFreqSpinBox->setValue(n);
+}
+
+void MainWindow::on_sbFtol_2_valueChanged (int n)
+{
+ m_wideGraph->setTol(n);
+}
+
+void MainWindow::on_comboBoxJttyStyle_currentIndexChanged(int index)
+{
+ auto const previousStyle = static_cast<Jtty::MessageStyle>(m_jttyMessageStyle);
+ auto const newStyle = static_cast<Jtty::MessageStyle>(index);
+ QLineEdit* const msgFields[8] = {ui->msg1, ui->msg2, ui->msg3, ui->msg4,
+ ui->msg5, ui->msg6, ui->msg7, ui->msg8};
+
+ m_settings->beginGroup("MainWindow");
+ for (int i = 0; i < 8; ++i) {
+ // Save the outgoing style's currently displayed text before switching away,
+ // so in-session edits aren't lost.
+ m_settings->setValue(Jtty::messageStyleSettingsKey(previousStyle, i + 1),
+ msgFields[i]->text());
+ }
+ for (int i = 0; i < 8; ++i) {
+ int const functionKey = i + 1;
+ msgFields[i]->setText(m_settings->value(
+ Jtty::messageStyleSettingsKey(newStyle, functionKey),
+ Jtty::messageStyleDefaultTemplate(newStyle, functionKey)).toString());
+ }
+ m_settings->endGroup();
+ m_jttyMessageStyle = index;
+}
+
+#ifdef WIN32
+void MainWindow::logText(const QString &text) {
+ LOG_INFO(text);
+}
+
+QString MainWindow::jttyRejectReasonText(JttyTxRejectReason reason) const
+{
+ switch (reason) {
+ case JttyTxRejectReason::Empty: return QStringLiteral("empty");
+ case JttyTxRejectReason::EncodingFailed: return QStringLiteral("encoding failed");
+ case JttyTxRejectReason::QueueFull: return QStringLiteral("queue full");
+ case JttyTxRejectReason::BackendRejected: return QStringLiteral("backend rejected");
+ case JttyTxRejectReason::Aborted: return QStringLiteral("aborted");
+ case JttyTxRejectReason::NotAvailable: return QStringLiteral("not available");
+ case JttyTxRejectReason::BackendTimedOut: return QStringLiteral("backend timed out");
+ }
+ return QStringLiteral("unknown");
+}
+
+void MainWindow::handleMmttyTxString(QString message)
+{
+ if (m_mmttyJttyOutput.finishRequested()) {
+ logText(QStringLiteral("MMTTY/N1MM JTTY text ignored after graceful OFF"));
+ return;
+ }
+
+ auto const context = jttyNativeMacroContext(
+ m_config, m_hisCall, ui->sbSerialNumber_2->value(), m_jttyHisCallSnr);
+ auto const compiled = Jtty::compileN1mmMessage(message, context);
+ qint64 const requestId = ++m_jttyTxRequestId;
+ m_mmttyJttyOutput.submit(requestId);
+ if (compiled.status == Jtty::N1mmCompileStatus::Error) {
+ logText(QStringLiteral("MMTTY/N1MM tagged JTTY request %1 rejected: %2")
+ .arg(requestId).arg(compiled.error));
+ Q_EMIT jttyTextRejected(requestId, JttyTxRejectReason::EncodingFailed);
+ return;
+ }
+
+ QString transmitText = compiled.status == Jtty::N1mmCompileStatus::Literal
+ ? compiled.literalText : compiled.canonicalText;
+ if (compiled.status == Jtty::N1mmCompileStatus::Literal) {
+ if (mmttyNeedsHandoff ()) {
+ if (!m_mmttyHandoff.queue (requestId)) {
+ Q_EMIT jttyTextRejected(requestId, JttyTxRejectReason::QueueFull);
+ return;
+ }
+ m_pendingMmttyJttyMessages.append ({requestId, transmitText, {}, true});
+ beginMmttyHandoff ();
+ return;
+ }
+ if (m_mode != QStringLiteral("JTTY")) set_mode (QStringLiteral("JTTY"));
+ execute_jtty_tx (requestId, transmitText);
+ return;
+ }
+ int itone[944] {};
+ int nsym = 0;
+ int encodeStatus = static_cast<int>(Jtty::NativeEncodeStatus::InvalidDescriptor);
+ genjtty_atoms_c(compiled.atoms.constData(), compiled.atoms.size(), itone, &nsym,
+ &encodeStatus);
+ if (nsym <= 0) {
+ logText(QStringLiteral("MMTTY/N1MM tagged JTTY request %1 rejected: %2")
+ .arg(requestId)
+ .arg(jttyNativeEncodeError(encodeStatus)));
+ Q_EMIT jttyTextRejected(requestId, JttyTxRejectReason::EncodingFailed);
+ return;
+ }
+
+ QVector<int> tones;
+ tones.reserve (nsym);
+ for (int i = 0; i < nsym; ++i) tones.append (itone[i]);
+
+ if (mmttyNeedsHandoff ()) {
+ if (!m_mmttyHandoff.queue (requestId)) {
+ Q_EMIT jttyTextRejected(requestId, JttyTxRejectReason::QueueFull);
+ return;
+ }
+ m_pendingMmttyJttyMessages.append ({requestId, transmitText, tones});
+ beginMmttyHandoff ();
+ return;
+ }
+
+ if (m_mode != QStringLiteral("JTTY")) set_mode (QStringLiteral("JTTY"));
+ enqueueJttyToneSegment(requestId, transmitText, tones.constData (), tones.size ());
+}
+
+void MainWindow::handleMmttyStartTx()
+{
+ m_mmttyJttyOutput.start();
+ if (mmttyNeedsHandoff ()) {
+ beginMmttyHandoff ();
+ return;
+ }
+ if (m_mode != QStringLiteral("JTTY")) set_mode (QStringLiteral("JTTY"));
+ startPendingMmttyJttyTx();
+}
+
+void MainWindow::handleMmttyStopTx()
+{
+ if (m_mode != "JTTY" && !m_mmttyHandoff.active ()
+ && !m_jttyTxLifecycle.active ()) {
+ noteTxStopReason (TxEvidence::TxStopReason::UserHalt);
+ stopTx ();
+ }
+ m_mmttyJttyOutput.finish();
+ logText(QStringLiteral("MMTTY/N1MM JTTY OFF requested; waiting for backend drain"));
+ completeMmttyJttyOutput();
+}
+
+void MainWindow::handleMmttyAbortTx()
+{
+ bool const handoffWasActive = m_mmttyHandoff.active ();
+ m_mmttyHandoffWatchdog.stop ();
+ m_pendingMmttyJttyMessages.clear ();
+ m_mmttyHandoff.abort ();
+ m_preserveMmttyOutputDuringStop = false;
+ m_mmttyJttyOutput.abort();
+ if (!handoffWasActive || m_jttyTxLifecycle.active ()) abort_jtty_tx();
+ updateModeControlLock ();
+}
+
+void MainWindow::handleMmttyJttyAccepted(qint64 requestId)
+{
+ if (!m_mmttyJttyOutput.accept(requestId)) return;
+
+ logText(QStringLiteral("MMTTY/N1MM JTTY request %1 accepted").arg(requestId));
+ m_mmttyHandoff.submitted (requestId);
+ if (m_mmttyHandoff.empty () && !m_mmttyHandoff.active ()) {
+ m_mmttyHandoffWatchdog.stop ();
+ }
+ startPendingMmttyJttyTx();
+}
+
+void MainWindow::handleMmttyJttyRejected(qint64 requestId, JttyTxRejectReason reason)
+{
+ if (!m_mmttyJttyOutput.resolve(requestId)) return;
+
+ logText(QStringLiteral("MMTTY/N1MM JTTY request %1 rejected: %2")
+ .arg(requestId)
+ .arg(jttyRejectReasonText(reason)));
+ m_mmttyHandoff.submitted (requestId);
+ if (m_mmttyHandoff.empty () && !m_mmttyHandoff.active ()) {
+ m_mmttyHandoffWatchdog.stop ();
+ }
+ // Backend rejection may reset the audio session after emitting this signal.
+ QTimer::singleShot(0, this, [this] { completeMmttyJttyOutput(); });
+}
+
+void MainWindow::handleMmttyJttyCompleted(qint64 requestId)
+{
+ if (!m_mmttyJttyOutput.resolve(requestId)) return;
+
+ logText(QStringLiteral("MMTTY/N1MM JTTY request %1 completed").arg(requestId));
+}
+
+void MainWindow::handleMmttyJttySessionDrained(qint64 sessionId)
+{
+ Q_UNUSED(sessionId)
+ completeMmttyJttyOutput(true);
+}
+
+void MainWindow::completeMmttyJttyOutput(bool drained)
+{
+ if (m_mmttyJttyOutput.takeCompletion(m_jttyTxLifecycle.active (), drained)
+ && m_mmttyif) {
+ m_mmttyif->report_output_complete();
+ }
+}
+
+void MainWindow::startPendingMmttyJttyTx()
+{
+ if (m_mode != "JTTY" || !m_mmttyJttyOutput.startRequested()
+ || m_mmttyHandoff.active ()) return;
+
+ if (!m_jttyTxLifecycle.active () || jttyTxCommittedSamples () <= 0) {
+ logText(QStringLiteral("MMTTY/N1MM JTTY start deferred until text is accepted"));
+ return;
+ }
+
+ if (g_iptt == 1) {
+ logText(QStringLiteral("MMTTY/N1MM JTTY start ignored; transmitter is already keyed"));
+ m_mmttyJttyOutput.started();
+ return;
+ }
+
+ m_mmttyJttyOutput.started();
+ startTx2();
+}
+
+bool MainWindow::mmttyNeedsHandoff() const
+{
+ if (m_mmttyHandoff.active ()) return true;
+ bool const busy = m_transmitting || m_tune || g_iptt == 1
+ || ptt0Timer.isActive ();
+ return Jtty::MmttyHandoff::SubmitAction::StopThenSubmit
+ == Jtty::MmttyHandoff::planSubmission (
+ true, m_jttyTxLifecycle.active (), busy);
+}
+
+void MainWindow::beginMmttyHandoff()
+{
+ if (m_mmttyHandoff.active ()) return;
+ m_mmttyHandoff.waitForStop ();
+ updateModeControlLock ();
+ if (!m_mmttyHandoffWatchdog.isActive ()) {
+ m_mmttyHandoffWatchdog.start (m_mmttyHandoff.timeoutMs ());
+ }
+ m_preserveMmttyOutputDuringStop = true;
+ noteTxStopReason (TxEvidence::TxStopReason::ModeChange);
+ if (m_tune) stop_tuning ();
+ if (m_transmitting || g_iptt == 1 || m_jttyTxLifecycle.active ()) {
+ stopTx ();
+ } else if (!ptt0Timer.isActive ()) {
+ QTimer::singleShot (0, this, &MainWindow::resumeMmttyHandoff);
+ }
+}
+
+void MainWindow::resumeMmttyHandoff()
+{
+ if (!m_mmttyHandoff.stopCompleted ()) return;
+ m_preserveMmttyOutputDuringStop = false;
+ if (m_mode != QStringLiteral("JTTY")) set_mode (QStringLiteral("JTTY"));
+
+ if (m_pendingMmttyJttyMessages.isEmpty ()) {
+ m_mmttyHandoffWatchdog.stop ();
+ }
+
+ auto const queued = m_pendingMmttyJttyMessages;
+ m_pendingMmttyJttyMessages.clear ();
+ for (auto const& pending : queued) {
+ if (pending.literal) execute_jtty_tx (pending.requestId, pending.message);
+ else enqueueJttyToneSegment (pending.requestId, pending.message,
+ pending.tones.constData (), pending.tones.size ());
+ }
+ startPendingMmttyJttyTx ();
+ updateModeControlLock ();
+}
+
+void MainWindow::handleMmttyHandoffTimeout()
+{
+ auto const notSubmitted = m_pendingMmttyJttyMessages;
+ m_pendingMmttyJttyMessages.clear ();
+ m_mmttyHandoff.expire ();
+ m_preserveMmttyOutputDuringStop = false;
+ for (auto const& pending : notSubmitted) {
+ Q_EMIT jttyTextRejected (pending.requestId,
+ JttyTxRejectReason::BackendTimedOut);
+ }
+ if (m_jttyTxLifecycle.hasPending ()) handleJttyEnqueueTimeout ();
+ finalizeMmttyExternalAbort ();
+}
+
+void MainWindow::finalizeMmttyExternalAbort()
+{
+ m_mmttyHandoffWatchdog.stop ();
+ m_pendingMmttyJttyMessages.clear ();
+ m_mmttyHandoff.abort ();
+ m_preserveMmttyOutputDuringStop = false;
+ updateModeControlLock ();
+ if (!m_mmttyJttyOutput.pending ()) return;
+ m_mmttyJttyOutput.externalAbort ();
+ completeMmttyJttyOutput (true);
+}
+
+void MainWindow::initMMTTY(quint16 port) {
+ if (!m_mmttyif) {
+ m_mmttyif = new MMTTYIF(this);
+ }
+
+ m_mmttyif->initialize(port);
+
+ connect(m_mmttyif, &MMTTYIF::log_message, this, &MainWindow::logText);
+ connect(m_mmttyif, &MMTTYIF::app_tx_string, this, &MainWindow::handleMmttyTxString);
+ connect(m_mmttyif, &MMTTYIF::app_start_tx, this, &MainWindow::handleMmttyStartTx);
+ connect(m_mmttyif, &MMTTYIF::app_stop_tx, this, &MainWindow::handleMmttyStopTx);
+ connect(m_mmttyif, &MMTTYIF::app_abort_tx, this, &MainWindow::handleMmttyAbortTx);
+ connect(this, &MainWindow::jttyTextAccepted, this, &MainWindow::handleMmttyJttyAccepted);
+ connect(this, &MainWindow::jttyTextRejected, this, &MainWindow::handleMmttyJttyRejected);
+ connect(this, &MainWindow::jttyTextCompleted, this, &MainWindow::handleMmttyJttyCompleted);
+ connect(this, &MainWindow::jttySessionDrained, this, &MainWindow::handleMmttyJttySessionDrained);
+
+ connect(m_mmttyif, &MMTTYIF::inactivity_timeout, qApp, &QCoreApplication::quit);
+ connect(m_mmttyif, &MMTTYIF::app_is_quitting, this, [this]() {
+ abort_jtty_tx();
+ close();
+ });
+
+ QTimer::singleShot(3000, this, [this]() {
+ bool const idle = !m_transmitting && !m_tune && g_iptt != 1
+ && !ptt0Timer.isActive () && !m_jttyTxLifecycle.active ()
+ && !m_mmttyHandoff.active ();
+ if (idle && m_mode != "JTTY") set_mode("JTTY");
+ });
+}
+
+MMTTYIF *MainWindow::getMmttyIf() const {
+ return m_mmttyif;
+}
+#endif
diff --git a/widgets/mainwindow_jtty_receive.cpp b/widgets/mainwindow_jtty_receive.cpp new file mode 100644 index 00000000..ae23d907 --- /dev/null +++ b/widgets/mainwindow_jtty_receive.cpp @@ -0,0 +1,807 @@ +#include "mainwindow.h" +#include "ui_mainwindow.h" +#include "widegraph.h" +#include "JttyDecoder.hpp" +#include "JttyReceiveHistory.hpp" +#include "JttyRecording.hpp" +#include "JttySpectrum.hpp" +#include "JttyMessages.hpp" +#include "JttyReceiveLine.hpp" +#include "JttyReceiveResultController.hpp" +#include "JttyReceiveTiming.hpp" +#include "Detector/Detector.hpp" +#include "Logger.hpp" +#ifdef WIN32 +#include "MMTTYIF.hpp" +#undef MessageBox +#endif +#include <QElapsedTimer> +#include <QEventLoop> +#include <QTextCursor> +#include <QScrollBar> +#include <algorithm> +#include <deque> + +extern dec_data_t& dec_data; +extern "C" void refspectrum_(short*, int*, bool*, bool*, bool*, char const*, fortran_charlen_t); + +namespace { +constexpr qint64 stepSamples = Jtty::receiveFrameSamples / 4; +constexpr qint64 windowSamples = Jtty::receiveFrameSamples + stepSamples; + +JttyRecording::SavePolicy savePolicy(bool all, bool decoded) +{ + return all ? JttyRecording::SavePolicy::All + : decoded ? JttyRecording::SavePolicy::Decoded : JttyRecording::SavePolicy::Off; +} + +struct ReceiveSpan { + quint64 id = 0; + quint64 contextId = 0; + quint64 displayGroup = 0; + QDateTime anchor; + QDateTime displayAnchor; + DecodeOperatingContext context; + JttyRecording::Settings recording; + int low = 200, high = 2800; + float center = 1500, tolerance = 50; +}; + +void renderLine(DisplayText* browser, JttyReceiveLine::Presentation const& presentation, + JttyReceiveLine::Options const& options, JttyReceiveLine& line, bool chronological) +{ + auto cursor = line.render(*browser->document(), presentation, options, browser->contentFont(), chronological); + if (cursor.isNull()) return; + browser->setTextCursor(cursor); + browser->ensureCursorVisible(); +} +} + +struct MainWindow::JttyReceiveState { + using Results = Jtty::ReceiveResultController; + using DecodeSource = Results::Source; + Jtty::ReceiveHistory history; + QMap<quint64, ReceiveSpan> spans; + ReceiveSpan liveSpan, reviewSpan, diskSpan; + QMap<quint64, ReceiveSpan> contexts; + quint64 nextContext = 0, currentContext = 0, nextDrain = 0, nextReplay = quint64(1) << 62; + quint64 nextDisplayGroup = 0; + Jtty::Decoder live, review, diskDecoder; + JttySpectrum spectrum, diskSpectrum; + JttyRecording recording; + Results results; + JttyReceiveMailboxPtr liveMailbox; + std::deque<JttyReceiveMailboxPtr> mailboxes; + struct ReviewJob { ReceiveSpan span; qint64 first, stop; std::vector<short> pcm; bool picked; }; + std::deque<ReviewJob> jobs; + bool scheduled = false, pumping = false, active = false, reviewing = false; + bool disk = false, continuous = false; + bool draining = false, drainCutoff = false, closeAfterDrain = false; + std::function<void()> drainProgress; +#if defined(WSJT_ENABLE_LIVE_AUDIO_TEST) + int drainIgnoredSources = 0; + int drainTimeoutMs = 5000; +#endif + int diskK = -1; + int referenceMode = -1; + qint64 acknowledged = -1; + JttyRecording::SavePolicy policy = JttyRecording::SavePolicy::Off; + + void apply(MainWindow& window, QVector<Jtty::ReceiveUpdate> const& updates, + ReceiveSpan const& span, DecodeSource source) + { + Results::Reception const reception {source, span.contextId, span.displayGroup, + span.anchor, span.displayAnchor, span.context, span.center, span.tolerance}; + Results::Inputs const inputs { + [&window] { return JttyReceiveLine::Options {window.ui->cbLowerCase->isChecked(), + window.ui->cbIncludeTime->isChecked()}; }, + [&window, this] { return Results::Selection {window.m_mode == "JTTY", currentContext, + float(window.ui->RxFreqSpinBox_2->value()), float(window.ui->sbFtol_2->value())}; }, + [&window] { +#ifdef WIN32 + return Results::EchoOptions {bool(window.m_mmttyif), window.ui->cbLowerCase->isChecked()}; +#else + Q_UNUSED(window); + return Results::EchoOptions {}; +#endif + }, + [&window] { return window.m_config.spot_to_psk_reporter(); } + }; + Results::Effects const effects { + [&window](Results::Pane pane) { + auto* browser = pane == Results::Pane::All + ? window.ui->decodedTextBrowser : window.ui->decodedTextBrowser2; + browser->insertLineSpacer(MainWindow::tr("JTTY review")); + }, + [&window](Results::Pane pane, JttyReceiveLine& line, + JttyReceiveLine::Presentation const& presentation, + JttyReceiveLine::Options const& options) { + auto* browser = pane == Results::Pane::All + ? window.ui->decodedTextBrowser : window.ui->decodedTextBrowser2; + renderLine(browser, presentation, options, line, pane == Results::Pane::All); + }, + [&window](QString const& text) { +#ifdef WIN32 + window.m_mmttyif->echo_message_to_n1mm(text); +#else + Q_UNUSED(window); + Q_UNUSED(text); +#endif + }, + [this](qint64 first, qint64 last) { recording.noteDecoded(first, last); }, + [&window](QString const& text, DecodeOperatingContext const& context) { + window.write_all("Rx", text, &context); + }, + [&window](Results::Spot const& spot) { + if (!window.m_psk_Reporter.addRemoteStation(spot.sender, spot.grid, spot.frequency, + spot.mode, spot.snr, spot.time)) + window.showStatusMessage(MainWindow::tr("PSK Reporter spot queue full; oldest spot dropped")); + } + }; + results.apply(updates, reception, inputs, effects); + } +}; + +int MainWindow::jttySnrForSelectedWord(QString const& word, bool leftPane) const +{ + if (!m_jttyReceive) return -10; + return m_jttyReceive->results.snrForSelectedWord(word, + leftPane ? Jtty::ReceiveResultController::Pane::All : Jtty::ReceiveResultController::Pane::Qso); +} + +void MainWindow::refreshJttyReceiveLines() +{ + JttyReceiveLine::Options const options {ui->cbLowerCase->isChecked(), ui->cbIncludeTime->isChecked()}; + for (auto* pane : {ui->decodedTextBrowser, ui->decodedTextBrowser2}) { + auto* scroll = pane->verticalScrollBar(); + bool const atEnd = scroll->value() == scroll->maximum(); + auto const anchor = pane->cursorForPosition(QPoint(1, 1)); + int const offset = pane->cursorRect(anchor).top(); + JttyReceiveLine::refresh(*pane->document(), options, pane->contentFont()); + scroll->setValue(atEnd ? scroll->maximum() + : scroll->value() + pane->cursorRect(anchor).top() - offset); + } +} + +void MainWindow::on_cbLowerCase_toggled(bool) +{ + if (m_mode == "JTTY") refreshJttyReceiveLines(); +} + +void MainWindow::cancelJttyReview() +{ + if (!m_jttyReceive) return; + auto& state = *m_jttyReceive; + bool const hadReview = state.reviewing || !state.jobs.empty(); + if (!hadReview) return; + state.jobs.clear(); + state.review.end(); + state.review.takeUpdates(); + state.reviewing = false; + state.results.resetReplay(); + if (hadReview && !state.disk) ui->DecodeButton->setChecked(false); +} + +void MainWindow::initializeJttyReceive() +{ + if (m_jttyReceive) return; + m_jttyReceive = std::make_shared<JttyReceiveState>(); + m_jttyReceive->recording.setErrorHandler([this](QString const& error) { + LOG_WARN("JTTY recording stopped: " << error.toStdString()); + statusBar()->showMessage(tr("JTTY recording stopped: %1. Change the save setting to retry.").arg(error)); + }); +} + +void MainWindow::updateJttyReceivePolicy(bool continuous) +{ + if (continuous && jttyDrainInProgress()) return; + if (!continuous && !m_jttyReceive) return; + initializeJttyReceive(); + auto& state = *m_jttyReceive; + if (continuous && !state.continuous) updateJttyReceiveContext(); + state.continuous = continuous; + auto policy = continuous ? ReceivePolicy::ContinuousJtty : ReceivePolicy::Timed; + m_detector->setReceivePolicy(policy); + m_config.transceiver_receive_policy(policy); + if (!continuous) cancelJttyReview(); +} + +void MainWindow::updateJttyReceiveContext() +{ + if (jttyDrainInProgress()) return; + initializeJttyReceive(); + auto& state = *m_jttyReceive; + ReceiveSpan span; + span.contextId = ++state.nextContext; + span.context = currentDecodeOperatingContext(); + span.context.diskData = false; + span.context.periodFrequency = m_operatingFrequency.rx(); + span.recording.directory = m_config.save_directory().absolutePath(); + span.recording.myCall = m_config.my_callsign(); span.recording.myGrid = m_config.my_grid(); + span.recording.hisCall = m_hisCall; span.recording.hisGrid = m_hisGrid; + span.recording.frequency = m_operatingFrequency.rx(); + span.low = m_wideGraph->nStartFreq(); span.high = m_wideGraph->Fmax(); + span.center = ui->RxFreqSpinBox_2->value(); span.tolerance = ui->sbFtol_2->value(); + state.currentContext = span.contextId; + state.contexts.insert(span.contextId, span); + // The two bounded mailboxes retain at most 2,048 events, including Begin. + while (state.contexts.size() > 2048) state.contexts.erase(state.contexts.begin()); + m_detector->setReceiveContext(m_tci_audio ? 0 : span.contextId); + m_config.transceiver_receive_context(m_tci_audio ? span.contextId : 0); +} + +void MainWindow::updateJttySavePolicy() +{ + if (!m_jttyReceive) return; + auto& state = *m_jttyReceive; + state.policy = savePolicy(m_saveAll, m_saveDecoded); + state.recording.updateSavePolicy(state.policy); +} + +#if defined(WSJT_ENABLE_LIVE_AUDIO_TEST) +QString MainWindow::checkLiveAudioTestJttyFrequencyChanges() +{ + if (!m_automated_test || !m_config.is_dummy_rig() || m_mode != "JTTY" || !m_jttyReceive) + return "JTTY frequency checks require the isolated test receiver."; + if (!m_operatingFrequency.rx() + && !requestNominalFrequencyChange(14078000, FrequencyRequestOrigin::User)) + return "Unable to initialize the isolated JTTY receiver frequency."; + auto const context = m_jttyReceive->currentContext; + int const audioFrequency = ui->RxFreqSpinBox_2->value(); + ui->RxFreqSpinBox_2->setValue(audioFrequency + 1); + ui->RxFreqSpinBox_2->setValue(audioFrequency); + if (m_jttyReceive->currentContext != context) + return "Changing the JTTY audio-frequency selection ended reception."; + auto const frequency = m_operatingFrequency.rx(); + if (!requestNominalFrequencyChange(frequency, FrequencyRequestOrigin::User) + || m_jttyReceive->currentContext != context) + return "An unchanged JTTY RF frequency reset the receive context."; + if (!requestNominalFrequencyChange(frequency + 100, FrequencyRequestOrigin::User) + || m_jttyReceive->currentContext == context) + return "An actual JTTY RF retune did not replace the receive context."; + if (!requestNominalFrequencyChange(frequency, FrequencyRequestOrigin::User)) + return "Unable to restore the isolated JTTY receiver frequency."; + return {}; +} + +bool MainWindow::startLiveAudioTestJttyWav(QString const& path) +{ + if (!m_automated_test || !m_config.is_dummy_rig() || m_mode != "JTTY" + || m_monitoring || decoderBusy()) return false; + m_diskData = true; + read_wav_file(path); + return true; +} + +QString MainWindow::checkLiveAudioTestJttyMailboxOverflow() +{ + if (!m_automated_test || !m_jttyReceive || m_jttyReceive->active) + return "Mailbox checks require an idle isolated JTTY receiver."; + auto& state = *m_jttyReceive; + JttyReceivePublisher source, otherSource; + source.setContext(state.currentContext); + source.begin(100000); + consumeJttyAudio(source.mailbox()); + pumpJttyReceive(); + if (!state.active) return "The test reception did not begin."; + short const sample = 0; + otherSource.begin(100000); + for (int i = 0; i < 1023; ++i) otherSource.append(&sample, 1); + otherSource.end(JttyReceiveReason::MonitorStopped); + consumeJttyAudio(otherSource.mailbox()); + pumpJttyReceive(); + if (!state.active) return "Another source's overflow ended the active reception."; + source.end(JttyReceiveReason::InputError); + source.begin(101000); + for (int i = 0; i < 1022; ++i) source.append(&sample, 1); + source.end(JttyReceiveReason::MonitorStopped); + consumeJttyAudio(source.mailbox()); + pumpJttyReceive(); + if (state.active) return "Mailbox overflow lost the active reception's end."; + return {}; +} + +QString MainWindow::checkLiveAudioTestJttyDrain() +{ + if (!m_automated_test || !m_config.is_dummy_rig() || m_mode != "JTTY" + || m_monitoring || decoderBusy()) + return "Drain checks require a stopped isolated JTTY receiver."; + auto& state = *m_jttyReceive; + bool const diskData = m_diskData; + bool const saveAll = m_saveAll, saveDecoded = m_saveDecoded; + m_diskData = false; + m_saveAll = m_saveDecoded = false; + QString error; + for (bool missingAcknowledgement : {false, true}) { + updateJttyReceivePolicy(true); + auto const context = state.currentContext; + JttyReceivePublisher source; + source.setContext(context); + source.begin(100000); + std::vector<short> samples(3456); + quint32 noise = 1; + for (auto& sample : samples) { + noise = noise * 1664525u + 1013904223u; + sample = short(int(noise >> 20) - 2048); + } + constexpr int blocks = 64; + for (int i = 0; i < blocks; ++i) source.append(samples.data(), int(samples.size())); + if (!missingAcknowledgement) source.end(JttyReceiveReason::MonitorStopped); + consumeJttyAudio(source.mailbox()); + state.drainIgnoredSources = missingAcknowledgement ? 2 : 0; + state.drainTimeoutMs = missingAcknowledgement ? 1 : 5000; + int progressCallbacks = 0; + qint64 lastSearch = -1; + bool latePublication = false; + bool lateEndNotified = false; + bool playbackStopped = false; + QTimer heartbeat; + connect(this, &MainWindow::endTransmitMessage, &heartbeat, [&] { playbackStopped = true; }); + if (missingAcknowledgement) { + auto const epoch = m_jttyTxLifecycle.begin (JttyTxLifecycle::Backend::Local); + if (!epoch.isValid () || !m_jttyTxLifecycle.addPending (1, 1)) + error = "Could not initialize the synthetic JTTY transmit session."; + } + connect(&heartbeat, &QTimer::timeout, this, [&] { + if (!state.draining) return; + if (state.active && state.live.nextSearchSample() != lastSearch) { + lastSearch = state.live.nextSearchSample(); + ++progressCallbacks; + } + monitor(true); + startJttyReview(0, 0, false); + on_actionFT8_triggered(); + if (m_monitoring || !state.jobs.empty() || m_mode != "JTTY" + || state.currentContext != context) + error = "A reentrant callback replaced the draining JTTY receiver."; + if (state.drainCutoff && !latePublication) { + latePublication = true; + source.append(samples.data(), int(samples.size())); + consumeJttyAudio(source.mailbox()); + } + }); + heartbeat.start(0); + drainJttyReceive(); + heartbeat.stop(); + qint64 const expected = blocks * qint64(samples.size()); + if (state.active || !state.mailboxes.empty() || state.history.end(state.liveSpan.id) != expected + || state.live.nextSearchSample() + windowSamples <= expected) + error = "JTTY drain did not process the complete accepted audio batch."; + if (progressCallbacks < 2) + error = "JTTY drain did not yield between decoder work slices."; + if (missingAcknowledgement && !latePublication) + error = "The missing-acknowledgement drain did not exercise its input cutoff."; + if (missingAcknowledgement && (!playbackStopped + || m_jttyTxLifecycle.active () || m_monitoring)) + error = "JTTY drain did not stop pending playback without restarting reception."; + lateEndNotified = source.end(JttyReceiveReason::MonitorStopped); + if (missingAcknowledgement && !lateEndNotified) + error = "JTTY input cutoff did not rearm the source notification."; + consumeJttyAudio(source.mailbox()); + pumpJttyReceive(); + if (state.active || state.history.end(state.liveSpan.id) != expected) + error = "Late source audio reopened a drained JTTY reception."; + if (!error.isEmpty()) break; + } + state.drainIgnoredSources = 0; + state.drainTimeoutMs = 5000; + updateJttyReceivePolicy(true); + m_diskData = diskData; + m_saveAll = saveAll; + m_saveDecoded = saveDecoded; + updateJttySavePolicy(); + return error; +} +#endif + +void MainWindow::drainJttyReceive() +{ + if (!m_jttyReceive || m_jttyReceive->draining) return; + auto& state = *m_jttyReceive; + state.draining = true; + state.drainCutoff = false; + if (m_wav_load_coordinator.isLoading()) m_discardJttyWavLoad = true; + if (m_mode == "JTTY" + && (m_jttyTxLifecycle.active () || !m_jttyTransmitQueue.empty () + || m_transmitting || m_tune)) { + noteTxStopReason(m_closing ? TxEvidence::TxStopReason::UserHalt : TxEvidence::TxStopReason::ModeChange); + stopTx(); + } + auto const request = ++state.nextDrain; + QEventLoop stopped; + int acknowledged = 0; + bool timedOut = false; + bool finished = false; + auto checkFinished = [&] { + bool const pending = !state.mailboxes.empty() || state.pumping + || (state.active && state.live.nextSearchSample() + windowSamples <= state.history.end(state.liveSpan.id)); + if ((acknowledged == 3 || timedOut) && !pending) { + finished = true; + stopped.quit(); + } + }; + state.drainProgress = checkFinished; + auto acknowledge = [&](int source, quint64 id, JttyReceiveMailboxPtr mailbox) { + if (id != request || timedOut) return; +#if defined(WSJT_ENABLE_LIVE_AUDIO_TEST) + if (state.drainIgnoredSources & source) return; +#endif + consumeJttyAudio(std::move(mailbox)); + acknowledged |= source; + checkFinished(); + }; + auto local = connect(m_detector, &Detector::continuousReceiveDrained, &stopped, + [&](quint64 id, JttyReceiveMailboxPtr mailbox) { acknowledge(1, id, std::move(mailbox)); }); + auto tci = connect(&m_config, &Configuration::continuousReceiveDrained, &stopped, + [&](quint64 id, JttyReceiveMailboxPtr mailbox) { acknowledge(2, id, std::move(mailbox)); }); + QTimer timeout; + timeout.setSingleShot(true); + connect(&timeout, &QTimer::timeout, &stopped, [&] { + if (acknowledged == 3) return; + timedOut = true; + state.drainCutoff = true; + // A missing source barrier must not let later publications extend this drain forever. + for (auto& mailbox : state.mailboxes) { + auto pending = mailbox->detachPending(); + if (state.liveMailbox == mailbox) state.liveMailbox = pending; + mailbox = std::move(pending); + } + LOG_WARN("JTTY input did not acknowledge shutdown before timeout"); + checkFinished(); + }); + statusBar()->showMessage(tr("Finishing JTTY reception…")); + if (m_monitoring) monitor(false); + updateJttyReceivePolicy(false); + m_detector->requestContinuousReceiveDrain(request); + m_config.requestContinuousReceiveDrain(request); + int timeoutMs = 5000; +#if defined(WSJT_ENABLE_LIVE_AUDIO_TEST) + if (m_automated_test) timeoutMs = state.drainTimeoutMs; +#endif + timeout.start(timeoutMs); + if (!state.scheduled) { + state.scheduled = true; + QTimer::singleShot(0, this, &MainWindow::pumpJttyReceive); + } + checkFinished(); + if (!finished) stopped.exec(QEventLoop::ExcludeUserInputEvents); + state.drainProgress = {}; + disconnect(local); disconnect(tci); + finishJttyReception(); + finishJttyDisk(); + state.contexts.clear(); + state.draining = false; + state.drainCutoff = false; + if (timedOut) statusBar()->showMessage(tr("JTTY input did not acknowledge stopping; available audio was drained.")); + else statusBar()->clearMessage(); + if (state.closeAfterDrain) { + state.closeAfterDrain = false; + QTimer::singleShot(0, this, &MainWindow::close); + } +} + +void MainWindow::consumeJttyAudio(JttyReceiveMailboxPtr mailbox) +{ + if (!mailbox) return; + initializeJttyReceive(); + auto& state = *m_jttyReceive; + if (state.drainCutoff) { + mailbox->discardPending(); + return; + } + if (std::find(state.mailboxes.begin(), state.mailboxes.end(), mailbox) == state.mailboxes.end()) + state.mailboxes.push_back(std::move(mailbox)); + if (!state.scheduled) { + state.scheduled = true; + QTimer::singleShot(0, this, &MainWindow::pumpJttyReceive); + } +} + +void MainWindow::finishJttyReception() +{ + if (!m_jttyReceive || !m_jttyReceive->active) return; + auto& state = *m_jttyReceive; + state.live.end(); + state.apply(*this, state.live.takeUpdates(), state.liveSpan, JttyReceiveState::DecodeSource::Live); + state.recording.endReception(); + if (m_mode == "JTTY" && !m_diskData) m_wideGraph->jttyReceptionEnded(); + state.active = false; + state.liveMailbox.reset(); +} + +void MainWindow::restartJttyReception() +{ + auto& state = *m_jttyReceive; + bool const current = state.continuous && state.liveSpan.contextId == state.currentContext; + finishJttyReception(); + if (current) { + m_detector->endContinuousReception(JttyReceiveReason::InputError); + m_config.transceiver_receive_discontinuity(JttyReceiveReason::InputError); + } + statusBar()->showMessage(tr("JTTY receive audio was lost; decoding restarted.")); +} + +void MainWindow::pumpJttyReceive() +{ + if (!m_jttyReceive) return; + auto& state = *m_jttyReceive; + state.scheduled = false; + if (state.pumping) return; + state.pumping = true; + QElapsedTimer budget; + budget.start(); + bool work = true; + while (work && budget.elapsed() < 12) { + work = false; + if (state.active) { + auto const end = state.history.end(state.liveSpan.id); + auto const search = state.live.nextSearchSample(); + if (search + windowSamples <= end) { + bool const current = m_mode == "JTTY" && state.liveSpan.contextId == state.currentContext; + auto const first = state.live.nextRequiredSample(); + auto pcm = state.history.snapshot(state.liveSpan.id, first, search + windowSamples); + int const processed = pcm.empty() ? -2 : state.live.process(pcm.data(), int(pcm.size()), first, + search + windowSamples, 1, + current ? m_wideGraph->nStartFreq() : state.liveSpan.low, + current ? m_wideGraph->Fmax() : state.liveSpan.high, + current ? ui->RxFreqSpinBox_2->value() : state.liveSpan.center, + current ? ui->sbFtol_2->value() : state.liveSpan.tolerance); + if (processed < 0) { + LOG_WARN("JTTY required receive audio unavailable"); + restartJttyReception(); + } else { + state.apply(*this, state.live.takeUpdates(), state.liveSpan, JttyReceiveState::DecodeSource::Live); + state.recording.advanceDecoderWatermark(state.live.nextRequiredSample()); + } + work = processed > 0; + if (work) continue; + } +#if defined(WSJT_ENABLE_LIVE_AUDIO_TEST) + if (m_automated_test && state.acknowledged != end) { + state.acknowledged = end; + Q_EMIT liveAudioTestJttyFramesConsumed(end); + } +#endif + } + if (!state.mailboxes.empty()) { + auto const sourceMailbox = state.mailboxes.front(); + JttyReceiveEvent event; + if (!sourceMailbox->take(event)) { state.mailboxes.pop_front(); work = true; continue; } + work = true; + if (event.kind == JttyReceiveEvent::Kind::Begin) { + if (!state.contexts.contains(event.context)) { + if (event.context) { + LOG_WARN("JTTY operating context expired before input could be processed"); + statusBar()->showMessage(tr("JTTY receive audio was lost; decoding restarted.")); + } + continue; + } + finishJttyReception(); + state.liveSpan = state.contexts[event.context]; + state.liveMailbox = sourceMailbox; + state.liveSpan.id = event.session; + state.liveSpan.displayGroup = ++state.nextDisplayGroup; + state.liveSpan.anchor = QDateTime::fromMSecsSinceEpoch(event.anchorUtcMs, Qt::UTC); + state.liveSpan.displayAnchor = state.liveSpan.anchor; + state.spans[event.session] = state.liveSpan; + state.live.begin(event.session, 0, event.firstSample); + state.spectrum.begin(event.session, event.firstSample, event.anchorUtcMs); + state.policy = savePolicy(m_saveAll, m_saveDecoded); + auto settings = state.liveSpan.recording; + settings.policy = state.policy; + state.recording.beginReception(event.session, state.liveSpan.anchor, settings); + state.active = true; + state.acknowledged = -1; + state.referenceMode = -1; + int zero = 0; + auto path = m_config.writeable_data_dir().absoluteFilePath("refspec.dat").toLocal8Bit(); + refspectrum_(dec_data.d2, &zero, &m_bClearRefSpec, &m_bRefSpec, &m_bUseRef, + path.constData(), path.size()); + } else if (event.kind == JttyReceiveEvent::Kind::Samples && state.active + && event.session == state.liveSpan.id) { + auto& recording = state.liveSpan.recording; + recording.directory = m_config.save_directory().absolutePath(); + recording.myCall = m_config.my_callsign(); recording.myGrid = m_config.my_grid(); + recording.hisCall = m_hisCall; recording.hisGrid = m_hisGrid; + state.recording.updateMetadata(recording); + auto policy = savePolicy(m_saveAll, m_saveDecoded); + if (policy != state.policy) { state.recording.updateSavePolicy(policy); state.policy = policy; } + m_bUseRef = m_wideGraph->useRef(); + auto path = m_config.writeable_data_dir().absoluteFilePath("refspec.dat").toLocal8Bit(); + int const referenceMode = m_bRefSpec ? 1 : m_bUseRef ? 2 : 0; + if (state.referenceMode != referenceMode || m_bClearRefSpec) { + int zero = 0; + refspectrum_(event.samples.data(), &zero, &m_bClearRefSpec, &m_bRefSpec, + &m_bUseRef, path.constData(), path.size()); + state.referenceMode = referenceMode; + } + m_bClearRefSpec = false; + for (int offset = 0; offset < int(event.samples.size());) { + int count = std::min(3456, int(event.samples.size()) - offset); + if (m_bRefSpec || m_bUseRef) + refspectrum_(event.samples.data() + offset, &count, &m_bClearRefSpec, + &m_bRefSpec, &m_bUseRef, path.constData(), path.size()); + offset += count; + } + if (!state.history.append(event.session, event.firstSample, event.samples.data(), int(event.samples.size()))) { + restartJttyReception(); continue; + } + state.recording.feed(event.firstSample, event.samples.data(), int(event.samples.size())); + state.spectrum.process(event.firstSample, event.samples.data(), int(event.samples.size()), m_inGain, + m_config.lowSidelobes(), m_wideGraph->smoothYellow() - 1, [this](JttySpectrumFrame const& frame) { + if (m_mode == "JTTY" && !m_diskData) { + m_wideGraph->jttyDataSink(frame); + ui->signal_meter_widget->setValue(frame.powerDb, frame.maxPowerDb); + } + }); + m_dataAvailable = true; + for (auto it = state.spans.begin(); it != state.spans.end();) { + if (it.key() != state.liveSpan.id && state.history.first(it.key()) < 0) it = state.spans.erase(it); + else ++it; + } + } else if (event.kind == JttyReceiveEvent::Kind::End || event.kind == JttyReceiveEvent::Kind::Gap) { + // Overflow can discard session transitions, so a Gap ends its source mailbox's active reception. + if (event.kind == JttyReceiveEvent::Kind::Gap + ? state.liveMailbox == sourceMailbox + : event.session == state.liveSpan.id) finishJttyReception(); + if (event.kind == JttyReceiveEvent::Kind::Gap) + statusBar()->showMessage(tr("JTTY receive audio was lost; decoding restarted.")); + } + continue; + } + if (!state.jobs.empty() && !state.disk) { + auto& job = state.jobs.front(); + if (!state.reviewing) { + state.review.end(); state.review.takeUpdates(); + state.review.begin(job.span.id, 0, job.first); + state.reviewSpan = job.span; + state.reviewing = true; + } + int steps = state.review.process(job.pcm.data(), int(job.pcm.size()), job.first, job.stop, 1, + job.span.low, job.span.high, job.span.center, job.span.tolerance); + auto updates = state.review.takeUpdates(); + bool done = steps <= 0; + for (auto const& update : updates) + if (job.picked && update.terminal == Jtty::ReceiveTerminal::Complete + && std::abs(update.frequency - job.span.center) < job.span.tolerance) done = true; + state.apply(*this, updates, job.span, JttyReceiveState::DecodeSource::Review); + if (done) { + state.review.end(); + state.apply(*this, state.review.takeUpdates(), job.span, JttyReceiveState::DecodeSource::Review); + state.jobs.pop_front(); state.reviewing = false; + if (state.jobs.empty()) finishDecodeUi(); + } + work = true; + } + } + state.pumping = false; + if (work && !state.scheduled) { + state.scheduled = true; + QTimer::singleShot(0, this, &MainWindow::pumpJttyReceive); + } + if (state.drainProgress) state.drainProgress(); +} + +void MainWindow::startJttyReview(quint64 reception, qint64 sample, bool picked) +{ + if (jttyDrainInProgress()) return; + initializeJttyReceive(); + auto& state = *m_jttyReceive; + if (state.disk) { + statusBar()->showMessage(tr("Wait for the recording to finish decoding before reviewing it.")); + return; + } + cancelJttyReview(); + auto add = [&](ReceiveSpan span, qint64 first, qint64 end, std::vector<short> pcm) { + if (pcm.empty()) return; + span.displayGroup = ++state.nextDisplayGroup; + span.center = ui->RxFreqSpinBox_2->value(); span.tolerance = ui->sbFtol_2->value(); + span.low = m_wideGraph->nStartFreq(); span.high = m_wideGraph->Fmax(); + state.jobs.push_back({span, first, end, std::move(pcm), picked}); + }; + if (m_diskData && (!picked || reception == state.diskSpan.id)) { + qint64 first = picked ? std::max<qint64>(0, sample - 5 * 12000) : 0; + qint64 end = picked ? std::min<qint64>(dec_data.params.kin, first + 40 * 12000) : dec_data.params.kin; + if (end > first && (!picked || (sample > 0 && sample <= dec_data.params.kin))) + add(state.diskSpan, first, end, {dec_data.d2 + first, dec_data.d2 + end}); + } else if (picked) { + auto const firstAvailable = state.history.first(reception); + auto const endAvailable = state.history.end(reception); + if (firstAvailable < 0 || sample <= firstAvailable || sample > endAvailable || !state.spans.contains(reception)) { + statusBar()->showMessage(tr("Audio for this waterfall row is no longer available.")); + finishDecodeUi(); + return; + } + auto const first = std::max(firstAvailable, sample - 5 * 12000); + auto const end = std::min(endAvailable, first + 40 * 12000); + add(state.spans[reception], first, end, state.history.snapshot(reception, first, end)); + } else { + for (auto const& span : state.spans) { + auto first = state.history.first(span.id), end = state.history.end(span.id); + if (first >= 0) add(span, first, end, state.history.snapshot(span.id, first, end)); + } + } + if (!state.jobs.empty()) { + statusBar()->showMessage(tr("Review uses retained audio; earlier message context may be missing.")); + ui->DecodeButton->setChecked(true); + if (!state.scheduled) { state.scheduled = true; QTimer::singleShot(0, this, &MainWindow::pumpJttyReceive); } + } else finishDecodeUi(); +} + +bool MainWindow::jttyReviewBusy() const +{ + return m_jttyReceive && (m_jttyReceive->draining || m_jttyReceive->disk || !m_jttyReceive->jobs.empty()); +} + +bool MainWindow::jttyDrainInProgress() const +{ + return m_jttyReceive && m_jttyReceive->draining; +} + +bool MainWindow::jttyDiskActive() const +{ + return m_jttyReceive && m_jttyReceive->disk; +} + +void MainWindow::closeAfterJttyDrain() +{ + m_jttyReceive->closeAfterDrain = true; +} + +void MainWindow::beginJttyDisk() +{ + initializeJttyReceive(); + auto& state = *m_jttyReceive; + finishJttyDisk(); + cancelJttyReview(); + state.diskSpan = {}; + state.diskSpan.id = ++state.nextReplay; + state.diskSpan.displayGroup = ++state.nextDisplayGroup; + state.diskSpan.anchor = m_UTCdiskDateTime; + state.diskSpan.displayAnchor = Jtty::jttyLineStartTimeUtc(m_UTCdiskDateTime, m_UTCdisk, 0); + state.diskSpan.context = currentDecodeOperatingContext(); + state.diskSpan.context.diskData = true; + state.diskSpan.low = m_wideGraph->nStartFreq(); state.diskSpan.high = m_wideGraph->Fmax(); + state.diskSpan.center = ui->RxFreqSpinBox_2->value(); state.diskSpan.tolerance = ui->sbFtol_2->value(); + state.diskK = -1; + state.results.resetReplay(); +} + +void MainWindow::decodeJttyDisk(int k) +{ + if (!m_diskData) return; + initializeJttyReceive(); + auto& state = *m_jttyReceive; + if (!state.disk || k <= state.diskK) { + finishJttyDisk(); + if (!state.diskSpan.id) beginJttyDisk(); + state.diskDecoder.begin(state.diskSpan.id, 0, 0); + state.diskSpectrum.begin(state.diskSpan.id, 0, state.diskSpan.anchor.toMSecsSinceEpoch()); + state.disk = true; state.diskK = 0; + state.results.resetReplay(); + } + if (k > state.diskK) + state.diskSpectrum.process(state.diskK, dec_data.d2 + state.diskK, k - state.diskK, + m_inGain, m_config.lowSidelobes(), m_wideGraph->smoothYellow() - 1, + [this](JttySpectrumFrame const& frame) { m_wideGraph->jttyDataSink(frame); }); + state.diskK = k; + m_k0 = k; + state.diskDecoder.process(dec_data.d2, k, 0, k, 0x7fffffff, + state.diskSpan.low, state.diskSpan.high, state.diskSpan.center, state.diskSpan.tolerance); + auto updates = state.diskDecoder.takeUpdates(); + state.apply(*this, updates, state.diskSpan, JttyReceiveState::DecodeSource::Wav); +} + +void MainWindow::finishJttyDisk() +{ + if (!m_jttyReceive || !m_jttyReceive->disk) return; + auto& state = *m_jttyReceive; + state.diskDecoder.end(); + state.apply(*this, state.diskDecoder.takeUpdates(), state.diskSpan, JttyReceiveState::DecodeSource::Wav); + m_wideGraph->jttyReceptionEnded(); + state.disk = false; + if (!state.jobs.empty() && !state.scheduled) { + state.scheduled = true; + QTimer::singleShot(0, this, &MainWindow::pumpJttyReceive); + } +} diff --git a/widgets/mainwindow_settings.cpp b/widgets/mainwindow_settings.cpp index f7a99450..262826f3 100644 --- a/widgets/mainwindow_settings.cpp +++ b/widgets/mainwindow_settings.cpp @@ -15,6 +15,7 @@ #include "JttyMessages.hpp" #include <QSettings> +#include <QSignalBlocker> #include <QVariant> #include <QThread> #include <QTimer> @@ -85,14 +86,18 @@ void MainWindow::writeSettings() m_settings->setValue("FoxNslots",m_Nslots0); m_settings->setValue("SerialNumber",ui->sbSerialNumber->value ()); m_settings->setValue("SerialNumberJTTY",ui->sbSerialNumber_2->value ()); - m_settings->setValue("JTTY_msg1",ui->msg1->text()); - m_settings->setValue("JTTY_msg2",ui->msg2->text()); - m_settings->setValue("JTTY_msg3",ui->msg3->text()); - m_settings->setValue("JTTY_msg4",ui->msg4->text()); - m_settings->setValue("JTTY_msg5",ui->msg5->text()); - m_settings->setValue("JTTY_msg6",ui->msg6->text()); - m_settings->setValue("JTTY_msg7",ui->msg7->text()); - m_settings->setValue("JTTY_msg8",ui->msg8->text()); + m_settings->setValue("JTTY_MessageStyle", ui->comboBoxJttyStyle->currentIndex()); + { + // Only the currently active style's displayed text needs saving here -- + // the inactive style's templates were already saved at its last + // switch-away (see MainWindow::on_comboBoxJttyStyle_currentIndexChanged). + auto const style = static_cast<Jtty::MessageStyle>(ui->comboBoxJttyStyle->currentIndex()); + QLineEdit* const msgFields[8] = {ui->msg1, ui->msg2, ui->msg3, ui->msg4, + ui->msg5, ui->msg6, ui->msg7, ui->msg8}; + for (int i = 0; i < 8; ++i) { + m_settings->setValue(Jtty::messageStyleSettingsKey(style, i + 1), msgFields[i]->text()); + } + } m_settings->setValue("FoxTextMsg", m_freeTextMsg0); m_settings->setValue("WorkDupes", ui->cbWorkDupes->isChecked()); m_settings->setValue("JTTY_LowerCase",ui->cbLowerCase->isChecked()); @@ -315,10 +320,21 @@ void MainWindow::readSettings() if(!m_config.superFox()) ui->sbNslots->setValue(m_Nslots); ui->sbSerialNumber->setValue (m_settings->value ("SerialNumber", 1).toInt ()); ui->sbSerialNumber_2->setValue (m_settings->value ("SerialNumberJTTY", 1).toInt ()); - auto const jttyTemplate = [this] (int functionKey) { - QString const key = QStringLiteral("JTTY_msg%1").arg(functionKey); + int const jttyStyleIndex = m_settings->value("JTTY_MessageStyle", 0).toInt(); + { + // Restoring the index would otherwise fire on_comboBoxJttyStyle_currentIndexChanged, + // which saves/reloads msg1-8 itself -- redundant and premature here, and it would + // nest another "MainWindow" settings group inside this function's own. + QSignalBlocker const blocker {ui->comboBoxJttyStyle}; + ui->comboBoxJttyStyle->setCurrentIndex(jttyStyleIndex); + } + m_jttyMessageStyle = jttyStyleIndex; + auto const jttyStyle = static_cast<Jtty::MessageStyle>(jttyStyleIndex); + auto const jttyTemplate = [this, jttyStyle] (int functionKey) { + QString const key = Jtty::messageStyleSettingsKey(jttyStyle, functionKey); QString const saved = m_settings->value( - key, Jtty::nativeMacroTemplate(functionKey)).toString(); + key, Jtty::messageStyleDefaultTemplate(jttyStyle, functionKey)).toString(); + if (jttyStyle != Jtty::MessageStyle::Contest) return saved; QString const migrated = Jtty::migratedNativeMacroTemplate(functionKey, saved); if (m_settings->contains(key) && migrated != saved) { m_settings->setValue(key, migrated); diff --git a/widgets/mainwindow_show_messages.cpp b/widgets/mainwindow_show_messages.cpp index 6e7236d7..d4023f1b 100644 --- a/widgets/mainwindow_show_messages.cpp +++ b/widgets/mainwindow_show_messages.cpp @@ -15,6 +15,11 @@ void MainWindow::showSoundInError(const QString& errorMsg) void MainWindow::showSoundOutError(const QString& errorMsg) { noteTxStopReason (TxEvidence::TxStopReason::Error); + if (m_jttyTxLifecycle.active () || !m_jttyTransmitQueue.empty ()) { + stopTx (); + m_jttyQueueNotice = errorMsg; + updateJttySendButton (); + } if (m_splash && m_splash->isVisible ()) m_splash->hide (); MessageBox::critical_message (this, tr ("Error in Sound Output"), errorMsg); } diff --git a/widgets/mainwindow_slots.cpp b/widgets/mainwindow_slots.cpp index 2ff97b42..18460105 100644 --- a/widgets/mainwindow_slots.cpp +++ b/widgets/mainwindow_slots.cpp @@ -175,9 +175,6 @@ void MainWindow::on_stopButton_clicked() //stopButton { ui->pbBandHopping->setChecked(false); // disable band hopping monitor (false); - if(m_mode=="JTTY" and m_saveAll and !m_diskData) { - jtty_save_wav(); - } m_loopall=false; finishReferenceSpectrumMeasurement(true); if (ui->DX_Call_Button->isChecked()) ui->DX_Call_Button->click (); @@ -238,6 +235,7 @@ void MainWindow::on_DecodeButton_clicked (bool /* checked */) //Decode request void MainWindow::on_ClrAvgButton_clicked() { m_nclearave=1; + if (m_mode == "Q65") m_q65ClearAveragesPending = true; if(m_mode=="Echo") { echocom_.nsum=0; m_echoGraph->clearAvg(); @@ -660,15 +658,20 @@ void MainWindow::reset_transmit_controls_after_stop () void MainWindow::on_stopTxButton_clicked() // Stop Tx { - noteTxStopReason (TxEvidence::TxStopReason::UserHalt); + requestTxStop (TxEvidence::TxStopReason::UserHalt); +} + +void MainWindow::requestTxStop (TxEvidence::TxStopReason reason) +{ + noteTxStopReason (reason); + bool const pending_start = m_tx_when_ready || ptt1Timer.isActive (); + m_tx_when_ready = false; + ptt1Timer.stop (); + m_restart = false; if (m_beaconTxController.txLifecycle () == BeaconTx::TxLifecycle::Decided || m_beaconTxController.txLifecycle () == BeaconTx::TxLifecycle::StartRequested) { - m_tx_when_ready = false; - ptt1Timer.stop (); processBeaconActions (m_beaconTxController.transmitWindowEnded ()); - if (g_iptt == 1 || m_transmitting) stopTx (); - else g_iptt = 0; } if (m_beaconTxController.active ()) { @@ -677,6 +680,15 @@ void MainWindow::on_stopTxButton_clicked() // Stop Tx if (m_tune) stop_tuning (); if (m_auto) auto_tx_mode (false); reset_transmit_controls_after_stop (); + // Reported PTT may remain high while the delayed PTT-off is already pending. + if (pending_start || g_iptt == 1 || m_transmitting + || m_jttyTxLifecycle.active () || !m_jttyTransmitQueue.empty ()) + { + stopTx (); + } +#ifdef WIN32 + finalizeMmttyExternalAbort (); +#endif } void MainWindow::on_pbR2T_clicked() @@ -1044,12 +1056,7 @@ void MainWindow::on_pb24G_clicked() void MainWindow::on_pbSendMessage_clicked() { - submitJttyDraft (ui->Tx_Message->text ().toUpper ()); -} - -void MainWindow::on_Tx_Message_returnPressed() -{ - on_pbSendMessage_clicked(); + commitJttyLiveEntry (); } void MainWindow::on_pbF1_clicked() diff --git a/widgets/plotter.cpp b/widgets/plotter.cpp index aaef1384..660b5db6 100644 --- a/widgets/plotter.cpp +++ b/widgets/plotter.cpp @@ -120,6 +120,7 @@ void CPlotter::resizeEvent(QResizeEvent* ) //resizeEvent() m_2DPixmap.fill(Qt::black); m_WaterfallPixmap = QPixmap(kWaterfallStorageWidth, m_h1); m_WaterfallPixmap.fill(Qt::black); + m_jttyRows.resize (m_h1); m_OverlayPixmap = QPixmap(m_Size.width(), m_h2); m_OverlayPixmap.fill(Qt::black); m_ScalePixmap = QPixmap(m_scale.width(),30); @@ -154,7 +155,7 @@ void CPlotter::paintEvent(QPaintEvent *) // paint void CPlotter::draw(float swide[], bool bScroll, bool bRed) { - if (!m_TRperiod) return; // not ready to plot yet + if (m_mode != "JTTY" && !m_TRperiod) return; int j,j0; float y,y2,ymin; bool const drawWaterfall = bScroll or bRed or m_bReplot; @@ -172,6 +173,12 @@ void CPlotter::draw(float swide[], bool bScroll, bool bRed) if(waterfallWidth<1) return; if(bScroll and !m_bReplot) { m_WaterfallPixmap.scroll(0,1,0,0,waterfallWidth,m_h1); + m_jttyRows.prepend ({m_pendingJttyRow, + m_pendingJttyRow.reception && m_jttyRowsSinceTimestamp >= fontMetrics ().height ()}); + if (m_jttyRows.front ().timestamp) m_jttyRowsSinceTimestamp = 0; + ++m_jttyRowsSinceTimestamp; + m_jttyRows.resize (m_h1); + m_pendingJttyRow = {}; } QPainter painter1(&m_WaterfallPixmap); if(m_bFirst or bRed or !m_bQ65_Sync or m_mode!=m_mode0 @@ -227,7 +234,8 @@ void CPlotter::draw(float swide[], bool bScroll, bool bRed) if(savgBins > availableBins) savgBins = availableBins; if(savgBins > 0) { m_savgDisplay.resize(savgBins); - std::copy(&dec_data.savg[j0], &dec_data.savg[j0] + savgBins, m_savgDisplay.data()); + auto const * average = m_mode == "JTTY" ? m_jttyCumulative.data () : dec_data.savg; + std::copy(average + j0, average + j0 + savgBins, m_savgDisplay.data()); flat4_(m_savgDisplay.data(),&savgBins,&m_Flatten); } } @@ -275,7 +283,7 @@ void CPlotter::draw(float swide[], bool bScroll, bool bRed) int j=j0+m_scale.binsPerPixel()*i; int n=0; for(int k=0; k<m_scale.binsPerPixel() and j<NSMAX; k++) { - sum+=spectra_.syellow[j++]; + sum += m_mode == "JTTY" ? m_jttyLinearAverage[j++] : spectra_.syellow[j++]; n++; } if(n>0) y2=2.0*gain2d*sum/n + m_plot2dZero; @@ -307,7 +315,8 @@ void CPlotter::draw(float swide[], bool bScroll, bool bRed) if(swidePlot[0]>1.0e29) m_line=0; if(m_mode=="FT4" and m_line==34) m_line=0; - if(m_line == painter1.fontMetrics ().height () && m_timestamp!=0) { + if (m_mode == "JTTY") drawJttyLabels (painter1, true); + if(m_mode != "JTTY" && m_line == painter1.fontMetrics ().height () && m_timestamp!=0) { painter1.setPen(Qt::white); QString t; if(m_nUTC<0) { @@ -433,10 +442,37 @@ void CPlotter::drawSavedWaterfall() if(m_mode=="Q65" and m_bQ65_Sync) { draw(m_replotRow.data(),false,true); } + if (m_mode == "JTTY") { + QPainter painter (&m_WaterfallPixmap); + drawJttyLabels (painter, false); + } update(); //trigger a new paintEvent m_bReplot=false; } +void CPlotter::setJttySpectrum ( + std::array<float, JttySpectrumFrame::BinCount> const& cumulative, + std::array<float, JttySpectrumFrame::BinCount> const& linearAverage) +{ + m_jttyCumulative = cumulative; + m_jttyLinearAverage = linearAverage; +} + +void CPlotter::drawJttyLabels (QPainter& painter, bool newestOnly) +{ + if (!m_timestamp) return; + painter.setPen (Qt::white); + int const count = newestOnly ? std::min (1, m_jttyRows.size ()) : m_jttyRows.size (); + for (int row = 0; row < count; ++row) { + auto const& saved = m_jttyRows[row]; + if (!saved.audio.reception || (!saved.timestamp && !saved.audio.gap)) continue; + QString label = QDateTime::fromMSecsSinceEpoch (saved.audio.utcEndMs, Qt::UTC).toString ("hh:mm:ss"); + if (saved.audio.gap) label += " " + tr ("Input interrupted"); + QRect const rect {5, row, m_scale.width () - 10, painter.fontMetrics ().height ()}; + painter.drawText (rect, (m_timestamp == 2 ? Qt::AlignRight : Qt::AlignLeft) | Qt::AlignTop, label); + } +} + void CPlotter::DrawOverlay() //DrawOverlay() { if(m_OverlayPixmap.isNull()) return; @@ -979,14 +1015,10 @@ void CPlotter::mouseDoubleClickEvent (QMouseEvent * event) bool leftbutton = (event->button() & Qt::LeftButton); bool ctrl = (event->modifiers() & Qt::ControlModifier); if (leftbutton and m_mode=="JTTY" and !ctrl) { - // Waterfall region is screen y in [30,30+m_h1); row 0 (newest) is at - // the top, growing downward -- see the m_j=0 draw + scroll(0,1,...) in - // draw(). Ctrl+double-click still falls through below for the old, - // unbounded full-buffer rescan. int const row = event->y() - 30; - if (row >= 0 and row < m_h1) { - float const secondsAgo = row * m_waterfallAvg * 3456.0f/12000.0f; - emit jttyDecodeAgainAt(secondsAgo); + if (row >= 0 && row < m_jttyRows.size ()) { + auto const& audio = m_jttyRows[row].audio; + if (audio.hasAudio ()) emit jttyDecodeAgainAtSample (audio.reception, audio.endSample); } } else if (leftbutton) { int n=2; diff --git a/widgets/plotter.h b/widgets/plotter.h index af2ec36c..51d5ccb1 100644 --- a/widgets/plotter.h +++ b/widgets/plotter.h @@ -16,12 +16,14 @@ #include <QToolTip> #include "WaterfallScale.hpp" +#include "JttySpectrum.hpp" #define VERT_DIVS 7 //specify grid screen divisions extern bool g_single_decode; class QAction; +class QPainter; class CPlotter : public QFrame { @@ -98,11 +100,14 @@ public: void restartTotalPower(); bool scaleOK () const {return m_bScaleOK;} void setDarkStyle(bool b); + void setJttyRow (JttyWaterfallRow const& row) { m_pendingJttyRow = row; } + void setJttySpectrum (std::array<float, JttySpectrumFrame::BinCount> const& cumulative, + std::array<float, JttySpectrumFrame::BinCount> const& linearAverage); signals: void freezeDecode1(int n); void setFreq1(int rxFreq, int txFreq); - void jttyDecodeAgainAt(float secondsAgo); + void jttyDecodeAgainAtSample (quint64 reception, qint64 endSample); protected: //re-implemented widget event handlers @@ -117,6 +122,7 @@ private: int XfromFreq(float f); float FreqfromX(int x); void drawSavedWaterfall(); + void drawJttyLabels (QPainter& painter, bool newestOnly); QAction * m_set_freq_action; @@ -167,6 +173,15 @@ private: QVector<float> m_swideDisplay; QVector<float> m_savgDisplay; QVector<float> m_replotRow; + struct JttyRowHistory { + JttyWaterfallRow audio; + bool timestamp = false; + }; + QVector<JttyRowHistory> m_jttyRows; + JttyWaterfallRow m_pendingJttyRow; + std::array<float, JttySpectrumFrame::BinCount> m_jttyCumulative {}; + std::array<float, JttySpectrumFrame::BinCount> m_jttyLinearAverage {}; + int m_jttyRowsSinceTimestamp = 1000; QString m_mode; QString m_mode0; QString m_rxBand; diff --git a/widgets/widegraph.cpp b/widgets/widegraph.cpp index f33b570c..3a50eb05 100644 --- a/widgets/widegraph.cpp +++ b/widgets/widegraph.cpp @@ -44,8 +44,8 @@ WideGraph::WideGraph(QSettings * settings, QWidget *parent) : connect(ui->widePlot, SIGNAL(setFreq1(int,int)),this, SLOT(setFreq2(int,int))); - connect(ui->widePlot, SIGNAL(jttyDecodeAgainAt(float)),this, - SLOT(wideJttyDecodeAgainAt(float))); + connect (ui->widePlot, &CPlotter::jttyDecodeAgainAtSample, + this, &WideGraph::jttyDecodeAgainAtSample); { //Restore user's settings @@ -230,8 +230,60 @@ void WideGraph::on_bppSpinBox_valueChanged(int n) //b ui->widePlot->setBinsPerPixel(n); } +void WideGraph::jttyDataSink (JttySpectrumFrame const& frame) +{ + if (m_jttyLastRow.reception && + (m_jttyLastRow.reception != frame.row.reception || + m_jttyLastRow.endSample != frame.row.beginSample)) { + jttyReceptionEnded (); + } + ui->widePlot->setJttySpectrum (frame.cumulative, frame.linearAverage); + if (ui->widePlot->TotalPower ()) ui->widePlot->drawTotalPower (frame.powerDb); + if (!m_jttySpectrumCount) m_jttyAverageRow = frame.row; + m_jttyAverageRow.endSample = frame.row.endSample; + m_jttyAverageRow.utcEndMs = frame.row.utcEndMs; + m_jttyLastRow = frame.row; + for (int i = 0; i < JttySpectrumFrame::BinCount; ++i) m_jttySpectrumSum[i] += frame.bins[i]; + if (++m_jttySpectrumCount >= std::max (1, m_waterfallAvg)) drawJttyAverage (); +} + +void WideGraph::drawJttyAverage () +{ + if (!m_jttySpectrumCount) return; + int const nbpp = ui->widePlot->binsPerPixel (); + int bin = int (ui->widePlot->startFreq () / JttySpectrumFrame::BinWidth + 0.5); + m_jz = std::min (MAX_SCREENSIZE, int (5000.0f / (nbpp * JttySpectrumFrame::BinWidth))); + std::fill (std::begin (m_swide), std::end (m_swide), 0); + for (int pixel = 0; pixel < m_jz; ++pixel) { + double sum = 0; + for (int k = 0; k < nbpp; ++k, ++bin) { + if (bin >= 0 && bin < JttySpectrumFrame::BinCount - 1) sum += m_jttySpectrumSum[bin]; + } + m_swide[pixel] = nbpp * sum / m_jttySpectrumCount; + } + ui->widePlot->setJttyRow (m_jttyAverageRow); + ui->widePlot->draw (m_swide, true, false); + m_jttySpectrumCount = 0; + m_jttySpectrumSum.fill (0); +} + +void WideGraph::jttyReceptionEnded () +{ + drawJttyAverage (); + if (m_jttyLastRow.reception) { + auto gap = m_jttyLastRow; + gap.beginSample = gap.endSample; + gap.gap = true; + std::fill (std::begin (m_swide), std::end (m_swide), 1.0e30f); + ui->widePlot->setJttyRow (gap); + ui->widePlot->draw (m_swide, true, false); + } + m_jttyLastRow = {}; +} + void WideGraph::on_waterfallAvgSpinBox_valueChanged(int n) //Navg { + if (m_mode == "JTTY") drawJttyAverage (); m_waterfallAvg = n; ui->widePlot->setWaterfallAvg(n); } @@ -277,11 +329,6 @@ void WideGraph::wideFreezeDecode(int n) //wideFreez emit freezeDecode2(n); } -void WideGraph::wideJttyDecodeAgainAt(float secondsAgo) //wideJttyDecodeAgainAt -{ - emit jttyDecodeAgainAt2(secondsAgo); -} - int WideGraph::Fmin() //Fmin { return "60m" == m_rxBand ? 0 : m_fMinPerBand.value (m_rxBand, 2500).toUInt (); @@ -323,6 +370,7 @@ void WideGraph::setTxFreq(int n) //setTxFreq void WideGraph::setMode(QString mode) //setMode { + if (m_mode == "JTTY" && mode != m_mode) jttyReceptionEnded (); m_mode=mode; ui->fSplitSpinBox->setVisible(m_mode.startsWith("FST4")); ui->fSplitSpinBox->setEnabled(m_mode.startsWith("FST4")); diff --git a/widgets/widegraph.h b/widgets/widegraph.h index d4d2d839..cfee0cd8 100644 --- a/widgets/widegraph.h +++ b/widgets/widegraph.h @@ -8,6 +8,7 @@ #include <QHash> #include <QVariant> #include "WFPalette.hpp" +#include "JttySpectrum.hpp" #define MAX_SCREENSIZE 2048 @@ -27,6 +28,8 @@ public: ~WideGraph (); void dataSink2(float s[], float df3, int ihsym, int ndiskdata, float pdB); + void jttyDataSink (JttySpectrumFrame const& frame); + void jttyReceptionEnded (); void setRxFreq(int n); int rxFreq(); int nStartFreq(); @@ -66,13 +69,12 @@ signals: void f11f12(int n); void setXIT2(int n); void setFreq3(int rxFreq, int txFreq); - void jttyDecodeAgainAt2(float secondsAgo); + void jttyDecodeAgainAtSample (quint64 reception, qint64 endSample); public slots: void wideFreezeDecode(int n); void setFreq2(int rxFreq, int txFreq); void setDialFreq(double d); - void wideJttyDecodeAgainAt(float secondsAgo); protected: void keyPressEvent (QKeyEvent *e) override; @@ -102,6 +104,7 @@ private slots: private: void readPalette (); void replot(); + void drawJttyAverage (); QScopedPointer<Ui::WideGraph> ui; @@ -134,6 +137,10 @@ private: QString m_waterfallPalette; float m_swide[MAX_SCREENSIZE]; QString m_user_defined; + std::array<double, JttySpectrumFrame::BinCount> m_jttySpectrumSum {}; + JttyWaterfallRow m_jttyAverageRow; + JttyWaterfallRow m_jttyLastRow; + int m_jttySpectrumCount = 0; }; #endif // WIDEGRAPH_H |
