diff options
| author | hibby <d@vehibberd.com> | 2026-10-06 21:24:40 +0100 |
|---|---|---|
| committer | hibby <d@vehibberd.com> | 2026-10-06 21:24:40 +0100 |
| commit | c25cbdf6fb6d946175f4335fab77bfea601b56db (patch) | |
| tree | 6f7a94b7b81f999e434f61b73d47e337dfd26bf2 /map65 | |
| parent | 71f5689252c9f13e70e1c24856904475b2307809 (diff) | |
| parent | 0685fcada9f95fe90f70b387cd7d757da8209624 (diff) | |
Merge tag 'debian/3.2.0_rc1+dfsg-2' into debian/trixie-backportsdebian/trixie-backports
tagging wsjtx 3.2.0~rc1+dfsg-2
Diffstat (limited to 'map65')
185 files changed, 14963 insertions, 8608 deletions
diff --git a/map65/CMakeLists.txt b/map65/CMakeLists.txt index 7de82d12..00de39fd 100644 --- a/map65/CMakeLists.txt +++ b/map65/CMakeLists.txt @@ -6,18 +6,26 @@ set (map65_CXXSRCS astro.cpp bandmap.cpp cqdatasender.cpp + commons.cpp devsetup.cpp displaytext.cpp + fortran_mutex.cpp getdev.cpp - getfile.cpp +# getfile.cpp liveCQSender.cpp +# map65_paths.cpp main.cpp mainwindow.cpp + map65_decode_display_filter.cpp messages.cpp meterwidget.cpp plotter.cpp - PSKReporter.cpp + pskreporter_decode.cpp + pskreporter_settings.cpp Radio.cpp + runtime_paths.cpp + ../Network/PSKReporter.cpp + ../Network/PSKReporterIPFIX.cpp set570.cpp signalmeter.cpp soundin.cpp @@ -26,10 +34,6 @@ set (map65_CXXSRCS widegraph.cpp ) -if (WIN32) - set (map65_CXXSRCS ${map65_CXXSRCS} killbyname.cpp) -endif (WIN32) - set (map65_UISRCS about.ui astro.ui @@ -54,28 +58,67 @@ add_subdirectory (libm65) # UI generation qt5_wrap_ui (map65_GENUISRCS ${map65_UISRCS}) -add_executable (map65 ${map65_CXXSRCS} ${map65_CSRCS} ${map65_GENUISRCS} map65.rc) -target_include_directories (map65 PRIVATE ${CMAKE_SOURCE_DIR} ${FFTW3_INCLUDE_DIRS}) -target_link_libraries (map65 wsjt_qt m65impl ${FFTW3_LIBRARIES} Qt5::Widgets Qt5::Network Portaudio::Portaudio Usb::Usb) +# windres doesn't track a .rc file's ICON directive as a dependency, so an icon-only edit needs this to trigger a rebuild. +set_property (SOURCE map65.rc APPEND PROPERTY OBJECT_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/wsjt.ico) + +# Resource generation (About dialog logo + GPL logo) +qt5_add_resources (map65_RESOURCES_RCC about.qrc) + +# Executable: only the .rc file is Windows-only +if (WIN32) + add_executable(map65 + ${map65_CXXSRCS} + ${map65_CSRCS} + ${map65_GENUISRCS} + ${map65_RESOURCES_RCC} + map65.rc + ) +else() + add_executable(map65 + ${map65_CXXSRCS} + ${map65_CSRCS} + ${map65_GENUISRCS} + ${map65_RESOURCES_RCC} + ) +endif() + +# Include directories (same on all platforms) +target_include_directories(map65 PRIVATE + ${CMAKE_SOURCE_DIR} + ${CMAKE_SOURCE_DIR}/map65/libm65 + ${FFTW3_INCLUDE_DIRS} +) + +# Link libraries (same on all platforms except libusb) +target_link_libraries(map65 PRIVATE + wsjt_qt + m65impl + ${FFTW3_LIBRARIES} + Qt5::Widgets + Qt5::Network + Qt5::SerialPort + Portaudio::Portaudio + Usb::Usb +) + +if (APPLE) + target_link_libraries(map65 PRIVATE m65_qt) +endif () -if (WSJT_CREATE_WINMAIN) - set_target_properties (map65 PROPERTIES WIN32_EXECUTABLE ON) -endif (WSJT_CREATE_WINMAIN) +# Linux needs libusb +# if (UNIX AND NOT APPLE) +# find_package(PkgConfig REQUIRED) +# pkg_check_modules(LIBUSB REQUIRED libusb-1.0) +# target_include_directories(map65 PRIVATE ${LIBUSB_INCLUDE_DIRS}) +# target_link_libraries(map65 PRIVATE ${LIBUSB_LIBRARIES}) +# endif() +# MAP65 must ALWAYS be a console subsystem executable on Windows if (WIN32) - install ( - CODE "get_filename_component (_path \"\$ENV{DESTDIR}\${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_BINDIR}/wsjtx_dir.txt\" REALPATH) - if (WIN32) - set (_separator \"\\\\\") - else () - set (_separator \"/\") - endif () - file (WRITE \"\${_path}\" \".\${_separator}\\n\")" - ) + set_target_properties(map65 PROPERTIES WIN32_EXECUTABLE OFF) +endif() - install ( - TARGETS map65 - RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT runtime - BUNDLE DESTINATION . COMPONENT runtime - ) -endif ()
\ No newline at end of file +# WSJT_CREATE_WINMAIN now ONLY controls console visibility +if (WIN32 AND WSJT_CREATE_WINMAIN) + target_compile_definitions(map65 PRIVATE MAP_GUI_SUBSYSTEM) + endif() diff --git a/map65/PSKReporter.cpp b/map65/PSKReporter.cpp deleted file mode 100644 index 139e74a6..00000000 --- a/map65/PSKReporter.cpp +++ /dev/null @@ -1,537 +0,0 @@ -#include "PSKReporter.hpp" -#include <QSettings> -#include "SettingsGroup.hpp" -#include "mainwindow.h" -#include "qt_helpers.hpp" -#include "../revision_utils.hpp" - -// Interface for posting spots to PSK Reporter web site -// Implemented by Edson Pereira PY2SDR -// Updated by Bill Somerville, G4WJS -// -// Reports will be sent in batch mode every 5 minutes. - -#include <fstream> -#include <iostream> -#include <cmath> -#include <QObject> -#include <QString> -#include <QDateTime> -#include <QSharedPointer> -#include <QTcpSocket> -#include <QHostInfo> -#include <QQueue> -#include <QByteArray> -#include <QDataStream> -#include <QTimer> -#include <QDir> -#include <QSettings> -#include <QDebug> -#include <QMetaType> -#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) -#include <QRandomGenerator> -#endif - -#include "../Logger.hpp" -#include "devsetup.h" - -//#define DEBUGECLIPSE 0 -# define DEBUGPSK 1; - -namespace -{ - QLatin1String HOST {"report.pskreporter.info"}; - //QLatin1String HOST {"127.0.0.1"}; - quint16 SERVICE_PORT {4739}; //this is normal user port - //quint16 SERVICE_PORT {14739}; //this is test port - int MIN_SEND_INTERVAL {120}; // in seconds - int FLUSH_INTERVAL {MIN_SEND_INTERVAL + 5}; // in send intervals - bool ALIGNMENT_PADDING {true}; - int MIN_PAYLOAD_LENGTH {508}; - int MAX_PAYLOAD_LENGTH {10000}; - int CACHE_TIMEOUT {300}; // default to 5 minutes for repeating spots - QMap<QString, time_t> spot_cache; -} - -static int added; -static int removed; - -PSKReporter::PSKReporter(QString const& myCall, QString const& myGrid, QString const& program_info) - : logger_ {boost::log::keywords::channel = "PSKRPRT"} - , myCall {myCall} - , myGrid {myGrid} - , sequence_number_ {0u} - , send_descriptors_ {1} - , send_receiver_data_ {1} - , flush_counter_ {0u} - , prog_id_ {program_info} - { - -#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) - observation_id_ = qrand(); -#else - observation_id_ = QRandomGenerator::global ()->generate (); -#endif - - qDebug() << "PSKReporter Current thread:" << QThread::currentThread(); - } - - void PSKReporter::handle_socket_error (QAbstractSocket::SocketError e) - { - LOG_LOG_LOCATION (logger_, warning, "PSKReporter socket error: " << socket->errorString ()); - switch (e) - { - case QAbstractSocket::RemoteHostClosedError: - socket->disconnectFromHost (); - break; - - case QAbstractSocket::TemporaryError: - break; - - default: - spots_.clear (); - Q_EMIT this->errorOccurred (socket->errorString ()); - break; - } - } - - void PSKReporter::stop () - { - if (socket) - { - LOG_LOG_LOCATION (logger_, trace, "PSKReporter disconnecting"); - socket->disconnectFromHost (); - } - this->descriptor_timer_->stop (); - this->report_timer_->stop (); - } - - - bool PSKReporter::flushing () - { - bool flush = FLUSH_INTERVAL && !(++flush_counter_ % FLUSH_INTERVAL); - LOG_LOG_LOCATION (logger_, trace, "PSKReporter flush: " << flush); - return flush; - } - - void PSKReporter::writeUtfString (QDataStream& out, QString const& s) - { - auto const& utf = s.toUtf8 ().left (254); - out << quint8 (utf.size ()); - out.writeRawData (utf, utf.size ()); - } - - int PSKReporter::num_pad_bytes (int len) - { - return ALIGNMENT_PADDING ? (4 - len % 4) % 4 : 0; - } - - void PSKReporter::set_length (QDataStream& out, QByteArray& b) - { - // pad with nulls modulo 4 - auto pad_len = num_pad_bytes (b.size ()); - out.writeRawData (QByteArray {pad_len, '\0'}.constData (), pad_len); - auto pos = out.device ()->pos (); - out.device ()->seek (sizeof (quint16)); - // insert length - out << static_cast<quint16> (b.size ()); - out.device ()->seek (pos); - } - - void PSKReporter::restartReportTimer() { - report_timer_->stop(); - report_timer_->start((MIN_SEND_INTERVAL+1) * 1000); - qDebug() << "PSKReporter Current thread for restartReportTimer:" << QThread::currentThread(); - } - - void PSKReporter::restartDescriptorTimer() { - descriptor_timer_->stop(); - descriptor_timer_->start(60 * 60 * 1000); - qDebug() << "PSKReporter Current thread for restartDescriptorTimer:" << QThread::currentThread(); - } - -void PSKReporter::init() { - report_timer_ = new QTimer(this); - descriptor_timer_ = new QTimer(this); - connect(report_timer_, &QTimer::timeout, this, &restartReportTimer); - connect(descriptor_timer_, &QTimer::timeout, this, &restartDescriptorTimer); - report_timer_->start((MIN_SEND_INTERVAL + 1) * 1000); - descriptor_timer_->start(60 * 60 * 1000); // 1 hour - qDebug() << "PSKReporter::init running on thread: " << QThread::currentThread(); - - socket.reset(new QTcpSocket(this)); - - // Connect signals before connecting - connect(socket.data(), &QAbstractSocket::connected, this, &PSKReporter::onConnected); - connect(socket.data(), &QAbstractSocket::readyRead, this, &PSKReporter::onReadyRead); - connect(this, &PSKReporter::dataReady, this, &PSKReporter::sendData); -#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) - connect(socket.data(), &QAbstractSocket::errorOccurred, this, &PSKReporter::handle_socket_error); -#else - connect(socket.data(), static_cast<void(QAbstractSocket::*)(QAbstractSocket::SocketError)>(&QAbstractSocket::error), - this, &PSKReporter::handle_socket_error); -#endif - // This timer sets the interval to check for spots to send. - connect (report_timer_, &QTimer::timeout, [this] () {this->send_report (true);}); - - connect (descriptor_timer_, &QTimer::timeout, [this] () {this->send_descriptors_ = 1; - this->send_receiver_data_ = 1; - }); - - // Start connection (non-blocking - setLocalStation(myCall, myGrid,"N/A","N/A (MAP65)"); - socket->connectToHost(HOST, SERVICE_PORT); - -} - - void PSKReporter::onConnected() { - - qDebug() << "PSKReporter onConnected Connected securely!"; - qDebug() << "PSKReporter::onConnected payload: " << payload_;// << request; - socket->write(payload_); - } - - void PSKReporter::onReadyRead() { - QByteArray data = socket->readAll(); - // Parse headers, then handle chunks - while (!data.isEmpty()) { - int pos = data.indexOf("\r\n"); - bool ok; - int size = data.left(pos).trimmed().toInt(&ok, 16); - if (!ok || size == 0) break; - data = data.mid(pos + 2); - qDebug() << "Chunk:" << data.left(size); - data = data.mid(size + 2); // skip \r\n - } - qDebug() << "PSKReporter Response:" << data; -} - - void PSKReporter::sendData(const QByteArray &payload1) { - if (socket->state() == QAbstractSocket::ConnectedState) { - socket->write(payload1); - qDebug() << "PSKReporter::sendData payload: " << payload1;// << request; - } - else { - socket->connectToHost(HOST, SERVICE_PORT); - // Data will be sent in onConnected() - } - } - -void PSKReporter::build_preamble (QDataStream& message) -{ - // Message Header - message - << quint16 (10u) // Version Number - << quint16 (0u) // Length (place-holder filled in later) - << quint32 (0u) // Export Time (place-holder filled in later) - << ++sequence_number_ // Sequence Number - << observation_id_; // Observation Domain ID - LOG_LOG_LOCATION (logger_, trace, "PSKReporter #: " << sequence_number_); - - if (send_descriptors_) - { - --send_descriptors_; - { - // Sender Information descriptor - QByteArray descriptor; - QDataStream out {&descriptor, QIODevice::WriteOnly}; - out - << quint16 (2u) // Template Set ID - << quint16 (0u) // Length (place-holder) - << quint16 (0x50e3) // Link ID - << quint16 (7u) // Field Count - << quint16 (0x8000 + 1u) // Option 1 Information Element ID (senderCallsign) - << quint16 (0xffff) // Option 1 Field Length (variable) - << quint32 (30351u) // Option 1 Enterprise Number - << quint16 (0x8000 + 5u) // Option 2 Information Element ID (frequency) - << quint16 (5u) // Option 2 Field Length - << quint32 (30351u) // Option 2 Enterprise Number - << quint16 (0x8000 + 6u) // Option 3 Information Element ID (sNR) - << quint16 (1u) // Option 3 Field Length - << quint32 (30351u) // Option 3 Enterprise Number - << quint16 (0x8000 + 10u) // Option 4 Information Element ID (mode) - << quint16 (0xffff) // Option 4 Field Length (variable) - << quint32 (30351u) // Option 4 Enterprise Number - << quint16 (0x8000 + 3u) // Option 5 Information Element ID (senderLocator) - << quint16 (0xffff) // Option 5 Field Length (variable) - << quint32 (30351u) // Option 5 Enterprise Number - << quint16 (0x8000 + 11u) // Option 6 Information Element ID (informationSource) - << quint16 (1u) // Option 6 Field Length - << quint32 (30351u) // Option 6 Enterprise Number - << quint16 (150u) // Option 7 Information Element ID (dateTimeSeconds) - << quint16 (4u); // Option 7 Field Length - // insert Length and move to payload - set_length (out, descriptor); - message.writeRawData (descriptor.constData (), descriptor.size ()); - } - { - // Receiver Information descriptor - QByteArray descriptor; - QDataStream out {&descriptor, QIODevice::WriteOnly}; - out - << quint16 (3u) // Options Template Set ID - << quint16 (0u) // Length (place-holder) - << quint16 (0x50e2) // Link ID - << quint16 (5u) // Field Count - << quint16 (0u) // Scope Field Count - << quint16 (0x8000 + 2u) // Option 1 Information Element ID (receiverCallsign) - << quint16 (0xffff) // Option 1 Field Length (variable) - << quint32 (30351u) // Option 1 Enterprise Number - << quint16 (0x8000 + 4u) // Option 2 Information Element ID (receiverLocator) - << quint16 (0xffff) // Option 2 Field Length (variable) - << quint32 (30351u) // Option 2 Enterprise Number - << quint16 (0x8000 + 8u) // Option 3 Information Element ID (decodingSoftware) - << quint16 (0xffff) // Option 3 Field Length (variable) - << quint32 (30351u) // Option 3 Enterprise Number - << quint16 (0x8000 + 9u) // Option 4 Information Element ID (antennaInformation) - << quint16 (0xffff) // Option 4 Field Length (variable) - << quint32 (30351u) // Option 5 Enterprise Number - << quint16 (0x8000 + 13u)// Option 5 Information Element ID (rigInformation) - << quint16 (0xffff) // Option 5 Field Length (variable) - << quint32 (30351u); // Option 4 Enterprise Number - // insert Length - set_length (out, descriptor); - message.writeRawData (descriptor.constData (), descriptor.size ()); - LOG_LOG_LOCATION (logger_, debug, "PSKReporter sent descriptors"); - } - } - - // if (send_receiver_data_) - { - // --send_receiver_data_; - - // Receiver information - QByteArray data; - QDataStream out {&data, QIODevice::WriteOnly}; - - // Set Header - out - << quint16 (0x50e2) // Template ID - << quint16 (0u); // Length (place-holder) - - // Set data - writeUtfString (out, rx_call_); - writeUtfString (out, rx_grid_); - writeUtfString (out, prog_id_); - writeUtfString (out, rx_ant_); - writeUtfString (out, rigInformation_); - - // insert Length and move to payload - set_length (out, data); - message.writeRawData (data.constData (), data.size ()); - LOG_LOG_LOCATION (logger_, debug, "PSKReporter sent local information"); - } -} - -void PSKReporter::send_report (bool send_residue) -{ - LOG_LOG_LOCATION (logger_, trace, "PSKReporter sending residue: " << send_residue); -// qDebug() << "PSKReporter send_report QAbstractSocket::ConnectedState is: " << socket->state (); - - QDataStream message {&payload_, QIODevice::WriteOnly | QIODevice::Append}; - QDataStream tx_out {&tx_data_, QIODevice::WriteOnly | QIODevice::Append}; - - if (!payload_.size ()) - { - // Build header, optional descriptors, and receiver information - build_preamble (message); - } - - auto flush = flushing () || send_residue; - while (spots_.size () || flush) - { - if (!payload_.size ()) - { - // Build header, optional descriptors, and receiver information - build_preamble (message); - } - - if (!tx_data_.size () && (spots_.size () || tx_residue_.size ())) - { - // Set Header - tx_out - << quint16 (0x50e3) // Template ID - << quint16 (0u); // Length (place-holder) - } - - // insert any residue - if (tx_residue_.size ()) - { - tx_out.writeRawData (tx_residue_.constData (), tx_residue_.size ()); - LOG_LOG_LOCATION (logger_, debug, "PSKReporter sent residue"); - tx_residue_.clear (); - } - - LOG_LOG_LOCATION (logger_, debug, "PSKReporter pending spots: " << spots_.size ()); - while (spots_.size () || flush) - { - auto tx_data_size = tx_data_.size (); - if (spots_.size ()) - { - auto const& spot = spots_.dequeue (); - - // Sender information - writeUtfString (tx_out, spot.call_); - uint8_t data[5]; - long long int i64 = spot.freq_; - data[0] = ( i64 & 0xff); - data[1] = ((i64 >> 8) & 0xff); - data[2] = ((i64 >> 16) & 0xff); - data[3] = ((i64 >> 24) & 0xff); - data[4] = ((i64 >> 32) & 0xff); - tx_out // BigEndian - << static_cast<uint8_t> (data[4]) - << static_cast<uint8_t> (data[3]) - << static_cast<uint8_t> (data[2]) - << static_cast<uint8_t> (data[1]) - << static_cast<uint8_t> (data[0]) - << static_cast<qint8> (spot.snr_); - writeUtfString (tx_out, spot.mode_); - writeUtfString (tx_out, spot.grid_); - tx_out - << quint8 (1u) // REPORTER_SOURCE_AUTOMATIC - << static_cast<quint32> ( -#if QT_VERSION >= QT_VERSION_CHECK(5, 8, 0) - spot.time_.toSecsSinceEpoch () -#else - spot.time_.toMSecsSinceEpoch () / 1000 -#endif - ); - } - - auto len = payload_.size () + tx_data_.size (); - len += num_pad_bytes (tx_data_.size ()); - len += num_pad_bytes (len); - if (len > MAX_PAYLOAD_LENGTH // our upper datagram size limit - || (!spots_.size () && len > MIN_PAYLOAD_LENGTH) // spots drained and above lower datagram size limit - || (flush && !spots_.size ())) // send what we have, possibly no spots - { - if (tx_data_.size ()) - { - if (len <= MAX_PAYLOAD_LENGTH) - { - tx_data_size = tx_data_.size (); - } - QByteArray tx {tx_data_.left (tx_data_size)}; - QDataStream out {&tx, QIODevice::WriteOnly | QIODevice::Append}; - // insert Length - set_length (out, tx); - message.writeRawData (tx.constData (), tx.size ()); - } - - // insert Length and Export Time - set_length (message, payload_); - message.device ()->seek (2 * sizeof (quint16)); - message << static_cast<quint32> ( -#if QT_VERSION >= QT_VERSION_CHECK(5, 8, 0) - QDateTime::currentDateTime ().toSecsSinceEpoch () -#else - QDateTime::currentDateTime ().toMSecsSinceEpoch () / 1000 -#endif - ); - - // Send data to PSK Reporter site - //socket->write (payload_); // TODO: handle errors - emit dataReady(payload_); - LOG_LOG_LOCATION (logger_, debug, "PSKReporter sent spots"); - flush = false; // break loop - message.device ()->seek (0u); - payload_.clear (); // Fresh message - // Save unsent spots - tx_residue_ = tx_data_.right (tx_data_.size () - tx_data_size); - tx_out.device ()->seek (0u); - tx_data_.clear (); - break; - } - } - LOG_LOG_LOCATION (logger_, debug, "PSKReporter remaining spots: " << spots_.size ()); - QThread::yieldCurrentThread(); // In long loops - } - qDebug() << "PSKReporter current thread for send_report:" << QThread::currentThread(); -} - -void PSKReporter::setLocalStation (QString const& call, QString const& gridSquare, QString const& antenna, QString const& rigInformation) -{ - LOG_LOG_LOCATION (logger_, trace, "PSKReporter call: " << call << " grid: " << gridSquare << " ant: " << antenna); - qDebug() << "PSKReporter setLocalStation QAbstractSocket::ConnectedState is: " << socket->state (); - qDebug() << "PSKReporter Connected to peer IP:" << socket->peerAddress().toString(); - qDebug() << "PSKReporter Current thread for setLocalStation:" << QThread::currentThread(); - - if (call != rx_call_ || gridSquare != rx_grid_ || antenna != rx_ant_) - { - LOG_LOG_LOCATION (logger_, trace, "PSKReporter updating information"); - send_receiver_data_ = 1; - rx_call_ = call; - rx_grid_ = gridSquare; - rx_ant_ = antenna; - rigInformation_ = rigInformation; - } -} - -void PSKReporter::addRemoteStation (QString const& call, QString const& grid, Radio::Frequency freq - , QString const& mode, int snr, QDateTime qSpotTime) -{ - LOG_LOG_LOCATION (logger_, trace, "PSKReporter call: " << call << " grid: " << grid << " freq: " << freq << " mode: " << mode << " snr: " << snr); - qDebug() << "PSKReporter addRemoteStation QAbstractSocket::ConnectedState is: " << socket->state (); - qDebug() << "PSKReporter Connected to peer IP:" << socket->peerAddress().toString(); - qDebug() << "PSKReporter Current thread for addRemoteStation:" << QThread::currentThread(); - if (socket && socket->isValid ()) - { - // remove any earlier spots of this call to reduce pskreporter load -#ifdef DEBUGPSK - static std::fstream fs; - if (!fs.is_open()) fs.open("/temp/psk.log", std::fstream::in | std::fstream::out | std::fstream::app); -#endif - added++; - - QDateTime qdateNow = QDateTime::currentDateTime().toUTC(); - // we allow all spots through +/- 6 hours around an eclipse for the HamSCI group - if (!spot_cache.contains(call) || freq > 49000000) // then it's a new spot - { - spots_.enqueue ({call, grid, snr, freq, mode, qSpotTime}); - spot_cache.insert(call, time(NULL)); -#ifdef DEBUGPSK - if (fs.is_open()) fs << "PSKReporter Adding " << call << " freq=" << freq << " " << spot_cache[call] << " count=" << spots_.count() << std::endl; -#endif - } - else if (time(NULL) - spot_cache[call] > CACHE_TIMEOUT) // then the cache has expired - { - spots_.enqueue ({call, grid, snr, freq, mode, qSpotTime}); -#ifdef DEBUGPSK - if (fs.is_open()) fs << "PSKReporter Adding # " << call << spot_cache[call] << " count=" << spots_.count() << std::endl; -#endif - spot_cache[call] = time(NULL); - } - else - { - removed++; -#ifdef DEBUGPSK - if (fs.is_open()) fs << "Removing " << call << " " << time(NULL) << " reduction=" << removed/(double)added*100 << "%" << std::endl; -#endif - } - // remove cached items over 10 minutes old to save a little memory - QMapIterator<QString, time_t> i(spot_cache); - time_t tmptime = time(NULL); - while(i.hasNext()) { - i.next(); - if (tmptime - i.value() > 600) spot_cache.remove(i.key()); - QThread::yieldCurrentThread(); // In long loops - } - } -} - -void PSKReporter::sendReport (bool last) -{ - LOG_LOG_LOCATION (logger_, trace, "PSKReporter last: " << last); - //qDebug() << "in PSKReporter sendReport QAbstractSocket::ConnectedState is: " << socket->state (); - if (socket && QAbstractSocket::ConnectedState == socket->state ()) - { - send_report (true); - } - if (last) - { - stop (); - } -} - -PSKReporter::~PSKReporter() = default; diff --git a/map65/PSKReporter.hpp b/map65/PSKReporter.hpp deleted file mode 100644 index 28884e0e..00000000 --- a/map65/PSKReporter.hpp +++ /dev/null @@ -1,107 +0,0 @@ -#ifndef PSK_REPORTER_HPP_ -#define PSK_REPORTER_HPP_ -#include <boost/log/sources/severity_channel_logger.hpp> -#include <boost/log/trivial.hpp> - -#include <QObject> -#include <QTimer> -#include <QDateTime> -#include <QQueue> -#include <QTcpSocket> -#include <QScopedPointer> -#include "Radio.hpp" -#include "../qt_helpers.hpp" -#include "commons.h" - -class QString; - -class PSKReporter : public QObject -{ - Q_OBJECT - -signals: - void dataReady(const QByteArray &payload); - - -public slots: - void restartReportTimer(); - void restartDescriptorTimer(); - void init(); // Slot to initialize timers/sockets - - -public: - explicit PSKReporter (QString const& myCall, QString const& myGrid, QString const& program_info); - ~PSKReporter (); - - void setLocalStation (QString const& call, QString const& grid, QString const& antenna, QString const& rigInformation); - void build_preamble (QDataStream& message); - void send_report (bool send_residue); - void stop (); - bool flushing(); - void writeUtfString (QDataStream& out, QString const& s); - int num_pad_bytes (int len); - void set_length (QDataStream& out, QByteArray& b); - - Q_SIGNAL void errorOccurred (QString const& reason); - - struct Spot - { - bool operator == (Spot const& rhs) - { - return - call_ == rhs.call_ - && grid_ == rhs.grid_ - && mode_ == rhs.mode_ - && std::abs (Radio::FrequencyDelta (freq_ - rhs.freq_)) < 50; - } - - QString call_; - QString grid_; - int snr_; - Radio::Frequency freq_; - QString mode_; - QDateTime time_; - }; - - void addRemoteStation (QString const& call, QString const& grid, Radio::Frequency freq, QString const& mode, int snr, QDateTime spotTime); - - // - // Flush any pending spots to PSK Reporter - // - void sendReport (bool last = false); - -private slots: - void handle_socket_error(QAbstractSocket::SocketError error); - void onConnected(); - void onReadyRead(); - void sendData(const QByteArray &payload); - -private: - using logger_type = boost::log::sources::severity_channel_logger_mt<boost::log::trivial::severity_level>; - logger_type mutable logger_; - QString myCall; - QString myGrid; - quint32 sequence_number_; - int send_descriptors_; - int send_receiver_data_; - unsigned flush_counter_ ; - QString prog_id_; - unsigned observation_id_; - QTimer *report_timer_; - QTimer *descriptor_timer_; - QScopedPointer<QTcpSocket> socket; // Or: std::unique_ptr<QSslSocket - int dns_lookup_id_; - QByteArray payload_; - QString rx_call_; - QString rx_grid_; - QString rx_ant_; - QString rigInformation_; - QByteArray tx_data_; - QByteArray tx_residue_; - QQueue<Spot> spots_; - - // Copy constructor and assignment operator disabled - Q_DISABLE_COPY(PSKReporter) -}; - -#endif diff --git a/map65/QtErrorCompat.h b/map65/QtErrorCompat.h new file mode 100644 index 00000000..01a8c012 --- /dev/null +++ b/map65/QtErrorCompat.h @@ -0,0 +1,106 @@ +#ifndef QT_ERROR_COMPAT_H +#define QT_ERROR_COMPAT_H + +#include <QObject> +#include <QProcess> +#include <QAbstractSocket> + +// --------------------------------------------------------------------------- +// QtErrorCompat +// +// Provides a unified way to connect to error signals across all Qt versions +// from 5.12.12 through 6.x, without using QT_VERSION checks. +// +// It connects BOTH the legacy "error(...)" signal and the newer +// "errorOccurred(...)" signal, but guarantees that your slot is invoked +// only once per error event. +// --------------------------------------------------------------------------- + +class QtErrorCompat : public QObject +{ + Q_OBJECT + +public: + explicit QtErrorCompat(QObject *parent = nullptr) + : QObject(parent) + {} + + // ----------------------------------------------------------------------- + // Connect QProcess error signals + // ----------------------------------------------------------------------- + template<typename Receiver> + void connectErrors(QProcess *proc, + Receiver *receiver, + void (Receiver::*slot)(QProcess::ProcessError)) + { + // Newer Qt (5.15+) + QObject::connect(proc, + SIGNAL(errorOccurred(QProcess::ProcessError)), + this, + SLOT(handleProcessError(QProcess::ProcessError))); + + // Older Qt (5.12.12) + QObject::connect(proc, + QOverload<QProcess::ProcessError>::of(&QProcess::error), + this, + &QtErrorCompat::handleProcessError); + + // Forward to user slot + QObject::connect(this, + &QtErrorCompat::processError, + receiver, + slot); + } + + // ----------------------------------------------------------------------- + // Connect QAbstractSocket error signals (QTcpSocket, QUdpSocket, etc.) + // ----------------------------------------------------------------------- + template<typename Receiver> + void connectErrors(QAbstractSocket *sock, + Receiver *receiver, + void (Receiver::*slot)(QAbstractSocket::SocketError)) + { + // Newer Qt (5.15+) + QObject::connect(sock, + SIGNAL(errorOccurred(QAbstractSocket::SocketError)), + this, + SLOT(handleSocketError(QAbstractSocket::SocketError))); + + // Older Qt (5.12.12) + QObject::connect(sock, + QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::error), + this, + &QtErrorCompat::handleSocketError); + + // Forward to user slot + QObject::connect(this, + &QtErrorCompat::socketError, + receiver, + slot); + } + +signals: + void processError(QProcess::ProcessError); + void socketError(QAbstractSocket::SocketError); + +private slots: + void handleProcessError(QProcess::ProcessError e) + { + static bool guard = false; + if (guard) return; + guard = true; + emit processError(e); + guard = false; + } + + void handleSocketError(QAbstractSocket::SocketError e) + { + static bool guard = false; + if (guard) return; + guard = true; + emit socketError(e); + guard = false; + } +}; + +#endif // QT_ERROR_COMPAT_H diff --git a/map65/Radio.cpp b/map65/Radio.cpp index 5ee29040..e90f5b3f 100644 --- a/map65/Radio.cpp +++ b/map65/Radio.cpp @@ -33,7 +33,7 @@ namespace Radio Frequency frequency (QVariant const& v, int scale, bool * ok, QLocale const& locale) { double value {0.}; - if (QVariant::String == v.type ()) + if (QMetaType::QString == v.userType()) { value = locale.toDouble (v.value<QString> (), ok); } @@ -70,7 +70,7 @@ namespace Radio FrequencyDelta frequency_delta (QVariant const& v, int scale, bool * ok, QLocale const& locale) { double value {0.}; - if (QVariant::String == v.type ()) + if (QMetaType::QString == v.userType()) { value = locale.toDouble (v.value<QString> (), ok); } diff --git a/map65/about.cpp b/map65/about.cpp index 020ccd1d..6a1dde07 100644 --- a/map65/about.cpp +++ b/map65/about.cpp @@ -7,14 +7,21 @@ CAboutDlg::CAboutDlg(QWidget *parent) : ui(new Ui::CAboutDlg) { ui->setupUi(this); - ui->labelTxt->setText("<html><h2>" + QString {"MAP65 v" + ui->labelTxt->setText("<html><h2>" + QString {"MAP65â„¢ v" + QCoreApplication::applicationVersion () + " " + revision ()}.simplified () + "</h2><br />" - "MAP65 implements a wideband polarization-matching receiver <br />" - "for the JT65 protocol, with a matching transmitting facility. <br />" - "It is primarily intended for amateur radio EME communication. <br /><br />" - "Copyright 2001-2026 by Joe Taylor, K1JT, and the WSJT <br/>" - "Development Group."); + "MAP65â„¢ implements a wideband polarization-matching receiver <br />" + "for the JT65 and Q65 protocols, with a matching transmitting <br />" + "facility. It is primarily intended for amateur radio EME communication. <br /><br />" + "Copyright 2001-2026 by Joe Taylor, K1JT, and the WSJTâ„¢ <br/>" + "Development Team.<br /><br />" + "MAP65 is licensed under the terms of Version 3 <br />" + "of the GNU General Public License (GPL) <br /><br />" + "<a href=" TO_STRING__ (PROJECT_HOMEPAGE) ">" + "<img src=\":/icon_128x128.png\" /></a>" + "<a href=\"https://www.gnu.org/licenses/gpl-3.0.txt\">" + "<img src=\":/gpl-v3-logo.svg\" height=\"80\" /><br />" + "https://www.gnu.org/licenses/gpl-3.0.txt</a>"); } CAboutDlg::~CAboutDlg() diff --git a/map65/about.qrc b/map65/about.qrc new file mode 100644 index 00000000..9520adbc --- /dev/null +++ b/map65/about.qrc @@ -0,0 +1,6 @@ +<RCC> + <qresource prefix="/"> + <file alias="icon_128x128.png">about_icon.png</file> + <file alias="gpl-v3-logo.svg">../contrib/gpl-v3-logo.svg</file> + </qresource> +</RCC> diff --git a/map65/about.ui b/map65/about.ui index fb20f48d..8141882d 100644 --- a/map65/about.ui +++ b/map65/about.ui @@ -5,22 +5,8 @@ <property name="windowModality"> <enum>Qt::NonModal</enum> </property> - <property name="geometry"> - <rect> - <x>0</x> - <y>0</y> - <width>374</width> - <height>164</height> - </rect> - </property> - <property name="sizePolicy"> - <sizepolicy hsizetype="Preferred" vsizetype="Preferred"> - <horstretch>0</horstretch> - <verstretch>0</verstretch> - </sizepolicy> - </property> <property name="windowTitle"> - <string>About MAP65</string> + <string>About MAP65â„¢</string> </property> <layout class="QHBoxLayout" name="horizontalLayout"> <item> @@ -28,6 +14,12 @@ <property name="text"> <string/> </property> + <property name="alignment"> + <set>Qt::AlignCenter</set> + </property> + <property name="openExternalLinks"> + <bool>true</bool> + </property> </widget> </item> </layout> diff --git a/map65/about_icon.png b/map65/about_icon.png Binary files differnew file mode 100644 index 00000000..68198d68 --- /dev/null +++ b/map65/about_icon.png diff --git a/map65/astro.cpp b/map65/astro.cpp index a6b0460a..8e17c3b0 100644 --- a/map65/astro.cpp +++ b/map65/astro.cpp @@ -62,16 +62,33 @@ void Astro::astroUpdate(QDateTime t, QString mygrid, QString hisgrid, double sec=t.time().second() + 0.001*t.time().msec(); int isec=sec; double uth=nhr + nmin/60.0 + sec/3600.0; - int nfreq=(int)datcom_.fcenter; + int nfreq=static_cast<int>(getFcenter()); // if(nfreq<10 or nfreq > 50000) nfreq=144; - astrosub_(&nyear, &month, &nday, &uth, &nfreq, mygrid.toLatin1(), - hisgrid.toLatin1(), &azsun, &elsun, &azmoon, &elmoon, - &azmoondx, &elmoondx, &ntsky, &ndop, &ndop00,&ramoon, &decmoon, - &dgrd, &poloffset, &xnr, 6, 6); + // Build stable, 6-character, space-padded, uppercase buffers + QString mg = mygrid.trimmed().toUpper(); + QString hg = hisgrid.trimmed().toUpper(); - datcom_.nfast=ndop00; //Send self Doppler to decoder, via datcom - sprintf(cc, + QByteArray myGridData = mg.left(6).toLatin1(); + QByteArray hisGridData = hg.left(6).toLatin1(); + + myGridData = myGridData.leftJustified(6, ' '); + hisGridData = hisGridData.leftJustified(6, ' '); + + // Fortran expects CHARACTER*6 with trailing lengths in its ABI + int mygrid_len = 6; + int hisgrid_len = 6; + + astrosub_(&nyear, &month, &nday, &uth, &nfreq, + myGridData.constData(), + hisGridData.constData(), + &azsun, &elsun, &azmoon, &elmoon, + &azmoondx, &elmoondx, &ntsky, &ndop, &ndop00, + &ramoon, &decmoon, &dgrd, &poloffset, &xnr, + mygrid_len, hisgrid_len); + + setNdop00(ndop00); //Send self Doppler to decoder, via datcom + snprintf(cc, sizeof(cc), "Az: %6.1f\n" "El: %6.1f\n" "MyDop: %6d\n" @@ -134,8 +151,9 @@ void Astro::astroUpdate(QDateTime t, QString mygrid, QString hisgrid, if(f.open(QIODevice::WriteOnly | QIODevice::Append)) { QTextStream out(&f); out << t.toString("yyyy-MMM-dd hh:mm:ss"); - sprintf(cc,"%7.1f %7.1f %d %7.1f %7.1f %10.1f %7.2f\n", - azsun,elsun,iCycle,azOffset,elOffset,xavg,10.0*log10(xavg)); + snprintf(cc, sizeof(cc), + "%7.1f %7.1f %d %7.1f %7.1f %10.1f %7.2f\n", + azsun,elsun,iCycle,azOffset,elOffset,xavg,10.0*log10(xavg)); out << cc; f.close(); } @@ -161,7 +179,8 @@ void Astro::astroUpdate(QDateTime t, QString mygrid, QString hisgrid, if(ntxFreq != ntxFreq0) ndiff=1; ntxFreq0=ntxFreq; QTextStream out(&f); - sprintf(cc,"%2.2d:%2.2d:%2.2d,%5.1f,%5.1f,Moon\n" + snprintf(cc, sizeof(cc), + "%2.2d:%2.2d:%2.2d,%5.1f,%5.1f,Moon\n" "%2.2d:%2.2d:%2.2d,%5.1f,%5.1f,Sun\n" "%2.2d:%2.2d:%2.2d,%5.1f,%5.1f,Source\n" "%4d,%6d,%6d,Doppler\n" diff --git a/map65/commons.cpp b/map65/commons.cpp new file mode 100644 index 00000000..74c69b74 --- /dev/null +++ b/map65/commons.cpp @@ -0,0 +1,11 @@ +#include "commons.h" + +extern "C" { + float* dd = nullptr; + float* ss = nullptr; + float* savg = nullptr; + float* dd_old = nullptr; + float* ss_old = nullptr; + float* savg_old = nullptr; +} + diff --git a/map65/commons.h b/map65/commons.h index 16aecb89..888e922b 100644 --- a/map65/commons.h +++ b/map65/commons.h @@ -2,15 +2,22 @@ #define COMMONS_H #define NFFT 32768 +#define BASELINE_RATE 96000 +#define BASELINE_NFFT 32768 + #include <QString> +#include <cstdint> -extern "C" { +// This header defines the C++ interface to the Fortran datcom_ptrs_mod module. +// It replaces the legacy common block interface with explicit setter/getter functions. +extern "C" { +/* extern struct { //This is "common/datcom/..." in Fortran - float d4[4*5760000]; //Raw I/Q data from Linrad - float ss[4*322*NFFT]; //Half-symbol spectra at 0,45,90,135 deg pol - float savg[4*NFFT]; //Avg spectra at 0,45,90,135 deg pol + float *dd; //Raw I/Q data from Linrad + float *ss; //Half-symbol spectra at 0,45,90,135 deg pol + float *savg; //Avg spectra at 0,45,90,135 deg pol double fcenter; //Center freq from Linrad (MHz) int nutc; //UTC as integer, HHMM int idphi; //Phase correction for Y pol'n, degrees @@ -45,6 +52,107 @@ extern struct { //This is "common/datcom/..." in Fortran int junk1; //Used to test extent of copy to shared memory int junk2; } datcom_; +*/ + + extern float* dd; + extern float* ss; + extern float* savg; + extern float* dd_old; + extern float* ss_old; + extern float* savg_old; + extern int manualDecodeFlag ; + double get_fcenter(); + void get_mycall(char*); + void get_hiscall(char*); + void get_mygrid(char*); + void get_hisgrid(char*); + void get_datetime(char*); + int get_manual_decode_flag(); + int get_nutc(); + int get_ndop00(); + int get_nkeep(); + int get_idphi(); + int get_mousedf(); + int get_mousefqso(); + int get_nagain(); + int get_ndepth(); + int get_ndiskdat(); + int get_neme(); + int get_newdat(); + int get_nfa(); + int get_nfb(); + int get_nfcal(); + int get_nfshift(); + int get_mcall3(); + int get_ntimeout(); + int get_ntol(); + int get_nxant(); + int get_map65RxLog(); + int get_nfsample(); + int get_nxpol(); + int get_nmode(); + int get_nsave(); + int get_max_drift(); + int get_nhsym(); + int get_junk1(); + int get_junk2(); + void set_d8_ptr(void* ptr, int dim1, int dim2); + void set_dd_ptr(void* ptr, int dim1, int dim2); + void set_ss_ptr(void* ptr, int dim1, int dim2, int dim3); + void set_savg_ptr(void* ptr, int dim1, int dim2); + void set_dd_old_ptr(void* ptr, int dim1, int dim2); + void set_ss_old_ptr(void* ptr, int dim1, int dim2, int dim3); + void set_savg_old_ptr(void* ptr, int dim1, int dim2); + void set_fcenter(double); + void set_map65RxLog(int); + void set_nutc(int); + void set_nkeep(int); + void set_ndop00(int); + void set_idphi(int); + void set_mousedf(int); + void set_mousefqso(int); + void set_nagain(int); + void set_ndepth(int); + void set_ndiskdat(int); + void set_neme(int); + void set_newdat(int); + void set_nfa(int); + void set_nfb(int); + void set_nfcal(int); + void set_nfshift(int); + void set_mcall3(int); + void set_ntimeout(int); + void set_ntol(int); + void set_nxant(int); + void set_nfsample(int); + void set_nxpol(int); + void set_nmode(int); + void set_nsave(int); + void set_max_drift(int); + void set_nhsym(int); + void set_junk1(int); + void set_junk2(int); + void set_mycall(const char*); + void set_hiscall(const char*); + void set_mygrid(const char*); + void set_hisgrid(const char*); + void set_datetime(const char*); + void set_quitid(unsigned long long); + + void run_m65_(int* pol, int* sample_rate); + void set_stop_m65(int val); + void set_decoder_ready(int val); + std::int64_t publish_decode_request(); + void cancel_pending_decode_requests(); + void advance_live_input_generation(); + bool is_current_decode_request(std::int64_t request_id); + void set_wsjtx_dir_(const char* path, int path_len); + void set_stdout_channel(void* buf_ptr, + void* hdr_ptr, + int buf_size, + intptr_t event_handle); + void set_manual_decode_flag(int); + void snapshot_buffers(); } extern QStringList allDecodes; @@ -53,6 +161,148 @@ extern QString guiDate; extern bool m_w3szUrl; extern QString m_otherUrl; -extern bool m_spot_to_psk_reporter; + +// Scalar getters +inline int getNutc() { return get_nutc(); } +inline int getNdop00() { return get_ndop00(); } +inline int getNkeep() { return get_nkeep(); } +inline int getIdphi() { return get_idphi(); } +inline int getMousedf() { return get_mousedf(); } +inline int getMousefqso() { return get_mousefqso(); } +inline int getNagain() { return get_nagain(); } +inline int getNdepth() { return get_ndepth(); } +inline int getNdiskdat() { return get_ndiskdat(); } +inline int getNeme() { return get_neme(); } +inline int getNewdat() { return get_newdat(); } +inline int getNfa() { return get_nfa(); } +inline int getNfb() { return get_nfb(); } +inline int getNfcal() { return get_nfcal(); } +inline int getNfshift() { return get_nfshift(); } +inline int getMcall3() { return get_mcall3(); } +inline int getNtimeout() { return get_ntimeout(); } +inline int getNtol() { return get_ntol(); } +inline int getNxant() { return get_nxant(); } +inline int getMap65RxLog() { return get_map65RxLog(); } +inline int getNfsample() { return get_nfsample(); } +inline int getNxpol() { return get_nxpol(); } +inline int getNmode() { return get_nmode(); } +inline int getNsave() { return get_nsave(); } +inline int getMaxDrift() { return get_max_drift(); } +inline int getNhsym() { return get_nhsym(); } +inline int getJunk1() { return get_junk1(); } +inline int getJunk2() { return get_junk2(); } + +inline double getFcenter() { return get_fcenter(); } + +// Character getters +inline QString getMyCall() { + char buf[12] = {}; + get_mycall(buf); + return QString::fromLatin1(buf, 12).trimmed(); +} + +inline QString getHisCall() { + char buf[12] = {}; + get_hiscall(buf); + return QString::fromLatin1(buf, 12).trimmed(); +} + +inline QString getMyGrid() { + char buf[6] = {}; + get_mygrid(buf); + return QString::fromLatin1(buf, 6).trimmed(); +} + +inline QString getHisGrid() { + char buf[6] = {}; + get_hisgrid(buf); + return QString::fromLatin1(buf, 6).trimmed(); +} + +// NOTE ABOUT DATETIME LENGTH (17 vs 20) +// +// The Fortran module npar_ptrs_mod declares `datetime` as CHARACTER(len=20) +// for historical compatibility with the old COMMON block layout. However, +// only the first 17 characters are meaningful. The decoder (m65_mod) formats +// and writes: +// +// write(..., '( "UTC Date: ", a17 )') datetime(1:17) +// +// i.e., the timestamp is always exactly 17 characters: +// +// YYYY-MM-DD HH:MM = 17 chars +// +// The remaining 3 characters in the Fortran variable are unused padding. +// Therefore, the C/Fortran interface intentionally exchanges only 17 bytes +// for datetime. This matches the actual data semantics and avoids passing +// unused trailing padding through the interface. +// +// If the decoder ever changes its timestamp format, this boundary should be +// revisited, but as of now the 17-byte interface is correct and intentional. + +inline QString getDatetime() { + char buf[17] = {}; + get_datetime(buf); + return QString::fromLatin1(buf, 17).trimmed(); +} + +//Scalar setters +inline void setFcenter(double val) { set_fcenter(val); } +inline void setNutc(int val) { set_nutc(val); } +inline void setNdop00(int val) { set_ndop00(val); } +inline void setNkeep(int val) { set_nkeep(val); } +inline void setIdphi(int val) { set_idphi(val); } +inline void setMousedf(int val) { set_mousedf(val); } +inline void setMousefqso(int val) { set_mousefqso(val); } +inline void setNagain(int val) { set_nagain(val); } +inline void setNdepth(int val) { set_ndepth(val); } +inline void setNdiskdat(int val) { set_ndiskdat(val); } +inline void setNeme(int val) { set_neme(val); } +inline void setNewdat(int val) { set_newdat(val); } +inline void setNfa(int val) { set_nfa(val); } +inline void setNfb(int val) { set_nfb(val); } +inline void setNfcal(int val) { set_nfcal(val); } +inline void setNfshift(int val) { set_nfshift(val); } +inline void setMcall3(int val) { set_mcall3(val); } +inline void setNtimeout(int val) { set_ntimeout(val); } +inline void setNtol(int val) { set_ntol(val); } +inline void setNxant(int val) { set_nxant(val); } +inline void setMap65RxLog(int val) { set_map65RxLog(val); } +inline void setNfsample(int val) { set_nfsample(val); } +inline void setNxpol(int val) { set_nxpol(val); } +inline void setNmode(int val) { set_nmode(val); } +inline void setNsave(int val) { set_nsave(val); } +inline void setMaxDrift(int val) { set_max_drift(val); } +inline void setNhsym(int val) { set_nhsym(val); } +inline void setJunk1(int val) { set_junk1(val); } +inline void setJunk2(int val) { set_junk2(val); } +inline void setQuitID(unsigned long long val) { set_quitid(val); } +inline void setDecoderReady(int val) { set_decoder_ready(val); } + +// Character setters +inline void setMyCall(const QString& val) { + QByteArray arr = val.leftJustified(12, ' ', true).toLatin1(); + set_mycall(arr.constData()); +} + +inline void setHisCall(const QString& val) { + QByteArray arr = val.leftJustified(12, ' ', true).toLatin1(); + set_hiscall(arr.constData()); +} + +inline void setMyGrid(const QString& val) { + QByteArray arr = val.leftJustified(6, ' ', true).toLatin1(); + set_mygrid(arr.constData()); +} + +inline void setHisGrid(const QString& val) { + QByteArray arr = val.leftJustified(6, ' ', true).toLatin1(); + set_hisgrid(arr.constData()); +} + +inline void setDatetime(const QString& val) { + QByteArray arr = val.leftJustified(17, ' ', true).toLatin1(); + set_datetime(arr.constData()); +} #endif // COMMONS_H diff --git a/map65/cqdatasender.cpp b/map65/cqdatasender.cpp index 6e437c44..182b40b5 100644 --- a/map65/cqdatasender.cpp +++ b/map65/cqdatasender.cpp @@ -5,6 +5,7 @@ #include <QNetworkReply> #include <QJsonDocument> #include <QJsonObject> +#include <QCoreApplication> #include <QDebug> #include <QThread> @@ -25,27 +26,30 @@ void CQDataSender::send(QString theUrl, const QString &data) { QUrl url(theUrl); QNetworkRequest request(url); - request.setRawHeader("User-Agent", "QMAP v0.5"); - request.setRawHeader("X-Custom-User-Agent", "QMAP v0.5"); + QByteArray userAgent = (QCoreApplication::applicationName() + " v" + + QCoreApplication::applicationVersion()).toUtf8(); + request.setRawHeader("User-Agent", userAgent); + request.setRawHeader("X-Custom-User-Agent", userAgent); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); QByteArray payload = data.toUtf8(); request.setRawHeader("Content-Length",QByteArray::number(payload.size())); QNetworkReply *reply = m_networkManager->post(request, payload); qDebug() << "Current thread for CQDataSender::send:" << QThread::currentThread(); - // Use the OLD signal name: 'error' instead of 'errorOccurred' -#if QT_VERSION >= QT_VERSION_CHECK (5, 15, 0) - connect(reply, &QNetworkReply::errorOccurred, this, [this, reply](QNetworkReply::NetworkError) { - emit errorOccurred(reply->errorString()); - }); -#else - connect(reply, static_cast<void(QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error), - this, [this, reply](QNetworkReply::NetworkError error) { - Q_UNUSED(error) - emit errorOccurred(reply->errorString()); - }); -#endif - // Connect to sslErrors without QOverload + // Qt 5.15+ (ignored on 5.12) + connect(reply, + SIGNAL(errorOccurred(QNetworkReply::NetworkError)), + this, + SLOT(onReplyError())); + +// Qt 5.12 (ignored on Qt 6) + connect(reply, + SIGNAL(error(QNetworkReply::NetworkError)), + this, + SLOT(onReplyError())); + + + // SSL errors unchanged connect(reply, &QNetworkReply::sslErrors, this, [this](const QList<QSslError> &errors) { QStringList errList; for (const auto &e : errors) @@ -65,3 +69,10 @@ void CQDataSender::onFinished(QNetworkReply *reply) reply->deleteLater(); qDebug() << "Current thread for CQDataSender::onFinished:" << QThread::currentThread(); } + +void CQDataSender::onReplyError() +{ + QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender()); + if (!reply) return; + emit errorOccurred(reply->errorString()); +} diff --git a/map65/cqdatasender.h b/map65/cqdatasender.h index 9b21f238..4c8a9339 100644 --- a/map65/cqdatasender.h +++ b/map65/cqdatasender.h @@ -24,6 +24,7 @@ signals: private slots: void onFinished(QNetworkReply *reply); + void onReplyError(); private: QNetworkAccessManager *m_networkManager; diff --git a/map65/decode_label.h b/map65/decode_label.h new file mode 100644 index 00000000..ecf63145 --- /dev/null +++ b/map65/decode_label.h @@ -0,0 +1,51 @@ +#ifndef MAP65_DECODE_LABEL_H +#define MAP65_DECODE_LABEL_H + +#include <QString> +#include <QtGlobal> + +// One decoded-callsign label drawn on top of the WideGraph waterfall +// at its audio-offset x-position. WideGraph maintains a list of these +// (refreshed each time mainwindow taps the decode-append path); CPlotter +// reads the list via setDecodeLabels() and overlays them in paintEvent. +// +// Lives in its own header so widegraph.h and plotter.h can both include +// it without creating a circular dependency between the two larger +// headers. +// +// Mirrors qmap/decode_label.h — MAP65 port (N6NU 2026-05-12) matches +// the QMAP feature exactly. +struct DecodeLabel { + double freq_khz; // audio offset (kHz), straight from the decode line + QString callsign; // sender's call extracted from the message field + qint64 last_seen_ms; // wall-clock of most recent fresh decode + int hits; // for tie-breaking when stacking + bool is_jt65; // true = JT65 (orange label); false = Q65 (yellow) + + DecodeLabel(double f, const QString& c, qint64 t, int h, bool jt65) + : freq_khz(f), callsign(c), last_seen_ms(t), hits(h), is_jt65(jt65) {} + DecodeLabel() : freq_khz(0), last_seen_ms(0), hits(0), is_jt65(false) {} +}; + +// Font-size choice for the callsign overlay. Menu values: +// 7 pt = Small (tightest packing, hardest to read at distance) +// 8 pt = Normal (default — fits dense bands, still legible) +// 10 pt = Medium (more readable, more stacking pressure) +// 12 pt = Large (easiest to read, biggest stacking pressure) +enum class DecodeLabelFontSize { + Small = 7, + Normal = 8, + Medium = 10, + Large = 12, +}; + +// Anchor position for the callsign overlay on the upper waterfall. +// Mirrors qmap/decode_label.h. Top = stack down from waterfall top +// (legacy); Bottom = stack up from the divider so fresh signals at +// the top of the waterfall stay visible. +enum class DecodeLabelPosition { + Top = 0, + Bottom = 1, +}; + +#endif // MAP65_DECODE_LABEL_H diff --git a/map65/devsetup.cpp b/map65/devsetup.cpp index 007b0d1c..4fae12ea 100644 --- a/map65/devsetup.cpp +++ b/map65/devsetup.cpp @@ -4,21 +4,81 @@ #include <QDebug> #include <cstdio> #include <portaudio.h> +#include <vector> +#include <QDir> +#include <QStringList> +#include <QSerialPortInfo> +#include <QRegularExpression> +#include <QSignalBlocker> +#include <QSettings> +#include "SettingsGroup.hpp" + +#if !defined(Q_OS_WIN) +extern "C" { + void ptt_set_override(const char *path); +} +#endif + +static QStringList enumeratePorts() +{ + QStringList result; + + QList<QSerialPortInfo> ports = QSerialPortInfo::availablePorts(); + + for (auto const& p : ports) + { + if (!p.portName().contains("NULL")) + { + QString loc = p.systemLocation(); + loc.remove(QRegularExpression{R"(^\\\\\.\\)"}); + result << loc; + } + } + + std::sort(result.begin(), result.end(), [](QString const& a, QString const& b) { + QRegularExpression re{"(\\d+)$"}; + auto ma = re.match(a); + auto mb = re.match(b); -#define MAXDEVICES 200 + if (ma.hasMatch() && mb.hasMatch()) + return ma.captured(1).toInt() < mb.captured(1).toInt(); + + return a < b; + }); + + return result; +} + +#define MAXDEVICES 1024 // was 200 //----------------------------------------------------------- DevSetup() -DevSetup::DevSetup(QWidget *parent) : QDialog(parent) +DevSetup::DevSetup(MainWindow *parent) + : QDialog(parent), + mw(parent) { ui.setupUi(this); //setup the dialog form + + { + QSettings settings(mw->m_settings_filename, QSettings::IniFormat); + SettingsGroup g {&settings, "DevSetup"}; + restoreGeometry(settings.value("geometry").toByteArray()); + } + m_restartSoundIn=false; m_restartSoundOut=false; + m_restartRequired=false; + m_pendingFs96000=-1; QButtonGroup *buttonGroup = new QButtonGroup(this); buttonGroup->addButton(ui.w3szBut); buttonGroup->addButton(ui.otherBut); - - connect(buttonGroup, SIGNAL(buttonClicked(int)), this, SLOT(onButtonClicked(int))); + +connect(buttonGroup, + QOverload<QAbstractButton *>::of(&QButtonGroup::buttonClicked), + this, + [this](QAbstractButton *) { + onButtonClicked(); + }); } @@ -26,100 +86,190 @@ DevSetup::~DevSetup() { } +void DevSetup::done(int r) +{ + // accept()/reject() (OK, Cancel, and the title-bar close button, which + // triggers reject() internally) all funnel through here -- unlike + // closeEvent(), which only fires for the title-bar close button, not + // for accept()/reject() called directly from button clicks. + QSettings settings(mw->m_settings_filename, QSettings::IniFormat); + SettingsGroup g {&settings, "DevSetup"}; + settings.setValue("geometry", saveGeometry()); + QDialog::done(r); +} + void DevSetup::initDlg() { int k,id; - int valid_devices=0; - int minChan[MAXDEVICES]; - int maxChan[MAXDEVICES]; - int minSpeed[MAXDEVICES]; - int maxSpeed[MAXDEVICES]; - char hostAPI_DeviceName[MAXDEVICES][50]; + + // Use heap-allocated vectors instead of stack arrays + std::vector<int> minChan(MAXDEVICES); + std::vector<int> maxChan(MAXDEVICES); + std::vector<int> minSpeed(MAXDEVICES); + std::vector<int> maxSpeed(MAXDEVICES); + + // Use a unique pointer or vector for the 2D char array + struct DeviceName { + char name[50]; +}; + std::vector<DeviceName> hostAPI_DeviceName(MAXDEVICES); + char s[256]; - int numDevices=Pa_GetDeviceCount(); - getDev(&numDevices,hostAPI_DeviceName,minChan,maxChan,minSpeed,maxSpeed); - k=0; - for(id=0; id<numDevices; id++) { - if(96000 >= minSpeed[id] && 96000 <= maxSpeed[id]) { - m_inDevList[k]=id; - k++; - sprintf(s,"%2d %d %-49s",id,maxChan[id],hostAPI_DeviceName[id]); - QString t(s); - ui.comboBoxSndIn->addItem(t); - valid_devices++; - } + int numDevices = Pa_GetDeviceCount(); + + if (numDevices > MAXDEVICES) { + numDevices = MAXDEVICES; } + // Pass the pointers to the data inside the vectors +getDev(&numDevices, + reinterpret_cast<char (*)[50]>(hostAPI_DeviceName.data()), + minChan.data(), maxChan.data(), minSpeed.data(), maxSpeed.data()); + +k = 0; +for (id = 0; id < numDevices; id++) { + + if (!(g_sampleRate >= minSpeed[id] && g_sampleRate <= maxSpeed[id])) + continue; + + +#ifdef _WIN32 + if (!QString(hostAPI_DeviceName[id].name).contains("MME")) + continue; +#endif + + // Now safe to add to list + m_inDevList[k] = id; + + snprintf(s, sizeof(s), "%2d %d %-49.49s", + id, maxChan[id], hostAPI_DeviceName[id].name); + + ui.comboBoxSndIn->addItem(QString(s)); + k++; +} + const PaDeviceInfo *pdi; int nchout; - char *p,*p1; char p2[256]; - char pa_device_name[128]; - char pa_device_hostapi[128]; k=0; - for(id=0; id<numDevices; id++ ) { - pdi=Pa_GetDeviceInfo(id); - nchout=pdi->maxOutputChannels; - if(nchout>=2) { - m_outDevList[k]=id; - k++; - sprintf((char*)(pa_device_name),"%s",pdi->name); - sprintf((char*)(pa_device_hostapi),"%s", - Pa_GetHostApiInfo(pdi->hostApi)->name); - - p1=(char*)""; - p=strstr(pa_device_hostapi,"MME"); - if(p!=NULL) p1=(char*)"MME"; - p=strstr(pa_device_hostapi,"Direct"); - if(p!=NULL) p1=(char*)"DirectX"; - p=strstr(pa_device_hostapi,"WASAPI"); - if(p!=NULL) p1=(char*)"WASAPI"; - p=strstr(pa_device_hostapi,"ASIO"); - if(p!=NULL) p1=(char*)"ASIO"; - p=strstr(pa_device_hostapi,"WDM-KS"); - if(p!=NULL) p1=(char*)"WDM-KS"; - - sprintf(p2,"%2d %-8s %-39s",id,p1,pa_device_name); - QString t(p2); - ui.comboBoxSndOut->addItem(t); - } - } + for (id = 0; id < numDevices; id++) { + + pdi = Pa_GetDeviceInfo(id); + if (!pdi) continue; + + nchout = pdi->maxOutputChannels; + if (nchout < 1) + continue; + + QString devName = QString(pdi->name); + +#ifdef __linux__ + QString lower = devName.toLower(); + + // Only allow plug/resampling devices for TX + bool isPlug = + lower.contains("default") || + lower.contains("dmix") || + lower.contains("pulse") || + lower.contains("pipewire") || + !lower.contains("hw:"); // reject raw hw: devices + + if (!isPlug) + continue; +#endif + + const char* api = Pa_GetHostApiInfo(pdi->hostApi)->name; + + // Skip WASAPI and WDM-KS for TX (Windows only) + if (strstr(api, "WASAPI") || strstr(api,"WDM-KS")) + continue; + + // Now safe to add to list + m_outDevList[k++] = id; - ui.myCallEntry->setText(m_myCall); - ui.myGridEntry->setText(m_myGrid); - ui.idIntSpinBox->setValue(m_idInt); - ui.pttComboBox->setCurrentIndex(m_pttPort); - ui.astroFont->setValue(m_astroFont); - ui.cbXpol->setChecked(m_xpol); - ui.rbAntennaX->setChecked(m_xpolx); - ui.saveDirEntry->setText(m_saveDir); - ui.azelDirEntry->setText(m_azelDir); - ui.editorEntry->setText(m_editorCommand); - ui.dxccEntry->setText(m_dxccPfx); - ui.timeoutSpinBox->setValue(m_timeout); - ui.dPhiSpinBox->setValue(m_dPhi); - ui.fCalSpinBox->setValue(m_fCal); - ui.faddEntry->setText(QString::number(m_fAdd,'f',3)); - ui.networkRadioButton->setChecked(m_network); - ui.soundCardRadioButton->setChecked(!m_network); - ui.rb96000->setChecked(m_fs96000); - ui.rb95238->setChecked(!m_fs96000); - ui.rbIQXT->setChecked(m_bIQxt); - ui.rbSi570->setChecked(!m_bIQxt); - ui.mult570TxSpinBox->setEnabled(m_bIQxt); - ui.comboBoxSndIn->setEnabled(!m_network); - ui.comboBoxSndIn->setCurrentIndex(m_nDevIn); - ui.comboBoxSndOut->setCurrentIndex(m_nDevOut); - ui.sbPort->setValue(m_udpPort); - ui.cbIQswap->setChecked(m_IQswap); - ui.cbInitIQplus->setChecked(m_initIQplus); - ui.sb_dB->setValue(m_dB); - ui.mult570SpinBox->setValue(m_mult570); - ui.mult570TxSpinBox->setValue(m_mult570Tx); - ui.cal570SpinBox->setValue(m_cal570); - ui.sbTxOffset->setValue(m_TxOffset); - ::sscanf (m_colors.toLatin1(),"%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x", + // Determine label + const char* p1 = ""; + if (strstr(api, "MME")) p1 = "MME"; + if (strstr(api, "Direct")) p1 = "DirectX"; + if (strstr(api, "ASIO")) p1 = "ASIO"; + if (strstr(api, "ALSA")) p1 = "ALSA"; + + snprintf(p2, sizeof(p2), "%2d %-8.8s %-39.39s", + id, p1, pdi->name); + + ui.comboBoxSndOut->addItem(QString(p2)); +} + ui.myCallEntry->setText(mw->m_myCall); + ui.myGridEntry->setText(mw->m_myGrid); + ui.idIntSpinBox->setValue(mw->m_idInt); + + ui.pttComboBox->clear(); + ui.pttComboBox->addItem("NONE"); + + // unified cross-platform enumeration + QStringList ports = enumeratePorts(); + for (auto const& p : ports) + ui.pttComboBox->addItem(p); + + // restore saved selection + QString saved = mw->m_pttPath; + int idx = ui.pttComboBox->findText(saved); + if (idx >= 0) + ui.pttComboBox->setCurrentIndex(idx); + + // backend override (Linux/macOS only) + #if !defined(Q_OS_WIN) + if (ui.pttComboBox->currentText() != "NONE") + ptt_set_override(ui.pttComboBox->currentText().toUtf8().constData()); + else + ptt_set_override(nullptr); + #endif + + if (mw->m_fs96000 == 2) + oldSampleRate = 192000; + else if (mw->m_fs96000 == 1) + oldSampleRate = 96000; + else if (mw->m_fs96000 == 0) + oldSampleRate = 95238; + else oldSampleRate = 96000; + + ui.astroFont->setValue(mw->m_astroFont); + ui.cbXpol->setChecked(mw->m_xpol); + ui.rbAntennaX->setChecked(mw->m_xpolx); + ui.saveDirEntry->setText(mw->m_saveDir); + ui.azelDirEntry->setText(mw->m_azelDir); + ui.editorEntry->setText(mw->m_editorCommand); + ui.dxccEntry->setText(mw->m_dxccPfx); + ui.timeoutSpinBox->setValue(mw->m_timeout); + ui.dPhiSpinBox->setValue(mw->m_dPhi); + ui.fCalSpinBox->setValue(mw->m_fCal); + ui.faddEntry->setText(QString::number(mw->m_fAdd,'f',3)); + { + QSignalBlocker blockNetwork {ui.networkRadioButton}; + QSignalBlocker blockSoundCard {ui.soundCardRadioButton}; + ui.networkRadioButton->setChecked(mw->m_network); + ui.soundCardRadioButton->setChecked(!mw->m_network); + } + ui.rb192000->setChecked(mw->m_fs96000 == 2); + ui.rb96000->setChecked(mw->m_fs96000 == 1); + ui.rb95238->setChecked(mw->m_fs96000 == 0); + on_soundCardRadioButton_toggled(ui.soundCardRadioButton->isChecked()); + ui.rbIQXT->setChecked(mw->m_bIQxt); + ui.rbSi570->setChecked(!mw->m_bIQxt); + ui.mult570TxSpinBox->setEnabled(mw->m_bIQxt); + ui.comboBoxSndIn->setEnabled(!mw->m_network); + ui.comboBoxSndIn->setCurrentIndex(mw->m_nDevIn); + ui.comboBoxSndOut->setCurrentIndex(mw->m_nDevOut); + ui.sbPort->setValue(mw->m_udpPort); + ui.cbIQswap->setChecked(mw->m_IQswap); + ui.cbInitIQplus->setChecked(mw->m_initIQplus); + ui.sb_dB->setValue(mw->m_dB); + ui.mult570SpinBox->setValue(mw->m_mult570); + ui.mult570TxSpinBox->setValue(mw->m_mult570Tx); + ui.cal570SpinBox->setValue(mw->m_cal570); + ui.sbTxOffset->setValue(mw->m_TxOffset); + ::sscanf (mw->m_colors.toLatin1(),"%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x", &r,&g,&b,&r0,&g0,&b0,&r1,&g1,&b1,&r2,&g2,&b2,&r3,&g3,&b3); updateColorLabels(); ui.sbBackgroundRed->setValue(r); @@ -138,14 +288,15 @@ void DevSetup::initDlg() ui.sbBlue2->setValue(b2); ui.sbBlue3->setValue(b3); - m_paInDevice=m_inDevList[m_nDevIn]; - m_paOutDevice=m_outDevList[m_nDevOut]; + mw->m_paInDevice=m_inDevList[mw->m_nDevIn]; + mw->m_paOutDevice=m_outDevList[mw->m_nDevOut]; - ui.otherUrlBox->setText(m_otherUrl); - if(m_w3szUrl) ui.w3szBut->setChecked(true); + ui.otherUrlBox->setText(mw->m_otherUrl); + if(mw->m_w3szUrl) ui.w3szBut->setChecked(true); else ui.otherBut->setChecked(true); - ui.pskBox->setChecked(m_spot_to_psk_reporter); + ui.pskBox->setChecked(mw->m_spot_to_psk_reporter); + ui.pskReporterTcpIpBox->setChecked(mw->m_psk_reporter_tcpip); } //------------------------------------------------------- accept() @@ -155,57 +306,110 @@ void DevSetup::accept() // Check to see whether SoundInThread must be restarted, // and save user parameters. - if(m_network!=ui.networkRadioButton->isChecked() or - m_nDevIn!=ui.comboBoxSndIn->currentIndex() or - m_paInDevice!=m_inDevList[m_nDevIn] or - m_xpol!=ui.cbXpol->isChecked() or - m_udpPort!=ui.sbPort->value()) m_restartSoundIn=true; - - if(m_nDevOut!=ui.comboBoxSndOut->currentIndex() or - m_paOutDevice!=m_outDevList[m_nDevOut]) m_restartSoundOut=true; - - m_myCall=ui.myCallEntry->text(); - m_myGrid=ui.myGridEntry->text(); - m_idInt=ui.idIntSpinBox->value(); - m_pttPort=ui.pttComboBox->currentIndex(); - m_astroFont=ui.astroFont->value(); - m_xpol=ui.cbXpol->isChecked(); - m_xpolx=ui.rbAntennaX->isChecked(); - m_saveDir=ui.saveDirEntry->text(); - m_azelDir=ui.azelDirEntry->text(); - m_editorCommand=ui.editorEntry->text(); - m_dxccPfx=ui.dxccEntry->text(); - m_timeout=ui.timeoutSpinBox->value(); - m_dPhi=ui.dPhiSpinBox->value(); - m_fCal=ui.fCalSpinBox->value(); - m_fAdd=ui.faddEntry->text().toDouble(); - m_network=ui.networkRadioButton->isChecked(); - m_fs96000=ui.rb96000->isChecked(); - m_bIQxt=ui.rbIQXT->isChecked(); - m_nDevIn=ui.comboBoxSndIn->currentIndex(); - m_paInDevice=m_inDevList[m_nDevIn]; - m_nDevOut=ui.comboBoxSndOut->currentIndex(); - m_paOutDevice=m_outDevList[m_nDevOut]; - m_udpPort=ui.sbPort->value(); - m_IQswap=ui.cbIQswap->isChecked(); - m_initIQplus=ui.cbInitIQplus->isChecked(); - m_dB=ui.sb_dB->value(); - m_mult570=ui.mult570SpinBox->value(); - m_mult570Tx=ui.mult570TxSpinBox->value(); - m_cal570=ui.cal570SpinBox->value(); - m_TxOffset=ui.sbTxOffset->value(); - m_otherUrl=ui.otherUrlBox->text(); - m_w3szUrl = ui.w3szBut->isChecked(); + int newSampleRate = ui.rb192000->isChecked() ? 192000 : + ui.rb96000->isChecked() ? 96000 : + 95238; + int newFs96000 = ui.rb192000->isChecked() ? 2 : + ui.rb96000->isChecked() ? 1 : + 0; + double const newFAdd = ui.faddEntry->text().toDouble(); + + m_restartRequired = oldSampleRate != newSampleRate; + if (m_restartRequired) { + m_pendingFs96000 = newFs96000; + } else { + emit sampleRateChanged(newSampleRate); + } + + if(mw->m_network!=ui.networkRadioButton->isChecked() or + mw->m_nDevIn!=ui.comboBoxSndIn->currentIndex() or + mw->m_paInDevice!=m_inDevList[mw->m_nDevIn] or + mw->m_xpol!=ui.cbXpol->isChecked() or + mw->m_fAdd!=newFAdd or + mw->m_udpPort!=ui.sbPort->value()) m_restartSoundIn=true; + + if(mw->m_nDevOut!=ui.comboBoxSndOut->currentIndex() or + mw->m_paOutDevice!=m_outDevList[mw->m_nDevOut]) m_restartSoundOut=true; + + mw->m_myCall=ui.myCallEntry->text(); + mw->m_myGrid=ui.myGridEntry->text(); + mw->m_idInt=ui.idIntSpinBox->value(); - m_spot_to_psk_reporter = ui.pskBox->isChecked(); + mw->m_pttPath = ui.pttComboBox->currentText(); + if (mw->m_pttPath.startsWith("COM")) + mw->m_pttPortNumber = mw->m_pttPath.mid(3).toInt(); + else + mw->m_pttPortNumber = 1; + +#if !defined(Q_OS_WIN) + if (ui.pttComboBox->currentText() != "NONE") + ptt_set_override(ui.pttComboBox->currentText().toUtf8().constData()); + else + ptt_set_override(nullptr); +#endif + + mw->m_astroFont=ui.astroFont->value(); + mw->m_xpol=ui.cbXpol->isChecked(); + mw->m_xpolx=ui.rbAntennaX->isChecked(); + mw->m_saveDir=ui.saveDirEntry->text(); + mw->m_azelDir=ui.azelDirEntry->text(); + mw->m_editorCommand=ui.editorEntry->text(); + mw->m_dxccPfx=ui.dxccEntry->text(); + mw->m_timeout=ui.timeoutSpinBox->value(); + mw->m_dPhi=ui.dPhiSpinBox->value(); + mw->m_fCal=ui.fCalSpinBox->value(); + mw->m_fAdd=newFAdd; + mw->m_network=ui.networkRadioButton->isChecked(); + if (!m_restartRequired) { + mw->m_fs96000 = newFs96000; + } + mw->m_bIQxt=ui.rbIQXT->isChecked(); + mw->m_nDevIn=ui.comboBoxSndIn->currentIndex(); + mw->m_paInDevice=m_inDevList[mw->m_nDevIn]; + mw->m_nDevOut=ui.comboBoxSndOut->currentIndex(); + mw->m_paOutDevice=m_outDevList[mw->m_nDevOut]; + mw->m_udpPort=ui.sbPort->value(); + mw->m_IQswap=ui.cbIQswap->isChecked(); + mw->m_initIQplus=ui.cbInitIQplus->isChecked(); + mw->m_dB=ui.sb_dB->value(); + mw->m_mult570=ui.mult570SpinBox->value(); + mw->m_mult570Tx=ui.mult570TxSpinBox->value(); + mw->m_cal570=ui.cal570SpinBox->value(); + mw->m_TxOffset=ui.sbTxOffset->value(); + mw->m_otherUrl=ui.otherUrlBox->text(); + mw->m_w3szUrl = ui.w3szBut->isChecked(); + + mw->m_spot_to_psk_reporter = ui.pskBox->isChecked(); + mw->m_psk_reporter_tcpip = ui.pskReporterTcpIpBox->isChecked(); + + if (m_restartRequired) { + QMessageBox::information(this, + "Restart Required", + "Changing sample rate requires MAP65 to be restarted.\n" + "Please exit MAP65 and start it again."); + } + // Normal path QDialog::accept(); + } void DevSetup::on_soundCardRadioButton_toggled(bool checked) { ui.comboBoxSndIn->setEnabled(ui.soundCardRadioButton->isChecked()); - ui.rb96000->setChecked(checked); + int fs96000 = ui.rb192000->isChecked() ? 2 : + ui.rb95238->isChecked() ? 0 : + 1; + if(checked) { + if(fs96000 == 0) fs96000 = 1; + ui.rb95238->setEnabled(false); + } + else { + ui.rb95238->setEnabled(true); + } + ui.rb192000->setChecked(fs96000 == 2); + ui.rb96000->setChecked(fs96000 == 1); + ui.rb95238->setChecked(fs96000 == 0); ui.rb95238->setEnabled(!checked); ui.label_InputDev->setEnabled(checked); ui.label_Port->setEnabled(!checked); @@ -218,36 +422,36 @@ void DevSetup::onButtonClicked() { if(ui.w3szBut->isChecked()) { - m_w3szUrl = true; + mw->m_w3szUrl = true; } else { - m_w3szUrl = false; + mw->m_w3szUrl = false; } } void DevSetup::on_cbXpol_stateChanged(int n) { - m_xpol = (n!=0); - ui.rbAntenna->setEnabled(m_xpol); - ui.rbAntennaX->setEnabled(m_xpol); - ui.dPhiSpinBox->setEnabled(m_xpol); - ui.labelDphi->setEnabled(m_xpol); + mw->m_xpol = (n!=0); + ui.rbAntenna->setEnabled(mw->m_xpol); + ui.rbAntennaX->setEnabled(mw->m_xpol); + ui.dPhiSpinBox->setEnabled(mw->m_xpol); + ui.labelDphi->setEnabled(mw->m_xpol); } void DevSetup::on_cal570SpinBox_valueChanged(double ppm) { - m_cal570=ppm; + mw->m_cal570=ppm; } void DevSetup::on_mult570SpinBox_valueChanged(int mult) { - m_mult570=mult; + mw->m_mult570=mult; } void DevSetup::on_sb_dB_valueChanged(int n) { - m_dB=n; + mw->m_dB=n; } void DevSetup::updateColorLabels() @@ -306,8 +510,8 @@ void DevSetup::updateColorLabels() .arg (b3, 2, 16, QLatin1Char {'0'}) ); - m_colors.clear (); - QTextStream ots {&m_colors, QIODevice::WriteOnly}; + mw->m_colors.clear (); + QTextStream ots {&mw->m_colors, QIODevice::WriteOnly}; ots.setIntegerBase (16); ots.setFieldWidth (2); ots.setPadChar ('0'); @@ -399,19 +603,19 @@ void DevSetup::on_pushButton_5_clicked() void DevSetup::on_mult570TxSpinBox_valueChanged(int n) { - m_mult570Tx=n; + mw->m_mult570Tx=n; } void DevSetup::on_rbIQXT_toggled(bool checked) { - m_bIQxt=checked; - ui.mult570TxSpinBox->setEnabled(m_bIQxt); - ui.label_25->setEnabled(m_bIQxt); - ui.sbTxOffset->setEnabled(m_bIQxt); - ui.label_26->setEnabled(m_bIQxt); + mw->m_bIQxt=checked; + ui.mult570TxSpinBox->setEnabled(mw->m_bIQxt); + ui.label_25->setEnabled(mw->m_bIQxt); + ui.sbTxOffset->setEnabled(mw->m_bIQxt); + ui.label_26->setEnabled(mw->m_bIQxt); } void DevSetup::on_sbTxOffset_valueChanged(double f) { - m_TxOffset=f; + mw->m_TxOffset=f; } diff --git a/map65/devsetup.h b/map65/devsetup.h index 2b023a28..64acd572 100644 --- a/map65/devsetup.h +++ b/map65/devsetup.h @@ -5,61 +5,31 @@ #include "ui_devsetup.h" #include "commons.h" + +class MainWindow; + class DevSetup : public QDialog { Q_OBJECT public: - DevSetup(QWidget *parent=0); + explicit DevSetup(MainWindow *parent = nullptr); ~DevSetup(); void initDlg(); - qint32 m_idInt; - qint32 m_pttPort; - qint32 m_nDevIn; - qint32 m_nDevOut; - qint32 m_inDevList[100]; - qint32 m_outDevList[100]; - qint32 m_paInDevice; - qint32 m_paOutDevice; - qint32 m_timeout; - qint32 m_dPhi; - qint32 m_fCal; - qint32 m_udpPort; - qint32 m_astroFont; - qint32 m_mult570; - qint32 m_mult570Tx; - qint32 m_dB; - - double m_fAdd; - double m_cal570; - double m_TxOffset; - bool m_xpolx; - bool m_network; - bool m_fs96000; - bool m_xpol; - bool m_IQswap; + qint32 m_inDevList[1024]; + qint32 m_outDevList[1024]; bool m_restartSoundIn; bool m_restartSoundOut; - bool m_initIQplus; - bool m_bIQxt; - - QString m_myCall; - QString m_myGrid; - QString m_saveDir; - QString m_azelDir; - QString m_dxccPfx; - QString m_colors; - QString m_editorCommand; - - QColor m_colorBackground; + bool m_restartRequired; + int m_pendingFs96000; - QString m_otherUrl; //liveCQ - bool m_w3szUrl; //liveCQ - bool m_spot_to_psk_reporter; //PSKReporter +signals: + void sampleRateChanged(int newRate); public slots: - void accept(); + void accept() override; + void done(int r) override; void onButtonClicked(); private slots: @@ -90,8 +60,10 @@ private slots: void on_sb_dB_valueChanged(int n); private: + MainWindow *mw; int r,g,b,r0,g0,b0,r1,g1,b1,r2,g2,b2,r3,g3,b3; Ui::DialogSndCard ui; + int oldSampleRate; }; #endif // DEVSETUP_H diff --git a/map65/devsetup.ui b/map65/devsetup.ui index c15e06f0..fa87164a 100644 --- a/map65/devsetup.ui +++ b/map65/devsetup.ui @@ -7,7 +7,7 @@ <x>0</x> <y>0</y> <width>531</width> - <height>387</height> + <height>419</height> </rect> </property> <property name="sizePolicy"> @@ -137,9 +137,15 @@ </item> <item> <widget class="QComboBox" name="pttComboBox"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Expanding" vsizetype="Fixed"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> <property name="maximumSize"> <size> - <width>60</width> + <width>16777215</width> <height>16777215</height> </size> </property> @@ -151,71 +157,6 @@ <string>None</string> </property> </item> - <item> - <property name="text"> - <string>COM1</string> - </property> - </item> - <item> - <property name="text"> - <string>COM2</string> - </property> - </item> - <item> - <property name="text"> - <string>COM3</string> - </property> - </item> - <item> - <property name="text"> - <string>COM4</string> - </property> - </item> - <item> - <property name="text"> - <string>COM5</string> - </property> - </item> - <item> - <property name="text"> - <string>COM6</string> - </property> - </item> - <item> - <property name="text"> - <string>COM7</string> - </property> - </item> - <item> - <property name="text"> - <string>COM8</string> - </property> - </item> - <item> - <property name="text"> - <string>COM9</string> - </property> - </item> - <item> - <property name="text"> - <string>COM10</string> - </property> - </item> - <item> - <property name="text"> - <string>COM11</string> - </property> - </item> - <item> - <property name="text"> - <string>COM12</string> - </property> - </item> - <item> - <property name="text"> - <string>COM13</string> - </property> - </item> </widget> </item> <item> @@ -227,7 +168,7 @@ <number>32</number> </property> <property name="value"> - <number>20</number> + <number>18</number> </property> </widget> </item> @@ -236,10 +177,10 @@ <item> <spacer name="horizontalSpacer_2"> <property name="orientation"> - <enum>Qt::Horizontal</enum> + <enum>Qt::Orientation::Horizontal</enum> </property> <property name="sizeType"> - <enum>QSizePolicy::Fixed</enum> + <enum>QSizePolicy::Policy::Fixed</enum> </property> <property name="sizeHint" stdset="0"> <size> @@ -306,10 +247,10 @@ <item> <spacer name="verticalSpacer"> <property name="orientation"> - <enum>Qt::Vertical</enum> + <enum>Qt::Orientation::Vertical</enum> </property> <property name="sizeType"> - <enum>QSizePolicy::Fixed</enum> + <enum>QSizePolicy::Policy::Fixed</enum> </property> <property name="sizeHint" stdset="0"> <size> @@ -363,10 +304,10 @@ <item> <spacer name="verticalSpacer_3"> <property name="orientation"> - <enum>Qt::Vertical</enum> + <enum>Qt::Orientation::Vertical</enum> </property> <property name="sizeType"> - <enum>QSizePolicy::Fixed</enum> + <enum>QSizePolicy::Policy::Fixed</enum> </property> <property name="sizeHint" stdset="0"> <size> @@ -383,17 +324,11 @@ <item> <widget class="QGroupBox" name="antennaGroupBox"> <property name="sizePolicy"> - <sizepolicy hsizetype="Preferred" vsizetype="Maximum"> + <sizepolicy hsizetype="Preferred" vsizetype="Preferred"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> - <property name="minimumSize"> - <size> - <width>0</width> - <height>55</height> - </size> - </property> <property name="title"> <string>Antennas:</string> </property> @@ -403,7 +338,7 @@ <item> <spacer name="horizontalSpacer_10"> <property name="orientation"> - <enum>Qt::Horizontal</enum> + <enum>Qt::Orientation::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> @@ -426,10 +361,10 @@ <item> <spacer name="horizontalSpacer_9"> <property name="orientation"> - <enum>Qt::Horizontal</enum> + <enum>Qt::Orientation::Horizontal</enum> </property> <property name="sizeType"> - <enum>QSizePolicy::Fixed</enum> + <enum>QSizePolicy::Policy::Fixed</enum> </property> <property name="sizeHint" stdset="0"> <size> @@ -459,10 +394,10 @@ <item> <spacer name="horizontalSpacer_3"> <property name="orientation"> - <enum>Qt::Horizontal</enum> + <enum>Qt::Orientation::Horizontal</enum> </property> <property name="sizeType"> - <enum>QSizePolicy::Fixed</enum> + <enum>QSizePolicy::Policy::Fixed</enum> </property> <property name="sizeHint" stdset="0"> <size> @@ -507,7 +442,7 @@ <item> <spacer name="horizontalSpacer_4"> <property name="orientation"> - <enum>Qt::Horizontal</enum> + <enum>Qt::Orientation::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> @@ -637,7 +572,7 @@ <item> <spacer name="horizontalSpacer"> <property name="orientation"> - <enum>Qt::Horizontal</enum> + <enum>Qt::Orientation::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> @@ -702,7 +637,7 @@ <item> <spacer name="horizontalSpacer_11"> <property name="orientation"> - <enum>Qt::Horizontal</enum> + <enum>Qt::Orientation::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> @@ -786,10 +721,10 @@ <item> <spacer name="horizontalSpacer_8"> <property name="orientation"> - <enum>Qt::Horizontal</enum> + <enum>Qt::Orientation::Horizontal</enum> </property> <property name="sizeType"> - <enum>QSizePolicy::Fixed</enum> + <enum>QSizePolicy::Policy::Fixed</enum> </property> <property name="sizeHint" stdset="0"> <size> @@ -804,10 +739,10 @@ <item> <spacer name="verticalSpacer_2"> <property name="orientation"> - <enum>Qt::Vertical</enum> + <enum>Qt::Orientation::Vertical</enum> </property> <property name="sizeType"> - <enum>QSizePolicy::Fixed</enum> + <enum>QSizePolicy::Policy::Fixed</enum> </property> <property name="sizeHint" stdset="0"> <size> @@ -847,7 +782,30 @@ <item> <spacer name="horizontalSpacer_5"> <property name="orientation"> - <enum>Qt::Horizontal</enum> + <enum>Qt::Orientation::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>40</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item> + <widget class="QRadioButton" name="rb192000"> + <property name="text"> + <string>192000 Hz</string> + </property> + <property name="checked"> + <bool>true</bool> + </property> + </widget> + </item> + <item> + <spacer name="horizontalSpacer_6"> + <property name="orientation"> + <enum>Qt::Orientation::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> @@ -868,9 +826,9 @@ </widget> </item> <item> - <spacer name="horizontalSpacer_6"> + <spacer name="horizontalSpacer_61"> <property name="orientation"> - <enum>Qt::Horizontal</enum> + <enum>Qt::Orientation::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> @@ -890,7 +848,7 @@ <item> <spacer name="horizontalSpacer_7"> <property name="orientation"> - <enum>Qt::Horizontal</enum> + <enum>Qt::Orientation::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> @@ -977,132 +935,67 @@ <string>Choose colors for Band Map and Messages Windows</string> </property> <property name="alignment"> - <set>Qt::AlignCenter</set> + <set>Qt::AlignmentFlag::AlignCenter</set> </property> </widget> </item> <item> - <layout class="QHBoxLayout" name="horizontalLayout_17"> - <item> - <spacer name="horizontalSpacer_17"> - <property name="orientation"> - <enum>Qt::Horizontal</enum> - </property> - <property name="sizeType"> - <enum>QSizePolicy::Fixed</enum> - </property> - <property name="sizeHint" stdset="0"> - <size> - <width>80</width> - <height>20</height> - </size> - </property> - </spacer> - </item> - <item> + <layout class="QGridLayout" name="colorsGridLayout"> + <item row="0" column="1"> <widget class="QLabel" name="label_20"> <property name="text"> <string>Red</string> </property> - </widget> - </item> - <item> - <spacer name="horizontalSpacer_19"> - <property name="orientation"> - <enum>Qt::Horizontal</enum> - </property> - <property name="sizeType"> - <enum>QSizePolicy::Fixed</enum> - </property> - <property name="sizeHint" stdset="0"> - <size> - <width>31</width> - <height>20</height> - </size> + <property name="alignment"> + <set>Qt::AlignmentFlag::AlignCenter</set> </property> - </spacer> + </widget> </item> - <item> + <item row="0" column="2"> <widget class="QLabel" name="label_21"> <property name="text"> <string>Green</string> </property> - </widget> - </item> - <item> - <spacer name="horizontalSpacer_20"> - <property name="orientation"> - <enum>Qt::Horizontal</enum> - </property> - <property name="sizeType"> - <enum>QSizePolicy::Fixed</enum> - </property> - <property name="sizeHint" stdset="0"> - <size> - <width>34</width> - <height>20</height> - </size> + <property name="alignment"> + <set>Qt::AlignmentFlag::AlignCenter</set> </property> - </spacer> + </widget> </item> - <item> + <item row="0" column="3"> <widget class="QLabel" name="label_22"> <property name="text"> <string>Blue</string> </property> - </widget> - </item> - <item> - <spacer name="horizontalSpacer_18"> - <property name="orientation"> - <enum>Qt::Horizontal</enum> - </property> - <property name="sizeType"> - <enum>QSizePolicy::Fixed</enum> - </property> - <property name="sizeHint" stdset="0"> - <size> - <width>80</width> - <height>20</height> - </size> + <property name="alignment"> + <set>Qt::AlignmentFlag::AlignCenter</set> </property> - </spacer> + </widget> </item> - </layout> - </item> - <item> - <layout class="QHBoxLayout" name="horizontalLayout_11"> - <item> + <item row="1" column="0"> <widget class="QLabel" name="label_15"> - <property name="maximumSize"> - <size> - <width>60</width> - <height>16777215</height> - </size> - </property> <property name="text"> <string>Background</string> </property> <property name="alignment"> - <set>Qt::AlignCenter</set> + <set>Qt::AlignmentFlag::AlignCenter</set> </property> </widget> </item> - <item> + <item row="1" column="1"> <widget class="QSpinBox" name="sbBackgroundRed"> <property name="maximum"> <number>255</number> </property> </widget> </item> - <item> + <item row="1" column="2"> <widget class="QSpinBox" name="sbBackgroundGreen"> <property name="maximum"> <number>255</number> </property> </widget> </item> - <item> + <item row="1" column="3"> <widget class="QSpinBox" name="sbBackgroundBlue"> <property name="maximum"> <number>255</number> @@ -1112,43 +1005,17 @@ </property> </widget> </item> - <item> - <spacer name="horizontalSpacer_14"> - <property name="orientation"> - <enum>Qt::Horizontal</enum> - </property> - <property name="sizeType"> - <enum>QSizePolicy::Fixed</enum> - </property> - <property name="sizeHint" stdset="0"> - <size> - <width>55</width> - <height>20</height> - </size> - </property> - </spacer> - </item> - </layout> - </item> - <item> - <layout class="QHBoxLayout" name="horizontalLayout_12"> - <item> + <item row="2" column="0"> <widget class="QLabel" name="label_16"> - <property name="maximumSize"> - <size> - <width>60</width> - <height>16777215</height> - </size> - </property> <property name="text"> <string>Newest</string> </property> <property name="alignment"> - <set>Qt::AlignCenter</set> + <set>Qt::AlignmentFlag::AlignCenter</set> </property> </widget> </item> - <item> + <item row="2" column="1"> <widget class="QSpinBox" name="sbRed0"> <property name="maximum"> <number>255</number> @@ -1158,34 +1025,28 @@ </property> </widget> </item> - <item> + <item row="2" column="2"> <widget class="QSpinBox" name="sbGreen0"> <property name="maximum"> <number>255</number> </property> </widget> </item> - <item> + <item row="2" column="3"> <widget class="QSpinBox" name="sbBlue0"> <property name="maximum"> <number>255</number> </property> </widget> </item> - <item> + <item row="2" column="4"> <widget class="QLabel" name="lab0"> <property name="sizePolicy"> - <sizepolicy hsizetype="Fixed" vsizetype="Preferred"> + <sizepolicy hsizetype="Preferred" vsizetype="Preferred"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> - <property name="maximumSize"> - <size> - <width>50</width> - <height>16777215</height> - </size> - </property> <property name="font"> <font> <family>Courier New</family> @@ -1197,27 +1058,17 @@ </property> </widget> </item> - </layout> - </item> - <item> - <layout class="QHBoxLayout" name="horizontalLayout_13"> - <item> + <item row="3" column="0"> <widget class="QLabel" name="label_17"> - <property name="maximumSize"> - <size> - <width>60</width> - <height>16777215</height> - </size> - </property> <property name="text"> <string>2nd</string> </property> <property name="alignment"> - <set>Qt::AlignCenter</set> + <set>Qt::AlignmentFlag::AlignCenter</set> </property> </widget> </item> - <item> + <item row="3" column="1"> <widget class="QSpinBox" name="sbRed1"> <property name="maximum"> <number>255</number> @@ -1227,7 +1078,7 @@ </property> </widget> </item> - <item> + <item row="3" column="2"> <widget class="QSpinBox" name="sbGreen1"> <property name="maximum"> <number>255</number> @@ -1237,27 +1088,21 @@ </property> </widget> </item> - <item> + <item row="3" column="3"> <widget class="QSpinBox" name="sbBlue1"> <property name="maximum"> <number>255</number> </property> </widget> </item> - <item> + <item row="3" column="4"> <widget class="QLabel" name="lab1"> <property name="sizePolicy"> - <sizepolicy hsizetype="Fixed" vsizetype="Preferred"> + <sizepolicy hsizetype="Preferred" vsizetype="Preferred"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> - <property name="maximumSize"> - <size> - <width>50</width> - <height>16777215</height> - </size> - </property> <property name="font"> <font> <family>Courier New</family> @@ -1269,27 +1114,17 @@ </property> </widget> </item> - </layout> - </item> - <item> - <layout class="QHBoxLayout" name="horizontalLayout_14"> - <item> + <item row="4" column="0"> <widget class="QLabel" name="label_18"> - <property name="maximumSize"> - <size> - <width>60</width> - <height>16777215</height> - </size> - </property> <property name="text"> <string>3rd</string> </property> <property name="alignment"> - <set>Qt::AlignCenter</set> + <set>Qt::AlignmentFlag::AlignCenter</set> </property> </widget> </item> - <item> + <item row="4" column="1"> <widget class="QSpinBox" name="sbRed2"> <property name="maximum"> <number>255</number> @@ -1299,7 +1134,7 @@ </property> </widget> </item> - <item> + <item row="4" column="2"> <widget class="QSpinBox" name="sbGreen2"> <property name="maximum"> <number>255</number> @@ -1309,7 +1144,7 @@ </property> </widget> </item> - <item> + <item row="4" column="3"> <widget class="QSpinBox" name="sbBlue2"> <property name="maximum"> <number>255</number> @@ -1319,20 +1154,14 @@ </property> </widget> </item> - <item> + <item row="4" column="4"> <widget class="QLabel" name="lab2"> <property name="sizePolicy"> - <sizepolicy hsizetype="Fixed" vsizetype="Preferred"> + <sizepolicy hsizetype="Preferred" vsizetype="Preferred"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> - <property name="maximumSize"> - <size> - <width>50</width> - <height>16777215</height> - </size> - </property> <property name="font"> <font> <family>Courier New</family> @@ -1344,27 +1173,17 @@ </property> </widget> </item> - </layout> - </item> - <item> - <layout class="QHBoxLayout" name="horizontalLayout_15"> - <item> + <item row="5" column="0"> <widget class="QLabel" name="label_19"> - <property name="maximumSize"> - <size> - <width>60</width> - <height>16777215</height> - </size> - </property> <property name="text"> <string>Oldest</string> </property> <property name="alignment"> - <set>Qt::AlignCenter</set> + <set>Qt::AlignmentFlag::AlignCenter</set> </property> </widget> </item> - <item> + <item row="5" column="1"> <widget class="QSpinBox" name="sbRed3"> <property name="maximum"> <number>255</number> @@ -1374,7 +1193,7 @@ </property> </widget> </item> - <item> + <item row="5" column="2"> <widget class="QSpinBox" name="sbGreen3"> <property name="maximum"> <number>255</number> @@ -1384,7 +1203,7 @@ </property> </widget> </item> - <item> + <item row="5" column="3"> <widget class="QSpinBox" name="sbBlue3"> <property name="maximum"> <number>255</number> @@ -1394,20 +1213,14 @@ </property> </widget> </item> - <item> + <item row="5" column="4"> <widget class="QLabel" name="lab3"> <property name="sizePolicy"> - <sizepolicy hsizetype="Fixed" vsizetype="Preferred"> + <sizepolicy hsizetype="Preferred" vsizetype="Preferred"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> - <property name="maximumSize"> - <size> - <width>50</width> - <height>16777215</height> - </size> - </property> <property name="font"> <font> <family>Courier New</family> @@ -1426,7 +1239,7 @@ <item> <spacer name="horizontalSpacer_15"> <property name="orientation"> - <enum>Qt::Horizontal</enum> + <enum>Qt::Orientation::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> @@ -1446,7 +1259,7 @@ <item> <spacer name="horizontalSpacer_16"> <property name="orientation"> - <enum>Qt::Horizontal</enum> + <enum>Qt::Orientation::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> @@ -1503,10 +1316,10 @@ <item row="1" column="0"> <spacer name="verticalSpacer_4"> <property name="orientation"> - <enum>Qt::Vertical</enum> + <enum>Qt::Orientation::Vertical</enum> </property> <property name="sizeType"> - <enum>QSizePolicy::Fixed</enum> + <enum>QSizePolicy::Policy::Fixed</enum> </property> <property name="sizeHint" stdset="0"> <size> @@ -1528,10 +1341,10 @@ <item> <spacer name="horizontalSpacer_12"> <property name="orientation"> - <enum>Qt::Horizontal</enum> + <enum>Qt::Orientation::Horizontal</enum> </property> <property name="sizeType"> - <enum>QSizePolicy::Preferred</enum> + <enum>QSizePolicy::Policy::Preferred</enum> </property> <property name="sizeHint" stdset="0"> <size> @@ -1580,7 +1393,7 @@ <item> <spacer name="horizontalSpacer_22"> <property name="orientation"> - <enum>Qt::Horizontal</enum> + <enum>Qt::Orientation::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> @@ -1632,10 +1445,10 @@ <item> <spacer name="horizontalSpacer_21"> <property name="orientation"> - <enum>Qt::Horizontal</enum> + <enum>Qt::Orientation::Horizontal</enum> </property> <property name="sizeType"> - <enum>QSizePolicy::Preferred</enum> + <enum>QSizePolicy::Policy::Preferred</enum> </property> <property name="sizeHint" stdset="0"> <size> @@ -1681,10 +1494,10 @@ <item> <spacer name="horizontalSpacer_13"> <property name="orientation"> - <enum>Qt::Horizontal</enum> + <enum>Qt::Orientation::Horizontal</enum> </property> <property name="sizeType"> - <enum>QSizePolicy::Preferred</enum> + <enum>QSizePolicy::Policy::Preferred</enum> </property> <property name="sizeHint" stdset="0"> <size> @@ -1724,10 +1537,10 @@ <item row="6" column="0"> <spacer name="verticalSpacer_5"> <property name="orientation"> - <enum>Qt::Vertical</enum> + <enum>Qt::Orientation::Vertical</enum> </property> <property name="sizeType"> - <enum>QSizePolicy::Fixed</enum> + <enum>QSizePolicy::Policy::Fixed</enum> </property> <property name="sizeHint" stdset="0"> <size> @@ -1752,81 +1565,107 @@ <attribute name="title"> <string>LiveCQ</string> </attribute> - <widget class="QGroupBox" name="groupBox_4"> - <property name="geometry"> - <rect> - <x>70</x> - <y>100</y> - <width>361</width> - <height>80</height> - </rect> - </property> - <property name="title"> - <string>LiveCQ URL</string> - </property> - <widget class="QRadioButton" name="otherBut"> - <property name="geometry"> - <rect> - <x>10</x> - <y>50</y> - <width>51</width> - <height>20</height> - </rect> - </property> - <property name="text"> - <string>Other</string> - </property> - </widget> - <widget class="QRadioButton" name="w3szBut"> - <property name="geometry"> - <rect> - <x>10</x> - <y>20</y> - <width>131</width> - <height>20</height> - </rect> - </property> - <property name="text"> - <string>Official QMAP URL</string> - </property> - </widget> - <widget class="QLineEdit" name="otherUrlBox"> - <property name="geometry"> - <rect> - <x>70</x> - <y>50</y> - <width>281</width> - <height>22</height> - </rect> - </property> - <property name="text"> - <string/> - </property> - </widget> - </widget> - <widget class="QCheckBox" name="pskBox"> - <property name="geometry"> - <rect> - <x>80</x> - <y>200</y> - <width>141</width> - <height>20</height> - </rect> - </property> - <property name="text"> - <string>Spot to PSKReporter</string> - </property> - </widget> + <layout class="QGridLayout" name="gridLayout_2"> + <item row="0" column="0"> + <spacer name="verticalSpacer_6"> + <property name="orientation"> + <enum>Qt::Orientation::Vertical</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>20</width> + <height>40</height> + </size> + </property> + </spacer> + </item> + <item row="3" column="0"> + <widget class="QCheckBox" name="pskBox"> + <property name="text"> + <string>Spot to PSKReporter</string> + </property> + </widget> + </item> + <item row="5" column="0"> + <spacer name="verticalSpacer_7"> + <property name="orientation"> + <enum>Qt::Orientation::Vertical</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>20</width> + <height>40</height> + </size> + </property> + </spacer> + </item> + <item row="4" column="0"> + <widget class="QCheckBox" name="pskReporterTcpIpBox"> + <property name="toolTip"> + <string>Transport changes take effect the next time MAP65 starts.</string> + </property> + <property name="text"> + <string>Use TCP for PSK Reporter</string> + </property> + </widget> + </item> + <item row="1" column="0"> + <widget class="QGroupBox" name="LiveCQ_groupBox"> + <property name="title"> + <string>LiveCQ URL</string> + </property> + <layout class="QGridLayout" name="gridLayout_9"> + <item row="1" column="0"> + <widget class="QRadioButton" name="otherBut"> + <property name="text"> + <string>Other</string> + </property> + </widget> + </item> + <item row="1" column="1"> + <widget class="QLineEdit" name="otherUrlBox"> + <property name="text"> + <string/> + </property> + </widget> + </item> + <item row="0" column="0" colspan="2"> + <widget class="QRadioButton" name="w3szBut"> + <property name="text"> + <string>Official QMAP URL</string> + </property> + </widget> + </item> + </layout> + </widget> + </item> + <item row="2" column="0"> + <spacer name="verticalSpacer_8"> + <property name="orientation"> + <enum>Qt::Orientation::Vertical</enum> + </property> + <property name="sizeType"> + <enum>QSizePolicy::Policy::Fixed</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>20</width> + <height>15</height> + </size> + </property> + </spacer> + </item> + </layout> </widget> </widget> </item> <item> <widget class="QDialogButtonBox" name="buttonBox"> <property name="orientation"> - <enum>Qt::Horizontal</enum> + <enum>Qt::Orientation::Horizontal</enum> </property> <property name="standardButtons"> - <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set> + <set>QDialogButtonBox::StandardButton::Cancel|QDialogButtonBox::StandardButton::Ok</set> </property> </widget> </item> diff --git a/map65/fortran_mutex.cpp b/map65/fortran_mutex.cpp new file mode 100644 index 00000000..a04178db --- /dev/null +++ b/map65/fortran_mutex.cpp @@ -0,0 +1,3 @@ +// fortran_mutex.cpp +#include "fortran_mutex.hpp" +std::mutex g_fortran_decode_mutex; diff --git a/map65/fortran_mutex.hpp b/map65/fortran_mutex.hpp new file mode 100644 index 00000000..b5181df1 --- /dev/null +++ b/map65/fortran_mutex.hpp @@ -0,0 +1,5 @@ +// fortran_mutex.hpp +#pragma once +#include <mutex> + +extern std::mutex g_fortran_decode_mutex; diff --git a/map65/getdev.cpp b/map65/getdev.cpp index 45addfa0..b3e55335 100644 --- a/map65/getdev.cpp +++ b/map65/getdev.cpp @@ -51,10 +51,34 @@ int pa_get_device_info (int n, minInputChannels=0; if(n >= Pa_GetDeviceCount() ) return -1; deviceInfo = Pa_GetDeviceInfo(n); - if (deviceInfo->maxInputChannels==0) return -1; - sprintf((char*)(pa_device_name),"%s",deviceInfo->name); - sprintf((char*)(pa_device_hostapi),"%s", - Pa_GetHostApiInfo( deviceInfo->hostApi )->name); + + // CRITICAL SAFETY CHECK: + if (!deviceInfo) { + qDebug() << "Skipping device index" << n << "because it returned a NULL pointer."; + return -1; + } + + if (deviceInfo->maxInputChannels == 0) return -1; + + // CRITICAL SAFETY CHECK: Validate the Host API info + const PaHostApiInfo* apiInfo = Pa_GetHostApiInfo(deviceInfo->hostApi); + if (!apiInfo) { + qDebug() << "Skipping device" << deviceInfo->name << "because its Host API is invalid."; + return -1; + } + + snprintf((char*)pa_device_name, + 128, + "%.127s", + deviceInfo->name); + + // Change this: + // snprintf((char*)pa_device_hostapi, 128, "%.127s", Pa_GetHostApiInfo(deviceInfo->hostApi)->name); + + // To this safe version: + snprintf((char*)pa_device_hostapi, 128, "%.127s", apiInfo->name); + + speed_warning=0; // bypass bug in Juli@ ASIO driver: @@ -83,14 +107,15 @@ int pa_get_device_info (int n, // ************************************************************************ //filter for portaudio Windows hostapi's with non experts. //only allow ASIO or WASAPI or WDM-KS - i = strncmp(Pa_GetHostApiInfo(deviceInfo->hostApi)->name, "ASIO", 4); - if (i==0 ) goto end_filter_hostapi; - i = strncmp(Pa_GetHostApiInfo(deviceInfo->hostApi)->name, - "Windows WASAPI", 14); - if (i==0 ) goto end_filter_hostapi; - i = strncmp(Pa_GetHostApiInfo(deviceInfo->hostApi)->name, - "Windows WDM-KS", 14); - if (i==0 ) goto end_filter_hostapi; +i = strncmp(apiInfo->name, "ASIO", 4); +if (i==0 ) goto end_filter_hostapi; + +i = strncmp(apiInfo->name, "Windows WASAPI", 14); +if (i==0 ) goto end_filter_hostapi; + +i = strncmp(apiInfo->name, "Windows WDM-KS", 14); +if (i==0 ) goto end_filter_hostapi; + speed_warning=1; end_filter_hostapi:; @@ -187,7 +212,7 @@ void paInputDevice(int id, char* hostAPI_DeviceName, int* minChan, int pa_device_min_channels; char p2[256]; char *p,*p1; - static int iret, valid_dev_cnt; + static int iret; iret=pa_get_device_info (id, &pa_device_name, @@ -200,7 +225,6 @@ void paInputDevice(int id, char* hostAPI_DeviceName, int* minChan, &pa_device_min_channels); if (iret >= 0 ) { - valid_dev_cnt++; p1=(char*)""; p=strstr(pa_device_hostapi,"MME"); @@ -214,7 +238,9 @@ void paInputDevice(int id, char* hostAPI_DeviceName, int* minChan, p=strstr(pa_device_hostapi,"WDM-KS"); if(p!=NULL) p1=(char*)"WDM-KS"; - sprintf(p2,"%-8s %-39s",p1,pa_device_name); + snprintf(p2, sizeof(p2), + "%-8s %-39.39s", + p1, pa_device_name); for(i=0; i<50; i++) { hostAPI_DeviceName[i]=p2[i]; if(p2[i]==0) break; diff --git a/map65/getfile.cpp b/map65/getfile.cpp deleted file mode 100644 index 2a47b508..00000000 --- a/map65/getfile.cpp +++ /dev/null @@ -1,108 +0,0 @@ -#include "getfile.h" -#include <QDir> -#include <stdio.h> -#include <stdlib.h> -#include <math.h> - -extern qint16 id[4*60*96000]; - -void getfile(QString fname, bool xpol, int dbDgrd) -{ - int npts=2*56*96000; - if(xpol) npts=2*npts; - -// Degrade S/N by dbDgrd dB -- for tests only!! - float dgrd=0.0; - if(dbDgrd<0) dgrd = 23.0*sqrt(pow(10.0,-0.1*(double)dbDgrd) - 1.0); - float fac=23.0/sqrt(dgrd*dgrd + 23.0*23.0); - - memset(id,0,2*npts); - char name[80]; - strcpy(name,fname.toLocal8Bit()); - FILE* fp=fopen(name,"rb"); - - if(fp != NULL) { - auto n = fread(&datcom_.fcenter,sizeof(datcom_.fcenter),1,fp); - n = fread(id,2,npts,fp); - Q_UNUSED (n); - int j=0; - - if(dbDgrd<0) { - for(int i=0; i<npts; i+=2) { - datcom_.d4[j++]=fac*((float)id[i] + dgrd*gran()); - datcom_.d4[j++]=fac*((float)id[i+1] + dgrd*gran()); - if(!xpol) j+=2; //Skip over d4(3,x) and d4(4,x) - } - } else { - for(int i=0; i<npts; i+=2) { - datcom_.d4[j++]=(float)id[i]; - datcom_.d4[j++]=(float)id[i+1]; - if(!xpol) j+=2; //Skip over d4(3,x) and d4(4,x) - } - } - fclose(fp); - - datcom_.ndiskdat=1; - int nfreq=(int)datcom_.fcenter; -// if(nfreq!=144 and nfreq != 432 and nfreq != 1296) datcom_.fcenter=144.125; - if(nfreq>9998) datcom_.fcenter=9990.100; //get crash if fcenter > 9999 - int i0=fname.indexOf(".tf2"); - if(i0<0) i0=fname.indexOf(".iq"); - datcom_.nutc=0; - if(i0>0) { - datcom_.nutc=100*fname.mid(i0-4,2).toInt() + fname.mid(i0-2,2).toInt(); - } - } -} - -void savetf2(QString fname, bool xpol) -{ - int npts=2*56*96000; - if(xpol) npts=2*npts; - - qint16* buf=(qint16*)malloc(2*npts); - char name[80]; - strcpy(name,fname.toLocal8Bit()); - FILE* fp=fopen(name,"wb"); - - if(fp != NULL) { - fwrite(&datcom_.fcenter,sizeof(datcom_.fcenter),1,fp); - int j=0; - for(int i=0; i<npts; i+=2) { - buf[i]=(qint16)datcom_.d4[j++]; - buf[i+1]=(qint16)datcom_.d4[j++]; - if(!xpol) j+=2; //Skip over d4(3,x) and d4(4,x) - } - fwrite(buf,2,npts,fp); - fclose(fp); - } - free(buf); -} - -//#define MAX_RANDOM 0x7fffffff - -/* Generate gaussian random float with mean=0 and std_dev=1 */ -float gran() -{ - float fac,rsq,v1,v2; - static float gset; - static int iset; - - if(iset){ - /* Already got one */ - iset = 0; - return gset; - } - /* Generate two evenly distributed numbers between -1 and +1 - * that are inside the unit circle - */ - do { - v1 = 2.0 * (float)rand() / RAND_MAX - 1; - v2 = 2.0 * (float)rand() / RAND_MAX - 1; - rsq = v1*v1 + v2*v2; - } while(rsq >= 1.0 || rsq == 0.0); - fac = sqrt(-2.0*log(rsq)/rsq); - gset = v1*fac; - iset++; - return v2*fac; -} diff --git a/map65/getfile.h b/map65/getfile.h deleted file mode 100644 index 796c31e5..00000000 --- a/map65/getfile.h +++ /dev/null @@ -1,12 +0,0 @@ -#ifndef GETFILE_H -#define GETFILE_H -#include <QString> -#include <QFile> -#include <QDebug> -#include "commons.h" - -void getfile(QString fname, bool xpol, int dbDgrd); -void savetf2(QString fname, bool xpol); -float gran(); - -#endif // GETFILE_H diff --git a/map65/globals.h b/map65/globals.h new file mode 100644 index 00000000..c9fa80d8 --- /dev/null +++ b/map65/globals.h @@ -0,0 +1 @@ +extern int g_activeNfft; diff --git a/map65/half_symbol_scheduler.h b/map65/half_symbol_scheduler.h new file mode 100644 index 00000000..b4b1e2b5 --- /dev/null +++ b/map65/half_symbol_scheduler.h @@ -0,0 +1,36 @@ +#ifndef MAP65_HALF_SYMBOL_SCHEDULER_H +#define MAP65_HALF_SYMBOL_SCHEDULER_H + +#include <atomic> + +class Map65HalfSymbolScheduler +{ +public: + void reset () noexcept { scheduled_half_symbol_ = 0; } + + bool claim_next (int available_half_symbol, std::atomic_bool& busy) noexcept + { + if (available_half_symbol <= scheduled_half_symbol_) + { + return false; + } + + bool expected = false; + if (!busy.compare_exchange_strong (expected, true, + std::memory_order_acq_rel, + std::memory_order_acquire)) + { + return false; + } + + ++scheduled_half_symbol_; + return true; + } + + int scheduled_half_symbol () const noexcept { return scheduled_half_symbol_; } + +private: + int scheduled_half_symbol_ {0}; +}; + +#endif diff --git a/map65/killbyname.cpp b/map65/killbyname.cpp deleted file mode 100644 index 11629e65..00000000 --- a/map65/killbyname.cpp +++ /dev/null @@ -1,282 +0,0 @@ -#include <windows.h> -#include <tlhelp32.h> -#include <iostream> - -int killbyname(const char *szToTerminate) -// Created: 6/23/2000 (Ravi Kochhar) -// Last modified: 3/10/2002 (RK) -// Please report any problems or bugs to kochhar@physiology.wisc.edu -// The latest version of this routine can be found at: -// http://www.neurophys.wisc.edu/ravi/software/killproc/ -// Terminate the process "szToTerminate" if it is currently running -// This works for Win/95/98/ME and also Win/NT/2000/XP -// The process name is case-insensitive, i.e. "notepad.exe" and "NOTEPAD.EXE" -// will both work (for szToTerminate) -// Return codes are as follows: -// 0 = Process was successfully terminated -// 602 = Unable to terminate process for some other reason -// 603 = Process was not currently running -// 604 = No permission to terminate process -// 605 = Unable to load PSAPI.DLL -// 606 = Unable to identify system type -// 607 = Unsupported OS -// 632 = Invalid process name -// 700 = Unable to get procedure address from PSAPI.DLL -// 701 = Unable to get process list, EnumProcesses failed -// 702 = Unable to load KERNEL32.DLL -// 703 = Unable to get procedure address from KERNEL32.DLL -// 704 = CreateToolhelp32Snapshot failed - -{ - BOOL bResult,bResultm; - DWORD aiPID[1000],iCb=1000,iNumProc; //,iV2000=0; - DWORD iCbneeded,i,iFound=0; - char szName[MAX_PATH],szToTermUpper[MAX_PATH]; - HANDLE hProc,hSnapShot,hSnapShotm; - OSVERSIONINFO osvi; - HINSTANCE hInstLib; - int iLenP,indx; - HMODULE hMod; - PROCESSENTRY32 procentry; - MODULEENTRY32 modentry; - - // Transfer Process name into "szToTermUpper" and convert to upper case - iLenP=strlen(szToTerminate); - if(iLenP<1 || iLenP>MAX_PATH) return 632; - for(indx=0;indx<iLenP;indx++) - szToTermUpper[indx]=toupper(szToTerminate[indx]); - szToTermUpper[iLenP]=0; - - // PSAPI Function Pointers. - BOOL (WINAPI *lpfEnumProcesses)( DWORD *, DWORD cb, DWORD * ); - BOOL (WINAPI *lpfEnumProcessModules)( HANDLE, HMODULE *, - DWORD, LPDWORD ); - DWORD (WINAPI *lpfGetModuleBaseName)( HANDLE, HMODULE, - LPTSTR, DWORD ); - - // ToolHelp Function Pointers. - HANDLE (WINAPI *lpfCreateToolhelp32Snapshot)(DWORD,DWORD) ; - BOOL (WINAPI *lpfProcess32First)(HANDLE,LPPROCESSENTRY32) ; - BOOL (WINAPI *lpfProcess32Next)(HANDLE,LPPROCESSENTRY32) ; - BOOL (WINAPI *lpfModule32First)(HANDLE,LPMODULEENTRY32) ; - BOOL (WINAPI *lpfModule32Next)(HANDLE,LPMODULEENTRY32) ; - - // First check what version of Windows we're in - osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); - bResult=GetVersionEx(&osvi); - if(!bResult) return 606; // Unable to identify system version - - // At Present we only support Win/NT/2000/XP or Win/9x/ME - // Seems to work OK in Win7 - if((osvi.dwPlatformId != VER_PLATFORM_WIN32_NT) && - (osvi.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS)) return 607; - - if(osvi.dwPlatformId==VER_PLATFORM_WIN32_NT) - { - // Win/NT or 2000 or XP - - // Load library and get the procedures explicitly. We do - // this so that we don't have to worry about modules using - // this code failing to load under Windows 9x, because - // it can't resolve references to the PSAPI.DLL. - hInstLib = LoadLibraryA("PSAPI.DLL"); - if(hInstLib == NULL) return 605; - - // Get procedure addresses. - lpfEnumProcesses = (BOOL(WINAPI *)(DWORD *,DWORD,DWORD*))(void (*)()) - GetProcAddress( hInstLib, "EnumProcesses" ) ; - lpfEnumProcessModules = (BOOL(WINAPI *)(HANDLE, HMODULE *, - DWORD, LPDWORD))(void (*)()) GetProcAddress( hInstLib, "EnumProcessModules" ) ; - lpfGetModuleBaseName =(DWORD (WINAPI *)(HANDLE, HMODULE, LPTSTR, - DWORD )) (void (*)())GetProcAddress( hInstLib, "GetModuleBaseNameA" ) ; - - if(lpfEnumProcesses == NULL || lpfEnumProcessModules == NULL || - lpfGetModuleBaseName == NULL) { - FreeLibrary(hInstLib); - return 700; - } - - bResult=lpfEnumProcesses(aiPID,iCb,&iCbneeded); - if(!bResult) { - // Unable to get process list, EnumProcesses failed - FreeLibrary(hInstLib); - return 701; - } - - // How many processes are there? - iNumProc=iCbneeded/sizeof(DWORD); - - // Get and match the name of each process - for(i=0;i<iNumProc;i++) { - // Get the (module) name for this process - strcpy(szName,"Unknown"); - // First, get a handle to the process - hProc=OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ,FALSE, - aiPID[i]); - // Now, get the process name - if(hProc) { - if(lpfEnumProcessModules(hProc,&hMod,sizeof(hMod),&iCbneeded) ) { - lpfGetModuleBaseName(hProc,hMod,szName,MAX_PATH); - } - } - CloseHandle(hProc); - // We will match regardless of lower or upper case - if(strcmp(_strupr(szName),szToTermUpper)==0) { - // Process found, now terminate it - iFound=1; - // First open for termination - hProc=OpenProcess(PROCESS_TERMINATE,FALSE,aiPID[i]); - if(hProc) { - if(TerminateProcess(hProc,0)) { - // process terminated - CloseHandle(hProc); - FreeLibrary(hInstLib); - return 0; - } else { - // Unable to terminate process - CloseHandle(hProc); - FreeLibrary(hInstLib); - return 602; - } - } else { - // Unable to open process for termination - FreeLibrary(hInstLib); - return 604; - } - } - } - } - - if(osvi.dwPlatformId==VER_PLATFORM_WIN32_WINDOWS) - { - // Win/95 or 98 or ME - - hInstLib = LoadLibraryA("Kernel32.DLL"); - if( hInstLib == NULL ) - return 702; - - // Get procedure addresses. - // We are linking to these functions of Kernel32 - // explicitly, because otherwise a module using - // this code would fail to load under Windows NT, - // which does not have the Toolhelp32 - // functions in the Kernel 32. - lpfCreateToolhelp32Snapshot= - (HANDLE(WINAPI *)(DWORD,DWORD))(void (*)()) - GetProcAddress( hInstLib, - "CreateToolhelp32Snapshot" ) ; - lpfProcess32First= - (BOOL(WINAPI *)(HANDLE,LPPROCESSENTRY32))(void (*)()) - GetProcAddress( hInstLib, "Process32First" ) ; - lpfProcess32Next= - (BOOL(WINAPI *)(HANDLE,LPPROCESSENTRY32))(void (*)()) - GetProcAddress( hInstLib, "Process32Next" ) ; - lpfModule32First= - (BOOL(WINAPI *)(HANDLE,LPMODULEENTRY32))(void (*)()) - GetProcAddress( hInstLib, "Module32First" ) ; - lpfModule32Next= - (BOOL(WINAPI *)(HANDLE,LPMODULEENTRY32))(void (*)()) - GetProcAddress( hInstLib, "Module32Next" ) ; - if( lpfProcess32Next == NULL || - lpfProcess32First == NULL || - lpfModule32Next == NULL || - lpfModule32First == NULL || - lpfCreateToolhelp32Snapshot == NULL ) - { - FreeLibrary(hInstLib); - return 703; - } - - // The Process32.. and Module32.. routines return names in all uppercase - - // Get a handle to a Toolhelp snapshot of all the systems processes. - - hSnapShot = lpfCreateToolhelp32Snapshot( - TH32CS_SNAPPROCESS, 0 ) ; - if( hSnapShot == INVALID_HANDLE_VALUE ) - { - FreeLibrary(hInstLib); - return 704; - } - - // Get the first process' information. - procentry.dwSize = sizeof(PROCESSENTRY32); - bResult=lpfProcess32First(hSnapShot,&procentry); - - // While there are processes, keep looping and checking. - while(bResult) - { - // Get a handle to a Toolhelp snapshot of this process. - hSnapShotm = lpfCreateToolhelp32Snapshot( - TH32CS_SNAPMODULE, procentry.th32ProcessID) ; - if( hSnapShotm == INVALID_HANDLE_VALUE ) - { - CloseHandle(hSnapShot); - FreeLibrary(hInstLib); - return 704; - } - // Get the module list for this process - modentry.dwSize=sizeof(MODULEENTRY32); - bResultm=lpfModule32First(hSnapShotm,&modentry); - - // While there are modules, keep looping and checking - while(bResultm) - { - if(strcmp(modentry.szModule,szToTermUpper)==0) - { - // Process found, now terminate it - iFound=1; - // First open for termination - hProc=OpenProcess(PROCESS_TERMINATE,FALSE,procentry.th32ProcessID); - if(hProc) - { - if(TerminateProcess(hProc,0)) - { - // process terminated - CloseHandle(hSnapShotm); - CloseHandle(hSnapShot); - CloseHandle(hProc); - FreeLibrary(hInstLib); - return 0; - } - else - { - // Unable to terminate process - CloseHandle(hSnapShotm); - CloseHandle(hSnapShot); - CloseHandle(hProc); - FreeLibrary(hInstLib); - return 602; - } - } - else - { - // Unable to open process for termination - CloseHandle(hSnapShotm); - CloseHandle(hSnapShot); - FreeLibrary(hInstLib); - return 604; - } - } - else - { // Look for next modules for this process - modentry.dwSize=sizeof(MODULEENTRY32); - bResultm=lpfModule32Next(hSnapShotm,&modentry); - } - } - - //Keep looking - CloseHandle(hSnapShotm); - procentry.dwSize = sizeof(PROCESSENTRY32); - bResult = lpfProcess32Next(hSnapShot,&procentry); - } - CloseHandle(hSnapShot); - } - if(iFound==0) - { - FreeLibrary(hInstLib); - return 603; - } - FreeLibrary(hInstLib); - return 0; -} diff --git a/map65/libm65/CMakeLists.txt b/map65/libm65/CMakeLists.txt index fe5ee170..c0361b44 100644 --- a/map65/libm65/CMakeLists.txt +++ b/map65/libm65/CMakeLists.txt @@ -1,14 +1,28 @@ set (libm65_FSRCS # Modules come first: + cacb_mod.f90 + datcom_ptrs_mod.f90 + decodes_mod.f90 + extract_shared_mod.f90 + gran_interface.f90 + m65_mod.f90 + map65_polarization_score.f90 + four2a_legacy_wrap.f90 + npar_ptrs_mod.f90 + pfx_mod.f90 + pr_mod.f90 + rs_mod.f90 + stdout_channel_mod.f90 wideband_sync.f90 + fftw3_f77_interfaces.f90 + sec0_mod.f90 + ftrsd2_mod.f90 # Non-module Fortran routines: afc65b.f90 astro.f90 astro0.f90 astrosub.f90 - averms.f90 - badmsg.f90 ccf2.f90 ccf65.f90 cgen65.f90 @@ -16,6 +30,7 @@ set (libm65_FSRCS chkmsg.f90 coord.f90 dcoord.f90 + debug_log.f90 decode0.f90 decode1a.f90 decode65b.f90 @@ -29,13 +44,14 @@ set (libm65_FSRCS extract.f90 fchisq.f90 fchisq0.f90 + fftw3.f90 fil6521.f90 filbig.f90 fmtmsg.f90 four2a.f90 ftninit.f90 ftnquit.f90 - q65b.f90 + q65b.F90 gen65.f90 gen_q65_cwave.f90 gen_q65_wave.f90 @@ -51,19 +67,22 @@ set (libm65_FSRCS interleave63.f90 iqcal.f90 iqfix.f90 - jt65code.f90 k2grid.f90 lorentzian.f90 + m65a.f90 map65a.f90 moon2.f90 moondop.f90 nchar.f90 noisegen.f90 packjt.f90 + pctile.f90 + pfx.f90 pfxdump.f90 polfit.f90 recvpkt.f90 rfile3a.f90 + run_m65.f90 s3avg.f90 sec_midn.f90 set.f90 @@ -94,6 +113,7 @@ set (libm65_ka9q_CSRCS set_source_files_properties (${libm65_ka9q_CSRCS} PROPERTIES COMPILE_FLAGS -Wno-sign-compare) set (libm65_CSRCS + decode_request_mutex.cpp ${libm65_ka9q_CSRCS} ftrsd2.c # gran.c @@ -103,18 +123,44 @@ set (libm65_CSRCS wrapkarn.c ) +# Platform-specific sources if (WIN32) - set (libm65_CSRCS ${libm65_CSRCS} ptt.c) + list(APPEND libm65_CSRCS + ptt.c + win_event_shim.c + stdout_shared_memory.cpp + ) else () - set (libm65_CSRCS ${libm65_CSRCS} ptt_unix.c) + list(APPEND libm65_CSRCS + ptt_unix.c + posix_event_shim.c + stdout_shared_memory.cpp + ) endif () -set (libm65_CXXSRCS - ipcomm.cpp - ) +if (APPLE) + # Keep Apple's framework include flags out of m65impl's Fortran sources. + list (REMOVE_ITEM libm65_CSRCS stdout_shared_memory.cpp) + add_library (m65_qt STATIC stdout_shared_memory.cpp) + target_link_libraries (m65_qt PRIVATE Qt5::Core) +endif () + +#set (libm65_CXXSRCS +# ipcomm.cpp +# ) add_definitions (-DBIGSYM=1) set_source_files_properties (sec_midn.f90 PROPERTIES COMPILE_FLAGS -fno-second-underscore) +# pol is genuine C-supplied state (bind(C, name='run_m65_'), called from +# MAP65's audio callback) that the current implementation doesn't happen +# to reference; removing it would mean touching the C++ caller too, so we +# suppress the warning instead. +set_source_files_properties (run_m65.f90 PROPERTIES COMPILE_FLAGS "-Wno-unused-dummy-argument") +if(Qt6_FOUND) + set_source_files_properties(m65a.f90 PROPERTIES COMPILE_FLAGS "-Wno-aliasing -fallow-argument-mismatch") +else() + set_source_files_properties(m65a.f90 PROPERTIES COMPILE_FLAGS "-Wno-aliasing") +endif() set (libm65_C_and_CXXSRCS ${libm65_CSRCS} @@ -128,20 +174,169 @@ set_property (SOURCE ${libm65_C_and_CXXSRCS} APPEND PROPERTY OBJECT_DEPENDS ${CM # build our targets # add_library (m65impl STATIC ${libm65_FSRCS} ${libm65_CSRCS} ${libm65_CXXSRCS}) -target_link_libraries (m65impl wsjt_fort wsjt_cxx Qt5::Core) -add_executable (m65 m65.f90 m65a.f90) -target_link_libraries (m65 m65impl ${FFTW3_LIBRARIES}) +target_compile_options(m65impl PRIVATE + $<$<COMPILE_LANGUAGE:Fortran>: + # -fcheck=bounds + # -fcheck=all + # -frecursive + -fbacktrace + -Wall + -Wmaybe-uninitialized + # -finit-real=snan # added for modernization testing + # -finit-integer=-999999 # added for modernization testing + > +) + +set_source_files_properties(stdout_channel_mod.f90 PROPERTIES + Fortran_PREPROCESS ON +) + +# MAP65 uses OpenMP critical regions to protect shared FFTW planning state, +# independently of which common Fortran library variant it consumes. +if (NOT TARGET wsjt_fortran_openmp) + message (FATAL_ERROR "MAP65 requires Fortran OpenMP support") +endif () +if (NOT APPLE) + target_link_libraries (m65impl PUBLIC Qt5::Core) +endif () +if (CMAKE_SYSTEM_NAME STREQUAL "Linux") + target_link_libraries (m65impl PRIVATE rt) +endif () +target_link_libraries (m65impl PRIVATE wsjt_fortran_openmp) +wsjt_link_common_fortran (m65impl) + +if (WSJT_ENABLE_TESTS) + add_subdirectory (${CMAKE_SOURCE_DIR}/tests/unit/map65/decode_history + ${CMAKE_CURRENT_BINARY_DIR}/decode_history) + + add_executable (test_map65_deep_search_cache + ${CMAKE_SOURCE_DIR}/tests/unit/map65/test_map65_deep_search_cache.f90) + target_include_directories (test_map65_deep_search_cache PRIVATE ${CMAKE_CURRENT_BINARY_DIR}) + target_link_libraries (test_map65_deep_search_cache PRIVATE m65impl) + file (MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/deep_search_cache) + add_test (NAME test_map65_deep_search_cache COMMAND test_map65_deep_search_cache) + set_tests_properties (test_map65_deep_search_cache PROPERTIES + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/deep_search_cache TIMEOUT 30) + + add_executable (test_map65_decode_requests + ${CMAKE_SOURCE_DIR}/tests/unit/map65/test_map65_decode_requests.f90) + target_include_directories (test_map65_decode_requests PRIVATE ${CMAKE_CURRENT_BINARY_DIR}) + target_link_libraries (test_map65_decode_requests PRIVATE m65impl) + add_test (NAME test_map65_decode_requests COMMAND test_map65_decode_requests) + + add_executable (test_map65_astro + ${CMAKE_SOURCE_DIR}/tests/unit/map65/test_map65_astro.f90) + target_include_directories (test_map65_astro PRIVATE ${CMAKE_CURRENT_BINARY_DIR}) + target_link_libraries (test_map65_astro PRIVATE m65impl) + add_test (NAME test_map65_astro COMMAND test_map65_astro) + set_tests_properties (test_map65_astro PROPERTIES TIMEOUT 180) + + add_executable (test_map65_jt65_handoff + ${CMAKE_SOURCE_DIR}/tests/unit/jt65/jt65_test_fixture.f90 + ${CMAKE_SOURCE_DIR}/tests/unit/jt65/test_map65_jt65_handoff.f90) + target_include_directories (test_map65_jt65_handoff PRIVATE ${CMAKE_CURRENT_BINARY_DIR}) + target_link_libraries (test_map65_jt65_handoff PRIVATE m65impl jt65_test_vectors) + add_test (NAME test_map65_jt65_handoff COMMAND test_map65_jt65_handoff) + set_tests_properties (test_map65_jt65_handoff PROPERTIES TIMEOUT 180) + + add_executable (test_q65_waveform_generator + ${CMAKE_SOURCE_DIR}/tests/unit/q65/test_q65_waveform_generator.f90) + target_include_directories (test_q65_waveform_generator PRIVATE ${CMAKE_CURRENT_BINARY_DIR}) + target_link_libraries (test_q65_waveform_generator PRIVATE m65impl) + add_test (NAME test_q65_waveform_generator COMMAND test_q65_waveform_generator) + set_tests_properties (test_q65_waveform_generator PROPERTIES TIMEOUT 180) + + add_executable (test_map65_wideband_sync_rows + ${CMAKE_SOURCE_DIR}/tests/unit/q65/test_map65_wideband_sync_rows.f90) + target_include_directories (test_map65_wideband_sync_rows PRIVATE ${CMAKE_CURRENT_BINARY_DIR}) + target_link_libraries (test_map65_wideband_sync_rows PRIVATE m65impl) + add_test (NAME test_map65_wideband_sync_rows COMMAND test_map65_wideband_sync_rows) + set_tests_properties (test_map65_wideband_sync_rows PROPERTIES TIMEOUT 180) + + add_executable (test_map65_polarization_score + ${CMAKE_SOURCE_DIR}/tests/unit/q65/test_map65_polarization_score.f90) + target_include_directories (test_map65_polarization_score PRIVATE ${CMAKE_CURRENT_BINARY_DIR}) + target_link_libraries (test_map65_polarization_score PRIVATE m65impl) + add_test (NAME test_map65_polarization_score COMMAND test_map65_polarization_score) + + add_executable (test_ccf65_correlator + ${CMAKE_SOURCE_DIR}/tests/unit/jt65/test_ccf65_correlator.f90) + target_include_directories (test_ccf65_correlator PRIVATE ${CMAKE_CURRENT_BINARY_DIR}) + target_link_libraries (test_ccf65_correlator PRIVATE m65impl) + add_test (NAME test_ccf65_correlator COMMAND test_ccf65_correlator) + set_tests_properties (test_ccf65_correlator PROPERTIES TIMEOUT 180) + + add_executable (test_map65_s3avg_contracts + ${CMAKE_SOURCE_DIR}/tests/unit/jt65/test_map65_s3avg_contracts.f90) + target_include_directories (test_map65_s3avg_contracts PRIVATE ${CMAKE_CURRENT_BINARY_DIR}) + target_link_libraries (test_map65_s3avg_contracts PRIVATE m65impl) + add_test (NAME test_map65_s3avg_contracts COMMAND test_map65_s3avg_contracts) + set_tests_properties (test_map65_s3avg_contracts PROPERTIES TIMEOUT 180) + + add_executable (test_map65_jt65_message_validity + ${CMAKE_SOURCE_DIR}/tests/unit/jt65/test_map65_jt65_message_validity.f90) + target_include_directories (test_map65_jt65_message_validity PRIVATE ${CMAKE_CURRENT_BINARY_DIR}) + target_link_libraries (test_map65_jt65_message_validity PRIVATE m65impl) + add_test (NAME test_map65_jt65_message_validity COMMAND test_map65_jt65_message_validity) + set_tests_properties (test_map65_jt65_message_validity PROPERTIES TIMEOUT 180) + + add_executable (test_map65_jt65_candidate_consistency + ${CMAKE_SOURCE_DIR}/tests/unit/jt65/test_map65_jt65_candidate_consistency.f90) + target_include_directories (test_map65_jt65_candidate_consistency PRIVATE ${CMAKE_CURRENT_BINARY_DIR}) + target_link_libraries (test_map65_jt65_candidate_consistency PRIVATE m65impl) + add_test (NAME test_map65_jt65_candidate_consistency COMMAND test_map65_jt65_candidate_consistency) + set_tests_properties (test_map65_jt65_candidate_consistency PROPERTIES TIMEOUT 180) + + add_executable (test_map65_result_selection + ${CMAKE_SOURCE_DIR}/tests/unit/map65/test_map65_result_selection.f90) + target_include_directories (test_map65_result_selection PRIVATE ${CMAKE_CURRENT_BINARY_DIR}) + target_link_libraries (test_map65_result_selection PRIVATE m65impl) + add_test (NAME test_map65_result_selection COMMAND test_map65_result_selection) + set_tests_properties (test_map65_result_selection PROPERTIES TIMEOUT 180) + + add_executable (test_map65_q65b_timeout + ${CMAKE_SOURCE_DIR}/tests/unit/map65/test_map65_q65b_timeout.f90) + target_include_directories (test_map65_q65b_timeout PRIVATE ${CMAKE_CURRENT_BINARY_DIR}) + target_link_libraries (test_map65_q65b_timeout PRIVATE m65impl) + add_test (NAME test_map65_q65b_timeout COMMAND test_map65_q65b_timeout) + set_tests_properties (test_map65_q65b_timeout PROPERTIES TIMEOUT 180) + + add_executable (test_map65_q65_dphi + ${CMAKE_SOURCE_DIR}/tests/unit/map65/test_map65_q65_dphi.f90) + target_include_directories (test_map65_q65_dphi PRIVATE ${CMAKE_CURRENT_BINARY_DIR}) + target_link_libraries (test_map65_q65_dphi PRIVATE m65impl) + file (MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/test-map65-q65-dphi) + add_test (NAME test_map65_q65_dphi COMMAND test_map65_q65_dphi) + set_tests_properties (test_map65_q65_dphi PROPERTIES + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/test-map65-q65-dphi + ENVIRONMENT "OMP_NUM_THREADS=1" + RUN_SERIAL TRUE + TIMEOUT 180) + +endif () + +if (WIN32 AND CMAKE_SIZEOF_VOID_P EQUAL 4) + target_compile_definitions(m65impl PRIVATE _WIN32) +elseif (WIN32 AND CMAKE_SIZEOF_VOID_P EQUAL 8) + target_compile_definitions(m65impl PRIVATE _WIN64) +endif() + +if (WIN32) + target_link_libraries(m65impl PUBLIC kernel32) +endif() add_executable (mapsim mapsim.f90) +add_dependencies(mapsim m65impl) target_link_libraries (mapsim m65impl ${FFTW3_LIBRARIES}) +wsjt_add_simulator_usage_test (mapsim "Usage:[ ]+mapsim") #add_executable (synctest synctest.f90) #target_link_libraries (synctest m65impl ${FFTW3_LIBRARIES}) if (WIN32) install ( - TARGETS m65 mapsim + TARGETS mapsim RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT runtime BUNDLE DESTINATION . COMPONENT runtime ) diff --git a/map65/libm65/afc65b.f90 b/map65/libm65/afc65b.f90 index 53f61ea4..e0ebfbc0 100644 --- a/map65/libm65/afc65b.f90 +++ b/map65/libm65/afc65b.f90 @@ -1,70 +1,187 @@ +module afc65b_mod + implicit none +contains + subroutine afc65b(cx,cy,npts,fsample,nflip,ipol,xpol,ndphi,a,ccfbest,dtbest) + use fchisq_mod + use, intrinsic :: ieee_arithmetic, only: ieee_is_finite + + implicit none + + integer, parameter :: MAX_STEP_TRIES = 200 + integer, parameter :: MAX_DOWNHILL_STEPS = 200 + real, parameter :: MIN_STEP = 1.0e-4 + real, parameter :: OBJECTIVE_REL_TOL = 1.0e-6 + + logical, intent(in) :: xpol + integer, intent(in) :: npts, nflip, ndphi + integer, intent(inout) :: ipol + complex, intent(in) :: cx(npts), cy(npts) + real, intent(inout) :: a(5) + real :: deltaa(5) + integer :: iter, j, nterms, step, downhill_steps + real, intent(out) :: ccfbest, dtbest + real :: chisq1, chisq2, chisqr, chisqr0 + real :: delta, dtmax + real, intent(in) :: fsample + real :: ccfmax + real :: x0, xlast, xprev, xbest, xnext, candidate + real :: flast, fprev, fbest, fnext, fcandidate, curvature, tolerance + logical :: bracketed, improved, have_previous + + ! Initial parameter guesses + a(1) = 0.0 + a(2) = 0.0 + a(3) = 0.0 + if (ipol < 1 .or. ipol > 4) ipol = 1 + a(4) = 45.0*(ipol - 1.0) + + deltaa(1) = 2.0 + deltaa(2) = 2.0 + deltaa(3) = 2.0 + deltaa(4) = 22.5 + deltaa(5) = 0.05 + + nterms = 3 + if (xpol) nterms = 4 + if (ndphi /= 0) nterms = 3 ! don't fit pol when solving for dphi + + ccfbest = 0.0 + dtbest = 0.0 + chisqr0 = 0.0 + have_previous = .false. + + if (npts < 1 .or. fsample <= 0.0 .or. .not. ieee_is_finite(fsample)) return + + do iter = 1, 3 + do j = 1, nterms + x0 = a(j) + chisq1 = fchisq(cx,cy,npts,fsample,nflip,a,ccfmax,dtmax) + if (.not. ieee_is_finite(chisq1)) then + a(j) = x0 + cycle + endif + + delta = abs(deltaa(j)) + if (.not. ieee_is_finite(delta) .or. delta < MIN_STEP) delta = MIN_STEP + improved = .false. + xlast = x0 + flast = chisq1 + xnext = xlast - logical xpol - complex cx(npts) - complex cy(npts) - real a(5),deltaa(5) - - a(1)=0. - a(2)=0. - a(3)=0. - a(4)=45.0*(ipol-1.0) - deltaa(1)=2.0 - deltaa(2)=2.0 - deltaa(3)=2.0 - deltaa(4)=22.5 - deltaa(5)=0.05 - nterms=3 - if(xpol) nterms=4 - -! Don't fit polarization when solving for dphi - if(ndphi.ne.0) nterms=3 - -! Start the iteration - chisqr=0. - chisqr0=1.e6 - do iter=1,3 !One iteration is enough? - do j=1,nterms - chisq1=fchisq(cx,cy,npts,fsample,nflip,a,ccfmax,dtmax) - fn=0. - delta=deltaa(j) -10 a(j)=a(j)+delta - chisq2=fchisq(cx,cy,npts,fsample,nflip,a,ccfmax,dtmax) - if(chisq2.eq.chisq1) go to 10 - if(chisq2.gt.chisq1) then - delta=-delta !Reverse direction - a(j)=a(j)+delta - tmp=chisq1 - chisq1=chisq2 - chisq2=tmp + do step = 1, MAX_STEP_TRIES + xnext = xlast + delta + a(j) = xnext + chisq2 = fchisq(cx,cy,npts,fsample,nflip,a,ccfmax,dtmax) + if (.not. ieee_is_finite(chisq2)) exit + tolerance = OBJECTIVE_REL_TOL * max(1.0, abs(chisq1), abs(chisq2)) + if (abs(chisq2 - chisq1) > tolerance) then + xprev = xlast + fprev = flast + improved = .true. + exit + endif + xlast = xnext + flast = chisq2 + end do + + if (.not. improved) then + a(j) = x0 + deltaa(j) = max(MIN_STEP, 0.5*delta) + cycle + endif + + if (chisq2 > chisq1) then + delta = -delta + xnext = x0 + delta + a(j) = xnext + chisq2 = fchisq(cx,cy,npts,fsample,nflip,a,ccfmax,dtmax) + tolerance = OBJECTIVE_REL_TOL * max(1.0, abs(chisq1), abs(chisq2)) + if (.not. ieee_is_finite(chisq2) .or. chisq2 >= chisq1 - tolerance) then + a(j) = x0 + deltaa(j) = max(MIN_STEP, 0.5*abs(delta)) + cycle + endif + xprev = x0 + fprev = chisq1 endif -20 fn=fn+1.0 - a(j)=a(j)+delta - chisq3=fchisq(cx,cy,npts,fsample,nflip,a,ccfmax,dtmax) - if(chisq3.lt.chisq2) then - chisq1=chisq2 - chisq2=chisq3 - go to 20 + + xbest = xnext + fbest = chisq2 + downhill_steps = 0 + bracketed = .false. + + do step = 1, MAX_DOWNHILL_STEPS + xnext = xbest + delta + a(j) = xnext + fnext = fchisq(cx,cy,npts,fsample,nflip,a,ccfmax,dtmax) + if (.not. ieee_is_finite(fnext)) then + a(j) = xbest + exit + endif + + tolerance = OBJECTIVE_REL_TOL * max(1.0, abs(fbest), abs(fnext)) + if (fnext < fbest - tolerance) then + xprev = xbest + fprev = fbest + xbest = xnext + fbest = fnext + downhill_steps = downhill_steps + 1 + else + a(j) = xbest + bracketed = .true. + exit + endif + end do + + if (bracketed) then + curvature = fprev - 2.0*fbest + fnext + tolerance = OBJECTIVE_REL_TOL * max(1.0, abs(fprev), abs(fbest), abs(fnext)) + if (curvature > tolerance) then + candidate = xbest + 0.5*delta*(fprev - fnext)/curvature + if (ieee_is_finite(candidate) .and. candidate > min(xprev, xnext) .and. & + candidate < max(xprev, xnext)) then + a(j) = candidate + fcandidate = fchisq(cx,cy,npts,fsample,nflip,a,ccfmax,dtmax) + if (ieee_is_finite(fcandidate)) then + tolerance = OBJECTIVE_REL_TOL * max(1.0, abs(fbest), abs(fcandidate)) + if (fcandidate < fbest - tolerance) then + xbest = candidate + fbest = fcandidate + endif + endif + endif + endif endif -! Find minimum of parabola defined by last three points - delta=delta*(1./(1.+(chisq1-chisq2)/(chisq3-chisq2))+0.5) - a(j)=a(j)-delta - deltaa(j)=deltaa(j)*fn/3. + a(j) = xbest + if (downhill_steps < 3) then + deltaa(j) = max(MIN_STEP, abs(delta)*max(1, downhill_steps)/3.0) + else + deltaa(j) = abs(delta) + endif enddo - chisqr=fchisq(cx,cy,npts,fsample,nflip,a,ccfmax,dtmax) - if(chisqr/chisqr0.gt.0.9999) go to 30 - chisqr0=chisqr + + chisqr = fchisq(cx,cy,npts,fsample,nflip,a,ccfmax,dtmax) + if (.not. ieee_is_finite(chisqr)) exit + if (have_previous) then + tolerance = OBJECTIVE_REL_TOL * max(1.0, abs(chisqr), abs(chisqr0)) + if (abs(chisqr - chisqr0) <= tolerance) exit + endif + chisqr0 = chisqr + have_previous = .true. enddo -30 ccfbest=ccfmax * (1378.125/fsample)**2 - dtbest=dtmax + if (ieee_is_finite(ccfmax)) ccfbest = max(0.0, ccfmax * (1378.125/fsample)**2) + if (ieee_is_finite(dtmax)) dtbest = dtmax + if (.not. ieee_is_finite(ccfbest)) ccfbest = 0.0 + if (.not. ieee_is_finite(dtbest)) dtbest = 0.0 - if(a(4).lt.0.0) a(4)=a(4)+180.0 - if(a(4).ge.180.0) a(4)=a(4)-180.0 - if(nint(a(4)).eq.180) a(4)=0. - ipol=nint(a(4)/45.0) + 1 - if(ipol.gt.4) ipol=ipol-4 + if (.not. ieee_is_finite(a(4))) a(4) = 0.0 + a(4) = modulo(a(4), 180.0) - return + ipol = modulo(nint(a(4)/45.0), 4) + 1 + end subroutine afc65b + +end module afc65b_mod diff --git a/map65/libm65/astro.f90 b/map65/libm65/astro.f90 index d34819cc..9ec92045 100644 --- a/map65/libm65/astro.f90 +++ b/map65/libm65/astro.f90 @@ -1,105 +1,147 @@ -subroutine astro(nyear,month,nday,uth,nfreq,Mygrid,NStation,MoonDX, & - AzSun,ElSun,AzMoon0,ElMoon0,ntsky,doppler00,doppler,dbMoon,RAMoon, & - DecMoon,HA,Dgrd,sd,poloffset,xnr,day,lon,lat,LST) - -! Computes astronomical quantities for display and tracking. -! NB: may want to smooth the Tsky map to 10 degrees or so. - - character*6 MyGrid,HisGrid - real LST - real lat,lon - integer*2 nt144(180) - -! common/echo/xdop(2),techo,AzMoon,ElMoon,mjd - real xdop(2) - - data rad/57.2957795/ - data nt144/ & - 234, 246, 257, 267, 275, 280, 283, 286, 291, 298, & - 305, 313, 322, 331, 341, 351, 361, 369, 376, 381, & - 383, 382, 379, 374, 370, 366, 363, 361, 363, 368, & - 376, 388, 401, 415, 428, 440, 453, 467, 487, 512, & - 544, 579, 607, 618, 609, 588, 563, 539, 512, 482, & - 450, 422, 398, 379, 363, 349, 334, 319, 302, 282, & - 262, 242, 226, 213, 205, 200, 198, 197, 196, 197, & - 200, 202, 204, 205, 204, 203, 202, 201, 203, 206, & - 212, 218, 223, 227, 231, 236, 240, 243, 247, 257, & - 276, 301, 324, 339, 346, 344, 339, 331, 323, 316, & - 312, 310, 312, 317, 327, 341, 358, 375, 392, 407, & - 422, 437, 451, 466, 480, 494, 511, 530, 552, 579, & - 612, 653, 702, 768, 863,1008,1232,1557,1966,2385, & - 2719,2924,3018,3038,2986,2836,2570,2213,1823,1461, & - 1163, 939, 783, 677, 602, 543, 494, 452, 419, 392, & - 373, 360, 353, 350, 350, 350, 350, 350, 350, 348, & - 344, 337, 329, 319, 307, 295, 284, 276, 272, 272, & - 273, 274, 274, 271, 266, 260, 252, 245, 238, 231/ - save - - call grid2deg(MyGrid,elon,lat) - lon=-elon - call sun(nyear,month,nday,uth,lon,lat,RASun,DecSun,LST,AzSun,ElSun,mjd,day) - - freq=nfreq*1.e6 - if(nfreq.eq.2) freq=1.8e6 - if(nfreq.eq.4) freq=3.5e6 - - call MoonDop(nyear,month,nday,uth,lon,lat,RAMoon,DecMoon,LST,HA, & - AzMoon,ElMoon,vr,dist) - -! Compute spatial polarization offset - xx=sin(lat/rad)*cos(ElMoon/rad) - cos(lat/rad)*cos(AzMoon/rad)*sin(ElMoon/rad) - yy=cos(lat/rad)*sin(AzMoon/rad) - if(NStation.eq.1) poloffset1=rad*atan2(yy,xx) - if(NStation.eq.2) poloffset2=rad*atan2(yy,xx) - - techo=2.0 * dist/2.99792458e5 !Echo delay time - doppler=-freq*vr/2.99792458e5 !One-way Doppler - - call coord(0.,0.,-1.570796,1.161639,RAMoon/rad,DecMoon/rad,el,eb) - longecl_half=nint(rad*el/2.0) - if(longecl_half.lt.1 .or. longecl_half.gt.180) longecl_half=180 - t144=nt144(longecl_half) - tsky=(t144-2.7)*(144.0/nfreq)**2.6 + 2.7 !Tsky for obs freq - - xdop(NStation)=doppler - if(NStation.eq.2) then - HisGrid=MyGrid - go to 900 - endif - - doppler00=2.0*xdop(1) - doppler=xdop(1)+xdop(2) -! if(mode.eq.3) doppler=2.0*xdop(1) - dBMoon=-40.0*log10(dist/356903.) - sd=16.23*370152.0/dist - -! if(NStation.eq.1 .and. MoonDX.ne.0 .and. -! + (mode.eq.2 .or. mode.eq.5)) then - if(NStation.eq.1 .and. MoonDX.ne.0) then - poloffset=mod(poloffset2-poloffset1+720.0,180.0) - if(poloffset.gt.90.0) poloffset=poloffset-180.0 - x1=abs(cos(2*poloffset/rad)) - if(x1.lt.0.056234) x1=0.056234 - xnr=-20.0*log10(x1) - if(HisGrid(1:1).lt.'A' .or. HisGrid(1:1).gt.'R') xnr=0 - endif - - tr=80.0 !Good preamp - tskymin=13.0*(408.0/nfreq)**2.6 !Cold sky temperature - tsysmin=tskymin+tr - tsys=tsky+tr - dgrd=-10.0*log10(tsys/tsysmin) + dbMoon -900 AzMoon0=Azmoon - ElMoon0=Elmoon - ntsky=nint(tsky) - -! auxHA = 15.0*(LST-auxra) !HA in degrees -! pi=3.14159265 -! pio2=0.5*pi -! call coord(pi,pio2-lat/rad,0.0,lat/rad,auxha*pi/180.0, -! + auxdec/rad,azaux,elaux) -! AzAux=azaux*rad -! ElAux=ElAux*rad - - return -end subroutine astro +module astro_mod + use iso_fortran_env, only: real64, real32, int16 + implicit none + + ! Sky temperature lookup table (was integer*2 nt144 + DATA + SAVE) + integer(int16), parameter :: nt144(180) = [ & + 234, 246, 257, 267, 275, 280, 283, 286, 291, 298, & + 305, 313, 322, 331, 341, 351, 361, 369, 376, 381, & + 383, 382, 379, 374, 370, 366, 363, 361, 363, 368, & + 376, 388, 401, 415, 428, 440, 453, 467, 487, 512, & + 544, 579, 607, 618, 609, 588, 563, 539, 512, 482, & + 450, 422, 398, 379, 363, 349, 334, 319, 302, 282, & + 262, 242, 226, 213, 205, 200, 198, 197, 196, 197, & + 200, 202, 204, 205, 204, 203, 202, 201, 203, 206, & + 212, 218, 223, 227, 231, 236, 240, 243, 247, 257, & + 276, 301, 324, 339, 346, 344, 339, 331, 323, 316, & + 312, 310, 312, 317, 327, 341, 358, 375, 392, 407, & + 422, 437, 451, 466, 480, 494, 511, 530, 552, 579, & + 612, 653, 702, 768, 863,1008,1232,1557,1966,2385, & + 2719,2924,3018,3038,2986,2836,2570,2213,1823,1461, & + 1163, 939, 783, 677, 602, 543, 494, 452, 419, 392, & + 373, 360, 353, 350, 350, 350, 350, 350, 350, 348, & + 344, 337, 329, 319, 307, 295, 284, 276, 272, 272, & + 273, 274, 274, 271, 266, 260, 252, 245, 238, 231 ] + + real(real32), parameter :: RAD2DEG = 57.2957795130823 + real(real32), parameter :: C_KM_S = 2.99792458e5 + +contains + + subroutine astro(nyear,month,nday,uth,nfreq,Mygrid,NStation,MoonDX, & + AzSun,ElSun,AzMoon0,ElMoon0,ntsky,doppler00,doppler,dbMoon,RAMoon, & + DecMoon,HA,Dgrd,sd,poloffset,xnr,day,lon,lat,LST) + + use coord_mod + use sun_mod + use moondop_mod + use grid2deg_mod, only: grid2deg + implicit none + + ! Dummy arguments + integer, intent(in) :: nyear, month, nday, nfreq, NStation + real, intent(in) :: uth + real, intent(in) :: MoonDX + character(len=6), intent(in):: MyGrid + integer, intent(out) :: ntsky + real, intent(out) :: AzSun, ElSun, AzMoon0, ElMoon0 + real, intent(out) :: doppler00, doppler, dbMoon + real, intent(out) :: RAMoon, DecMoon, HA, Dgrd, sd + real, intent(out) :: poloffset, xnr + real, intent(out) :: day + real, intent(out) :: lon, lat, LST + + ! Locals + character(len=6) :: HisGrid = 'UNK ' + real(real64) :: freq + real :: RASun, DecSun + real :: AzMoon, ElMoon, vr, dist + real(real64) :: xx, yy, poloffset1 = 0.0, poloffset2 = 0.0 + real(real64) :: techo + real(real32) :: el, eb + integer :: longecl_half, t144 + real(real64) :: tsky, x1, tr, tskymin, tsysmin, tsys + real :: elon + real(real64) :: xdop(2) + integer :: mjd + + ! Initialize intent(out) variables + ntsky = 0 + AzSun = 0.0 + ElSun = 0.0 + AzMoon0 = 0.0 + ElMoon0 = 0.0 + doppler00 = 0.0 + doppler = 0.0 + dbMoon = 0.0 + RAMoon = 0.0 + DecMoon = 0.0 + HA = 0.0 + Dgrd = 0.0 + sd = 0.0 + poloffset = 0.0 + xnr = 0.0 + day = 0.0 + lon = 0.0 + lat = 0.0 + LST = 0.0 + + ! Convert grid to lon/lat + call grid2deg(MyGrid, elon, lat) + lon = -elon + + call sun(nyear,month,nday,uth,lon,lat,RASun,DecSun,LST,AzSun,ElSun,mjd,day) + freq = nfreq*1.0d6 + call MoonDop(nyear,month,nday,uth,lon,lat,RAMoon,DecMoon,LST,HA, & + AzMoon,ElMoon,vr,dist) + + ! Spatial polarization offset + xx = sin(lat/RAD2DEG)*cos(ElMoon/RAD2DEG) - & + cos(lat/RAD2DEG)*cos(AzMoon/RAD2DEG)*sin(ElMoon/RAD2DEG) + yy = cos(lat/RAD2DEG)*sin(AzMoon/RAD2DEG) + if (NStation == 1) poloffset1 = RAD2DEG*atan2(yy,xx) + if (NStation == 2) poloffset2 = RAD2DEG*atan2(yy,xx) + + techo = 2.0 * dist / C_KM_S + doppler = -freq*vr / C_KM_S + + call coord(0.,0.,-1.570796,1.161639, & + RAMoon/RAD2DEG,DecMoon/RAD2DEG,el,eb) + + longecl_half = nint(RAD2DEG*el/2.0) + if (longecl_half < 1 .or. longecl_half > 180) longecl_half = 180 + t144 = nt144(longecl_half) + tsky = (t144-2.7)*(144.0e6/freq)**2.6 + 2.7 + + xdop(NStation) = doppler + if (NStation == 2) then + HisGrid = MyGrid + else + doppler00 = 2.0*xdop(1) + doppler = xdop(1) + xdop(2) + dbMoon = -40.0*log10(dist/356903.0) + sd = 16.23*370152.0/dist + + if (NStation == 1 .and. MoonDX /= 0.0) then + poloffset = mod(poloffset2-poloffset1+720.d0,180.d0) + if (poloffset > 90.0) poloffset = poloffset - 180.0 + x1 = abs(cos(2.0*poloffset/RAD2DEG)) + if (x1 < 0.056234) x1 = 0.056234 + xnr = -20.0*log10(x1) + if (HisGrid(1:1) < 'A' .or. HisGrid(1:1) > 'R') xnr = 0.0 + end if + + tr = 80.0 + tskymin = 13.0*(408.0e6/freq)**2.6 + tsysmin = tskymin + tr + tsys = tsky + tr + Dgrd = -10.0*log10(tsys/tsysmin) + dbMoon + end if + + AzMoon0 = AzMoon + ElMoon0 = ElMoon + ntsky = nint(tsky) + + end subroutine astro + +end module astro_mod diff --git a/map65/libm65/astro0.f90 b/map65/libm65/astro0.f90 index ec234215..f84c8bba 100644 --- a/map65/libm65/astro0.f90 +++ b/map65/libm65/astro0.f90 @@ -1,81 +1,136 @@ -subroutine astro0(nyear,month,nday,uth8,nfreq,mygrid,hisgrid, & - AzSun8,ElSun8,AzMoon8,ElMoon8,AzMoonB8,ElMoonB8,ntsky,ndop,ndop00, & - dbMoon8,RAMoon8,DecMoon8,HA8,Dgrd8,sd8,poloffset8,xnr8,dfdt,dfdt0, & - width1,width2,w501,w502,xlst8) - - parameter (DEGS=57.2957795130823d0) - character*6 mygrid,hisgrid - real*8 AzSun8,ElSun8,AzMoon8,ElMoon8,AzMoonB8,ElMoonB8 - real*8 dbMoon8,RAMoon8,DecMoon8,HA8,Dgrd8,xnr8,dfdt,dfdt0,dt - real*8 sd8,poloffset8,day8,width1,width2,w501,w502,xlst8 - real*8 uth8 - data uth8z/0.d0/ - save - - uth=uth8 - call astro(nyear,month,nday,uth,nfreq,hisgrid,2,1, & - AzSun,ElSun,AzMoon,ElMoon,ntsky,doppler00,doppler, & - dbMoon,RAMoon,DecMoon,HA,Dgrd,sd,poloffset,xnr, & - day,xlon2,xlat2,xlst) - AzMoonB8=AzMoon - ElMoonB8=ElMoon - call astro(nyear,month,nday,uth,nfreq,mygrid,1,1, & - AzSun,ElSun,AzMoon,ElMoon,ntsky,doppler00,doppler, & - dbMoon,RAMoon,DecMoon,HA,Dgrd,sd,poloffset,xnr, & - day,xlon1,xlat1,xlst) - - day8=day - xlst8=xlst - call tm2(day8,xlat1,xlon1,xl1,b1) - call tm2(day8,xlat2,xlon2,xl2,b2) - call tm2(day8+1.d0/1440.0,xlat1,xlon1,xl1a,b1a) - call tm2(day8+1.d0/1440.0,xlat2,xlon2,xl2a,b2a) - fghz=0.001*nfreq - dldt1=DEGS*(xl1a-xl1) - dbdt1=DEGS*(b1a-b1) - dldt2=DEGS*(xl2a-xl2) - dbdt2=DEGS*(b2a-b2) - rate1=2.0*sqrt(dldt1**2 + dbdt1**2) - width1=0.5*6741*fghz*rate1 - rate2=sqrt((dldt1+dldt2)**2 + (dbdt1+dbdt2)**2) - width2=0.5*6741*fghz*rate2 - - fbend=0.7 - a2=0.0045*log(fghz/fbend)/log(1.05) - if(fghz.lt.fbend) a2=0.0 - f50=0.19 * (fghz/fbend)**a2 - if(f50.gt.1.0) f50=1.0 - w501=f50*width1 - w502=f50*width2 - - AzSun8=AzSun - ElSun8=ElSun - AzMoon8=AzMoon - ElMoon8=ElMoon - dbMoon8=dbMoon - RAMoon8=RAMoon/15.0 - DecMoon8=DecMoon - HA8=HA - Dgrd8=Dgrd - sd8=sd - poloffset8=poloffset - xnr8=xnr - ndop=nint(doppler) - ndop00=nint(doppler00) - - if(uth8z.eq.0.d0) then - uth8z=uth8-1.d0/3600.d0 - dopplerz=doppler - doppler00z=doppler00 - endif - - dt=60.0*(uth8-uth8z) - if(dt.le.0) dt=1.d0/60.d0 - dfdt=(doppler-dopplerz)/dt - dfdt0=(doppler00-doppler00z)/dt - uth8z=uth8 - dopplerz=doppler - doppler00z=doppler00 - - return -end subroutine astro0 +module astro0_state_mod + use iso_fortran_env, only: real64 + implicit none + real(real64) :: uth8z = 0.0 + real(real64) :: dopplerz = 0.0 + real(real64) :: doppler00z = 0.0 +end module astro0_state_mod + + +module astro0_mod + use iso_fortran_env, only: real64 + use astro_mod + use astro0_state_mod + use tm2_mod + implicit none + + real(real64), parameter :: DEGS = 57.2957795130823_real64 + +contains + + subroutine astro0(nyear,month,nday,uth8,nfreq,mygrid,hisgrid, & + AzSun8,ElSun8,AzMoon8,ElMoon8,AzMoonB8,ElMoonB8,ntsky,ndop,ndop00, & + dbMoon8,RAMoon8,DecMoon8,HA8,Dgrd8,sd8,poloffset8,xnr8,dfdt,dfdt0, & + width1,width2,w501,w502,xlst8) + + implicit none + + ! Dummy arguments + integer, intent(in) :: nyear, month, nday, nfreq + real(real64), intent(inout) :: uth8 + character(len=6), intent(in) :: mygrid, hisgrid + real(real64), intent(out) :: AzSun8, ElSun8, AzMoon8, ElMoon8 + real(real64), intent(out) :: AzMoonB8, ElMoonB8 + integer, intent(out) :: ntsky, ndop, ndop00 + real(real64), intent(out) :: dbMoon8, RAMoon8, DecMoon8, HA8 + real(real64), intent(out) :: Dgrd8, sd8, poloffset8, xnr8 + real(real64), intent(out) :: dfdt, dfdt0 + real(real64), intent(out) :: width1, width2, w501, w502, xlst8 + + ! Locals + real :: uth,day + real :: doppler00_loc, ndop_loc + real :: AzSun, ElSun, AzMoon, ElMoon + real :: AzMoonB, ElMoonB + integer :: ntsky_loc + real :: dbMoon, RAMoon, DecMoon, HA, Dgrd, sd + real :: poloffset, xnr + real :: xlon1, xlat1, xlon2, xlat2 + real :: xlst + real :: xl1, b1, xl2, b2 + real :: xl1a, b1a, xl2a, b2a + real(real64) :: fghz, dldt1, dbdt1, dldt2, dbdt2 + real(real64) :: rate1, rate2 + real(real64) :: fbend, a2, f50 + real(real64) :: dt + + uth = uth8 + + ! Station 2 (hisgrid) + call astro(nyear,month,nday,uth,nfreq,hisgrid,2,1.0, & + AzSun,ElSun,AzMoonB,ElMoonB,ntsky_loc,doppler00_loc,ndop_loc, & + dbMoon,RAMoon,DecMoon,HA,Dgrd,sd,poloffset,xnr, & + day,xlon2,xlat2,xlst) + + AzMoonB8 = AzMoonB + ElMoonB8 = ElMoonB + + ! Station 1 (mygrid) + call astro(nyear,month,nday,uth,nfreq,mygrid,1,1.0, & + AzSun,ElSun,AzMoon,ElMoon,ntsky_loc,doppler00_loc,ndop_loc, & + dbMoon,RAMoon,DecMoon,HA,Dgrd,sd,poloffset,xnr, & + day,xlon1,xlat1,xlst) + + ! Outputs from second call + AzSun8 = AzSun + ElSun8 = ElSun + AzMoon8 = AzMoon + ElMoon8 = ElMoon + dbMoon8 = dbMoon + RAMoon8 = RAMoon/15.0 + DecMoon8 = DecMoon + HA8 = HA + Dgrd8 = Dgrd + sd8 = sd + poloffset8 = poloffset + xnr8 = xnr + ndop = nint(ndop_loc) + ndop00 = nint(doppler00_loc) + ntsky = ntsky_loc + xlst8 = xlst + + ! Tracking motion for width1/width2 + call tm2(real(day,8),xlat1,xlon1,xl1,b1) + call tm2(real(day,8),xlat2,xlon2,xl2,b2) + call tm2(real(day,8)+1.0/1440.0,xlat1,xlon1,xl1a,b1a) + call tm2(real(day,8)+1.0/1440.0,xlat2,xlon2,xl2a,b2a) + + fghz = 0.001*real(nfreq,real64) + dldt1 = DEGS*(xl1a-xl1) + dbdt1 = DEGS*(b1a-b1) + dldt2 = DEGS*(xl2a-xl2) + dbdt2 = DEGS*(b2a-b2) + + rate1 = 2.0*sqrt(dldt1**2 + dbdt1**2) + width1 = 0.5*6741.0*fghz*rate1 + rate2 = sqrt((dldt1+dldt2)**2 + (dbdt1+dbdt2)**2) + width2 = 0.5*6741.0*fghz*rate2 + + fbend = 0.7 + a2 = 0.0045*log(fghz/fbend)/log(1.05) + if (fghz < fbend) a2 = 0.0 + f50 = 0.19 * (fghz/fbend)**a2 + if (f50 > 1.0) f50 = 1.0 + w501 = f50*width1 + w502 = f50*width2 + + ! df/dt using persistent state in astro0_state_mod + if (uth8z == 0.0) then + uth8z = uth8 - 1.0/3600.0 + dopplerz = ndop_loc + doppler00z = doppler00_loc + end if + + dt = 60.0*(uth8-uth8z) + if (dt <= 0.0) dt = 1.0/60.0 + + dfdt = (ndop_loc - dopplerz )/dt + dfdt0 = (doppler00_loc - doppler00z)/dt + + uth8z = uth8 + dopplerz = ndop_loc + doppler00z = doppler00_loc + + end subroutine astro0 + +end module astro0_mod diff --git a/map65/libm65/astrosub.f90 b/map65/libm65/astrosub.f90 index ce25a0d9..1671f6f0 100644 --- a/map65/libm65/astrosub.f90 +++ b/map65/libm65/astrosub.f90 @@ -1,26 +1,138 @@ -subroutine astrosub(nyear,month,nday,uth8,nfreq,mygrid,hisgrid, & - AzSun8,ElSun8,AzMoon8,ElMoon8,AzMoonB8,ElMoonB8,ntsky,ndop,ndop00, & - RAMoon8,DecMoon8,Dgrd8,poloffset8,xnr8) +module astrosub_mod + use iso_fortran_env, only: real64 + use iso_c_binding, only: c_int, c_double, c_char + use astro0_mod + implicit none - implicit real*8 (a-h,o-z) - character*6 mygrid,hisgrid +contains - call astro0(nyear,month,nday,uth8,nfreq,mygrid,hisgrid, & - AzSun8,ElSun8,AzMoon8,ElMoon8,AzMoonB8,ElMoonB8,ntsky,ndop,ndop00, & - dbMoon8,RAMoon8,DecMoon8,HA8,Dgrd8,sd8,poloffset8,xnr8,dfdt,dfdt0, & - width1,width2,w501,w502,xlst8) + ! Pure Fortran interface (internal) + subroutine astrosub(nyear,month,nday,uth8,nfreq,mygrid,hisgrid, & + AzSun8,ElSun8,AzMoon8,ElMoon8,AzMoonB8,ElMoonB8,ntsky,ndop,ndop00, & + RAMoon8,DecMoon8,Dgrd8,poloffset8,xnr8) + implicit none + integer, intent(in) :: nyear, month, nday, nfreq + real(real64), intent(inout) :: uth8 + character(len=6), intent(in):: mygrid, hisgrid + real(real64), intent(out) :: AzSun8, ElSun8, AzMoon8, ElMoon8 + real(real64), intent(out) :: AzMoonB8, ElMoonB8 + integer, intent(out) :: ntsky, ndop, ndop00 + real(real64), intent(out) :: RAMoon8, DecMoon8, Dgrd8 + real(real64), intent(out) :: poloffset8, xnr8 - return -end subroutine astrosub + ! Locals for astro0 extras we don’t export + real(real64) :: dbMoon8, HA8, sd8, dfdt, dfdt0 + real(real64) :: width1, width2, w501, w502, xlst8 -subroutine astrosub00(nyear,month,nday,uth8,nfreq,mygrid,ndop00) + call astro0(nyear,month,nday,uth8,nfreq,mygrid,hisgrid, & + AzSun8,ElSun8,AzMoon8,ElMoon8,AzMoonB8,ElMoonB8,ntsky,ndop,ndop00, & + dbMoon8,RAMoon8,DecMoon8,HA8,Dgrd8,sd8,poloffset8,xnr8,dfdt,dfdt0, & + width1,width2,w501,w502,xlst8) + end subroutine astrosub - implicit real*8 (a-h,o-z) - character*6 mygrid + subroutine astrosub_legacy(nyear,month,nday,uth8,nfreq, & + mygrid,hisgrid, & + azsun,elsun,azmoon,elmoon, & + azmoondx,elmoondx, & + ntsky,ndop,ndop00, & + ramoon,decmoon,dgrd,poloffset,xnr, & + len1,len2) & + bind(C, name='astrosub_') - call astrosub(nyear,month,nday,uth8,nfreq,mygrid,mygrid, & - AzSun8,ElSun8,AzMoon8,ElMoon8,AzMoonB8,ElMoonB8,ntsky,ndop,ndop00, & - RAMoon8,DecMoon8,Dgrd8,poloffset8,xnr8) + use iso_c_binding + implicit none + + ! ===== C ABI dummy arguments (must match C++ exactly) ===== + integer(c_int), intent(inout) :: nyear, month, nday, nfreq + real(c_double), intent(inout) :: uth8 + character(c_char), intent(in) :: mygrid(*), hisgrid(*) + real(c_double), intent(out) :: azsun, elsun, azmoon, elmoon + real(c_double), intent(out) :: azmoondx, elmoondx + integer(c_int), intent(out) :: ntsky, ndop, ndop00 + real(c_double), intent(out) :: ramoon, decmoon, dgrd + real(c_double), intent(out) :: poloffset, xnr + integer(c_int), value :: len1, len2 + + ! ===== Local CHARACTER*6 buffers ===== + character(len=6) :: g1, g2 + + ! ===== Local Fortran outputs ===== + real(real64) :: AzSun8, ElSun8, AzMoon8, ElMoon8 + real(real64) :: AzMoonB8, ElMoonB8 + integer :: ntsky_loc, ndop_loc, ndop00_loc + real(real64) :: RAMoon8, DecMoon8, Dgrd8, poloffset8, xnr8 + + ! ===== Convert C strings to CHARACTER*6 ===== + call copy_c_to_f6(g1, mygrid, len1) + call copy_c_to_f6(g2, hisgrid, len2) + + ! ===== Call modern Fortran routine ===== + call astrosub(nyear,month,nday,uth8,nfreq,g1,g2, & + AzSun8,ElSun8,AzMoon8,ElMoon8,AzMoonB8,ElMoonB8, & + ntsky_loc,ndop_loc,ndop00_loc, & + RAMoon8,DecMoon8,Dgrd8,poloffset8,xnr8) + ! ===== Copy results back to C ===== + azsun = AzSun8 + elsun = ElSun8 + azmoon = AzMoon8 + elmoon = ElMoon8 + azmoondx = AzMoonB8 + elmoondx = ElMoonB8 + + ntsky = ntsky_loc + ndop = ndop_loc + ndop00 = ndop00_loc + + ramoon = RAMoon8 + decmoon = DecMoon8 + dgrd = Dgrd8 + poloffset= poloffset8 + xnr = xnr8 + end subroutine astrosub_legacy + + ! C-callable wrapper: astrosub00_ + subroutine astrosub00(nyear,month,nday,uth8,nfreq,mygrid,ndop00, mygrid_len) & + bind(C, name='astrosub00_') + use iso_c_binding + implicit none + ! C ABI arguments + integer(c_int), intent(inout) :: nyear, month, nday, nfreq, ndop00 + real(c_double), intent(inout) :: uth8 + character(c_char), intent(in) :: mygrid(*) + integer(c_int), value :: mygrid_len + + ! Locals + character(len=6) :: mygrid6, hisgrid6 + integer :: ntsky, ndop + real(real64) :: AzSun8, ElSun8, AzMoon8, ElMoon8 + real(real64) :: AzMoonB8, ElMoonB8 + real(real64) :: RAMoon8, DecMoon8, Dgrd8 + real(real64) :: poloffset8, xnr8 + + ! C string → Fortran CHARACTER*6 + call copy_c_to_f6(mygrid6, mygrid, mygrid_len) + hisgrid6 = mygrid6 ! same grid for now + + call astrosub(nyear,month,nday,uth8,nfreq,mygrid6,hisgrid6, & + AzSun8,ElSun8,AzMoon8,ElMoon8,AzMoonB8,ElMoonB8,ntsky,ndop,ndop00, & + RAMoon8,DecMoon8,Dgrd8,poloffset8,xnr8) + + end subroutine astrosub00 + + subroutine copy_c_to_f6(dest, src, n) + use iso_c_binding, only: c_char, c_int, c_double, c_null_char + + character(len=6), intent(out) :: dest + character(c_char), intent(in) :: src(*) + integer(c_int), intent(in) :: n + integer :: i + + dest = ' ' + do i = 1, min(6, n) + if (src(i) == c_null_char) exit + dest(i:i) = src(i) + end do + end subroutine copy_c_to_f6 + +end module astrosub_mod - return -end subroutine astrosub00 diff --git a/map65/libm65/averms.f90 b/map65/libm65/averms.f90 deleted file mode 100644 index 904004c8..00000000 --- a/map65/libm65/averms.f90 +++ /dev/null @@ -1,20 +0,0 @@ -subroutine averms(x,n,nskip,ave,rms) - real x(n) - integer ipk(1) - - ns=0 - s=0. - sq=0. - ipk=maxloc(x) - do i=1,n - if(abs(i-ipk(1)).gt.nskip) then - s=s + x(i) - sq=sq + x(i)**2 - ns=ns+1 - endif - enddo - ave=s/ns - rms=sqrt(sq/ns - ave*ave) - - return -end subroutine averms diff --git a/map65/libm65/badmsg.f90 b/map65/libm65/badmsg.f90 deleted file mode 100644 index 007da8a8..00000000 --- a/map65/libm65/badmsg.f90 +++ /dev/null @@ -1,46 +0,0 @@ -subroutine badmsg(irc,dat,nc1,nc2,ng2) - -! Get rid of a few QRA64 false decodes that cannot be correct messages. - - integer dat(12) !Decoded message (as 12 integers) - - ic1=ishft(dat(1),22) + ishft(dat(2),16) + ishft(dat(3),10)+ & - ishft(dat(4),4) + iand(ishft(dat(5),-2),15) - -! Test for "......" or "CQ 000" - if(ic1.eq.262177560 .or. ic1.eq.262177563) then - irc=-1 - return - endif - - ic2=ishft(iand(dat(5),3),26) + ishft(dat(6),20) + & - ishft(dat(7),14) + ishft(dat(8),8) + ishft(dat(9),2) + & - iand(ishft(dat(10),-4),3) - - ig=ishft(iand(dat(10),15),12) + ishft(dat(11),6) + dat(12) - -! Test for blank, -01 to -30, R-01 to R-30, RO, RRR, 73 - if(ig.ge.32401 .and. ig.le.32464) return - - if(ig.ge.14220 .and. ig.le.14229) return !-41 to -50 - if(ig.ge.14040 .and. ig.le.14049) return !-31 to -40 - - if(ig.ge.13320 .and. ig.le.13329) return !+00 to +09 - if(ig.ge.13140 .and. ig.le.13149) return !+10 to +19 - if(ig.ge.12960 .and. ig.le.12969) return !+20 to +29 - if(ig.ge.12780 .and. ig.le.12789) return !+30 to +39 - if(ig.ge.12600 .and. ig.le.12609) return !+40 to +49 - - if(ig.ge.12420 .and. ig.le.12429) return !R-41 to R-50 - if(ig.ge.12240 .and. ig.le.12249) return !R-31 to R-40 - - if(ig.ge.11520 .and. ig.le.11529) return !R+00 to R+09 - if(ig.ge.11340 .and. ig.le.11349) return !R+10 to R+19 - if(ig.ge.11160 .and. ig.le.11169) return !R+20 to R+29 - if(ig.ge.10980 .and. ig.le.10989) return !R+30 to R+39 - if(ig.ge.10800 .and. ig.le.10809) return !R+40 to R+49 - - if(ic1.eq.nc1 .and. ic2.eq.nc2 .and. ng2.ne.32401 .and. ig.ne.ng2) irc=-1 - - return -end subroutine badmsg diff --git a/map65/libm65/cacb_mod.f90 b/map65/libm65/cacb_mod.f90 new file mode 100644 index 00000000..badd7025 --- /dev/null +++ b/map65/libm65/cacb_mod.f90 @@ -0,0 +1,13 @@ +module cacb_mod + implicit none + complex, allocatable :: ca(:), cb(:) ! FFTs of input + +contains + subroutine init_cacb(n) + use iso_fortran_env + integer, intent(in) :: n + if (.not. allocated(ca)) allocate (ca(n)) + if (.not. allocated(cb)) allocate (cb(n)) + end subroutine init_cacb + +end module cacb_mod diff --git a/map65/libm65/ccf2.f90 b/map65/libm65/ccf2.f90 index 287e70ff..521c7d6f 100644 --- a/map65/libm65/ccf2.f90 +++ b/map65/libm65/ccf2.f90 @@ -1,45 +1,68 @@ -subroutine ccf2(ss,nz,nflip,ccfbest,lagpk) +module ccf2_mod + implicit none +contains -! parameter (LAGMAX=60) - parameter (LAGMAX=200) - real ss(nz) - real ccf(-LAGMAX:LAGMAX) - integer npr(126) +subroutine ccf2(ss, nz, nflip, ccfbest, lagpk) + implicit none -! The JT65 pseudo-random sync pattern: - data npr/ & + !==== Arguments ============================================================ + integer, intent(in) :: nz + real, intent(in) :: ss(nz) + integer, intent(in) :: nflip + real, intent(out) :: ccfbest + integer, intent(out) :: lagpk + + !==== Parameters =========================================================== + integer, parameter :: LAGMAX = 200 + + !==== Local variables ====================================================== + real :: ccf(-LAGMAX:LAGMAX) + real :: s0, s1, x + integer :: npr(126) + integer :: i, j, lag, lag1, lag2 + + !==== JT65 pseudo-random sync pattern ===================================== + data npr / & 1,0,0,1,1,0,0,0,1,1,1,1,1,1,0,1,0,1,0,0, & 0,1,0,1,1,0,0,1,0,0,0,1,1,1,0,0,1,1,1,1, & 0,1,1,0,1,1,1,1,0,0,0,1,1,0,1,0,1,0,1,1, & 0,0,1,1,0,1,0,1,0,1,0,0,1,0,0,0,0,0,0,1, & 1,0,0,0,0,0,0,0,1,1,0,1,0,0,1,0,1,1,0,1, & 0,1,0,1,0,0,1,1,0,0,1,0,0,1,0,0,0,0,1,1, & - 1,1,1,1,1,1/ - save - - ccfbest=0. - lag1=-LAGMAX - lag2=LAGMAX - do lag=lag1,lag2 - s0=0. - s1=0. - do i=1,126 - j=2*(8*i + 43) + lag - if(j.ge.1 .and. j.le.nz-8) then - x=ss(j)+ss(j+8) !Add two half-symbol contributions - if(npr(i).eq.0) then - s0=s0 + x + 1,1,1,1,1,1 / + + !==== Initialize outputs =================================================== + ccfbest = 0.0 + lagpk = 0 + + !==== Main correlation loop =============================================== + lag1 = -LAGMAX + lag2 = LAGMAX + + do lag = lag1, lag2 + s0 = 0.0 + s1 = 0.0 + + do i = 1, 126 + j = 2*(8*i + 43) + lag + if (j >= 1 .and. j <= nz-8) then + x = ss(j) + ss(j+8) + if (npr(i) == 0) then + s0 = s0 + x else - s1=s1 + x - endif - endif - enddo - ccf(lag)=nflip*(s1-s0) - if(ccf(lag).gt.ccfbest) then - ccfbest=ccf(lag) - lagpk=lag - endif - enddo - - return + s1 = s1 + x + end if + end if + end do + + ccf(lag) = nflip * (s1 - s0) + + if (ccf(lag) > ccfbest) then + ccfbest = ccf(lag) + lagpk = lag + end if + end do + end subroutine ccf2 + +end module ccf2_mod diff --git a/map65/libm65/ccf65.f90 b/map65/libm65/ccf65.f90 index 592fe95e..2aa5228a 100644 --- a/map65/libm65/ccf65.f90 +++ b/map65/libm65/ccf65.f90 @@ -1,23 +1,55 @@ -subroutine ccf65(ss,nhsym,ssmax,sync1,ipol1,jpz,dt1,flipk, & - syncshort,snr2,ipol2,dt2) - - parameter (NFFT=512,NH=NFFT/2) - real ss(4,322) !Input: half-symbol powers, 4 pol'ns - real s(NFFT) !CCF = ss*pr - complex cs(0:NH) !Complex FT of s - real s2(NFFT) !CCF = ss*pr2 - complex cs2(0:NH) !Complex FT of s2 - real pr(NFFT) !JT65 pseudo-random sync pattern - complex cpr(0:NH) !Complex FT of pr - real pr2(NFFT) !JT65 shorthand pattern - complex cpr2(0:NH) !Complex FT of pr2 - real tmp1(322) +!------------------------------------------------------------------------------ +! NOTE: This routine preserves the legacy JT65 correlation core. Its boundary +! validation and output defaults make degenerate inputs deterministic +! without changing the normal signal-processing path. +!------------------------------------------------------------------------------ + +module ccf65_legacy_mod + implicit none +contains + +subroutine ccf65(ss_plane, nhsym, ssmax, sync1, ipol1, jpz, dt1, flipk, & + syncshort, snr2, ipol2, dt2) + + use four2a_legacy_wrap_mod, only: r2c_legacy, c2r_legacy, JT65_NFFT, JT65_NH + use pctile_mod, only: pctile + use, intrinsic :: ieee_arithmetic, only: ieee_is_finite + + implicit none + + integer, parameter :: NFFT = JT65_NFFT + integer, parameter :: NH = JT65_NH + integer, parameter :: MAX_NHSYM = 322 + + integer, intent(in) :: nhsym, jpz + real, intent(in) :: ssmax + real, intent(out) :: sync1, dt1, flipk, syncshort, snr2, dt2 + integer, intent(out) :: ipol1, ipol2 + + ! Modern interface: + ! ss_plane(4,322) is passed as a proper 2-D slice (ss(:,:,i)) + real, intent(in) :: ss_plane(4,MAX_NHSYM) + + ! Legacy expects: real ss(4,322) passed by reference from ss(1,1,i) + real :: ss(4,MAX_NHSYM) + + ! time-domain + real :: s(NFFT) ! CCF = ss*pr + real :: s2(NFFT) ! CCF = ss*pr2 + real :: pr(NFFT) ! JT65 pseudo-random sync pattern + real :: pr2(NFFT) ! JT65 shorthand pattern + + ! frequency-domain: half-spectrum, as in legacy + complex :: cs(0:NH) ! Complex FT of s + complex :: cs2(0:NH) ! Complex FT of s2 + complex :: cpr(0:NH) ! Complex FT of pr + complex :: cpr2(0:NH) ! Complex FT of pr2 + + real tmp1(MAX_NHSYM) real ccf(-11:54,4) - logical first integer npr(126) - data first/.true./ - equivalence (s,cs),(pr,cpr),(s2,cs2),(pr2,cpr2) - save + integer :: i, j, k, ip, lag, lagpk, lagpk2, npol + real :: fac, base, ccfbest, ccfbest2, ccf2, sumccf, sq, rms ! The JT65 pseudo-random sync pattern: data npr/ & @@ -29,34 +61,48 @@ subroutine ccf65(ss,nhsym,ssmax,sync1,ipol1,jpz,dt1,flipk, & 0,1,0,1,0,0,1,1,0,0,1,0,0,1,0,0,0,0,1,1, & 1,1,1,1,1,1/ - if(first) then -! Initialize pr, pr2; compute cpr, cpr2. - fac=1.0/NFFT - do i=1,NFFT - pr(i)=0. - pr2(i)=0. - k=2*mod((i-1)/8,2)-1 - if(i.le.NH) pr2(i)=fac*k - enddo - do i=1,126 - j=2*i - pr(j)=fac*(2*npr(i)-1) -! Not sure why, but it works significantly better without the following line: -! pr(j-1)=pr(j) - enddo - call four2a(cpr,NFFT,1,-1,0) - call four2a(cpr2,NFFT,1,-1,0) - first=.false. - endif - syncshort=0. - snr2=0. + sync1 = -4.0 + syncshort = -4.0 + snr2 = 0.01 + dt1 = 0.0 + dt2 = 0.0 + flipk = 1.0 + ipol1 = 1 + ipol2 = 1 + + if (nhsym < 2 .or. nhsym > MAX_NHSYM) return + if (jpz < 1 .or. jpz > 4) return + if (.not. ieee_is_finite(ssmax)) return + + npol = jpz + ss = ss_plane + if (.not. all(ieee_is_finite(ss(1:npol,1:nhsym)))) return + + fac = 1.0/NFFT + do i=1,NFFT + pr(i)=0. + pr2(i)=0. + k=2*mod((i-1)/8,2)-1 + if(i.le.NH) pr2(i)=fac*k + enddo + do i=1,126 + j=2*i + pr(j)=fac*(2*npr(i)-1) + enddo + + call r2c_legacy(pr, cpr) + call r2c_legacy(pr2, cpr2) + + ccf = 0.0 ! Look for JT65 sync pattern and shorthand square-wave pattern. ccfbest=0. ccfbest2=0. ipol1=1 ipol2=1 - do ip=1,jpz !Do jpz polarizations + lagpk=0 + lagpk2=0 + do ip=1,npol !Do npol polarizations do i=1,nhsym-1 ! s(i)=ss(ip,i)+ss(ip,i+1) s(i)=min(ssmax,ss(ip,i)+ss(ip,i+1)) @@ -64,13 +110,19 @@ subroutine ccf65(ss,nhsym,ssmax,sync1,ipol1,jpz,dt1,flipk, & call pctile(s,nhsym-1,50,base) s(1:nhsym-1)=s(1:nhsym-1)-base s(nhsym:NFFT)=0. - call four2a(cs,NFFT,1,-1,0) !Real-to-complex FFT + + ! === Forward FFT: real ? packed half-spectrum === + call r2c_legacy(s, cs) + + ! === Multiply by sync patterns in frequency domain === do i=0,NH - cs2(i)=cs(i)*conjg(cpr2(i)) !Mult by complex FFT of pr2 - cs(i)=cs(i)*conjg(cpr(i)) !Mult by complex FFT of pr + cs2(i) = cs(i) * conjg(cpr2(i)) + cs(i) = cs(i) * conjg(cpr(i)) enddo - call four2a(cs,NFFT,1,1,-1) !Complex-to-real inv-FFT - call four2a(cs2,NFFT,1,1,-1) !Complex-to-real inv-FFT + + ! === Inverse FFT: packed half-spectrum ? real === + call c2r_legacy(cs, s) + call c2r_legacy(cs2, s2) do lag=-11,54 !Check for best JT65 sync j=lag @@ -85,9 +137,6 @@ subroutine ccf65(ss,nhsym,ssmax,sync1,ipol1,jpz,dt1,flipk, & endif enddo -!### Not sure why this is ever true??? - if(sum(ccf).eq.0.0) return -!### do lag=-11,54 !Check for best shorthand ccf2=s2(lag+28) if(ccf2.gt.ccfbest2) then @@ -99,6 +148,8 @@ subroutine ccf65(ss,nhsym,ssmax,sync1,ipol1,jpz,dt1,flipk, & enddo + if (.not. ieee_is_finite(ccfbest) .or. ccfbest <= 0.0) return + ! Find rms level on baseline of "ccfblue", for normalization. sumccf=0. do lag=-11,54 @@ -110,8 +161,10 @@ subroutine ccf65(ss,nhsym,ssmax,sync1,ipol1,jpz,dt1,flipk, & if(abs(lag-lagpk).gt.1) sq=sq + (ccf(lag,ipol1)-base)**2 enddo rms=sqrt(sq/49.0) - sync1=-4.0 - if(rms.gt.0.0) sync1=ccfbest/rms - 4.0 + if (ieee_is_finite(rms) .and. rms > 0.0) then + sync1=ccfbest/rms - 4.0 + syncshort=0.5*ccfbest2/rms - 4.0 + endif dt1=lagpk*(2048.0/11025.0) - 2.5 ! Find base level for normalizing snr2. @@ -121,8 +174,12 @@ subroutine ccf65(ss,nhsym,ssmax,sync1,ipol1,jpz,dt1,flipk, & call pctile(tmp1,nhsym,40,base) snr2=0.01 if(base.gt.0.0) snr2=0.398107*ccfbest2/base !### empirical - syncshort=0.5*ccfbest2/rms - 4.0 !### better normalizer than rms? dt2=2.5 + lagpk2*(2048.0/11025.0) + if (.not. ieee_is_finite(sync1)) sync1 = -4.0 + if (.not. ieee_is_finite(syncshort)) syncshort = -4.0 + if (.not. ieee_is_finite(snr2)) snr2 = 0.01 + return end subroutine ccf65 +end module ccf65_legacy_mod diff --git a/map65/libm65/cgen65.f90 b/map65/libm65/cgen65.f90 index 096e9790..6fcf98d6 100644 --- a/map65/libm65/cgen65.f90 +++ b/map65/libm65/cgen65.f90 @@ -1,21 +1,49 @@ -subroutine cgen65(message,mode65,samfac,nsendingsh,msgsent,cwave,nwave) +module cgen65_mod + implicit none +contains -! Encodes a JT65 message into a wavefile. -! Executes in 17 ms on opti-745. +subroutine cgen65(message,mode65,samfac,nsendingsh,msgsent,cwave,nwave) + use iso_fortran_env, only: int8, real64 use packjt + use chkmsg_mod + use graycode_mod + use rs_mod + use interleave63_mod, only: interleave63 + !-------------------------------------------------------------------- + ! Parameters and arguments + !-------------------------------------------------------------------- + integer, parameter :: NMAX = 60*96000 + + character(len=22),intent(inout) :: message + integer, intent(in) :: mode65 + real(real64), intent(in) :: samfac + + integer, intent(out) :: nsendingsh + character(len=22),intent(out) :: msgsent + complex, intent(out) :: cwave(:) + integer, intent(out) :: nwave + + !-------------------------------------------------------------------- + ! Local variables (explicit typing) + !-------------------------------------------------------------------- + character(len=3) :: cok + real(real64) :: t, dt, phi, f, f0, dfgen, dphi, twopi, tsymbol + real(real64) :: xphi + real :: pr(126), flip + + integer :: dgen(12) + integer :: sent(63) + integer :: nprc(126) + integer :: nspecial, itype + integer :: nsym, ndata + integer :: i, j, j0, k - parameter (NMAX=60*96000) !Max length of wave file - character*22 message !Message to be generated - character*22 msgsent !Message as it will be received - character*3 cok !' ' or 'OOO' - real*8 t,dt,phi,f,f0,dfgen,dphi,twopi,samfac,tsymbol - complex cwave(NMAX) !Generated complex wave file - integer dgen(12) - integer sent(63) - logical first - integer nprc(126) - real pr(126) + logical :: first + + !-------------------------------------------------------------------- + ! DATA initialization (preserved exactly) + !-------------------------------------------------------------------- data nprc/1,0,0,1,1,0,0,0,1,1,1,1,1,1,0,1,0,1,0,0, & 0,1,0,1,1,0,0,1,0,0,0,1,1,1,0,0,1,1,1,1, & 0,1,1,0,1,1,1,1,0,0,0,1,1,0,1,0,1,0,1,1, & @@ -23,77 +51,107 @@ subroutine cgen65(message,mode65,samfac,nsendingsh,msgsent,cwave,nwave) 1,0,0,0,0,0,0,0,1,1,0,1,0,0,1,0,1,1,0,1, & 0,1,0,1,0,0,1,1,0,0,1,0,0,1,0,0,0,0,1,1, & 1,1,1,1,1,1/ - data twopi/6.283185307179586476d0/,first/.true./ + data twopi /6.283185307179586476d0/ + data first /.true./ save - if(first) then - do i=1,126 - pr(i)=2*nprc(i)-1 + !-------------------------------------------------------------------- + ! First‑time initialization of pr() + !-------------------------------------------------------------------- + if (first) then + do i = 1, 126 + pr(i) = 2*nprc(i) - 1 enddo - first=.false. + first = .false. endif - call chkmsg(message,cok,nspecial,flip) !See if it's a shorthand - if(nspecial.eq.0) then - call packmsg(message,dgen,itype) !Pack message into 72 bits - nsendingsh=0 - if(iand(dgen(10),8).ne.0) nsendingsh=-1 !Plain text flag - - call rs_encode(dgen,sent) - call interleave63(sent,1) !Apply interleaving - call graycode(sent,63,1) !Apply Gray code - nsym=126 !Symbols per transmission - tsymbol=4096.d0/11025.d0 !Time per symbol + !-------------------------------------------------------------------- + ! Message packing / shorthand detection + !-------------------------------------------------------------------- + call chkmsg(message, cok, nspecial, flip) + + if (nspecial .eq. 0) then + call packmsg(message, dgen, itype) + nsendingsh = 0 + if (iand(dgen(10),8) .ne. 0) nsendingsh = -1 ! Plain text flag + + call rs_encode_(dgen, sent) + call interleave63(sent, 1) + call graycode(sent, 63, 1) + + nsym = 126 + tsymbol = 4096.d0 / 11025.d0 else - nsendingsh=1 !Flag for shorthand message - nsym=32 - tsymbol=16384.d0/11025.d0 + nsendingsh = 1 + nsym = 32 + tsymbol = 16384.d0 / 11025.d0 endif -! Set up necessary constants - dt=1.d0/(samfac*96000.d0) - f0=118*11025.d0/1024 - dfgen=mode65*11025.d0/4096.d0 - t=0.d0 - phi=0.d0 - k=0 - j0=0 - ndata=nsym*96000.d0*samfac*tsymbol - - do i=1,ndata - t=t+dt - j=int(t/tsymbol) + 1 !Symbol number, 1-126 - if(j.ne.j0) then - f=f0 - if(nspecial.ne.0 .and. mod(j,2).eq.0) f=f0+10*nspecial*dfgen - if(nspecial.eq.0 .and. flip*pr(j).lt.0.0) then - k=k+1 - f=f0+(sent(k)+2)*dfgen + !-------------------------------------------------------------------- + ! Waveform generation constants + !-------------------------------------------------------------------- + dt = 1.d0 / (samfac * 96000.d0) + f0 = 118 * 11025.d0 / 1024.d0 + dfgen = mode65 * 11025.d0 / 4096.d0 + + t = 0.d0 + phi = 0.d0 + k = 0 + j0 = 0 + + ndata = nsym * 96000.d0 * samfac * tsymbol + + !-------------------------------------------------------------------- + ! Main waveform synthesis loop + !-------------------------------------------------------------------- + do i = 1, ndata + t = t + dt + j = min(nsym, int(t / tsymbol) + 1) + + if (j .ne. j0) then + f = f0 + + if (nspecial .ne. 0 .and. mod(j,2) .eq. 0) then + f = f0 + 10 * nspecial * dfgen endif - dphi=twopi*dt*f - j0=j + + if (nspecial .eq. 0 .and. flip * pr(j) .lt. 0.d0) then + k = k + 1 + f = f0 + (sent(k) + 2) * dfgen + endif + + dphi = twopi * dt * f + j0 = j endif - phi=phi+dphi - if(phi.gt.twopi) phi=phi-twopi - xphi=phi - cwave(i)=cmplx(cos(xphi),-sin(xphi)) + + phi = phi + dphi + if (phi .gt. twopi) phi = phi - twopi + + xphi = phi + cwave(i) = cmplx(cos(xphi), -sin(xphi)) enddo - cwave(ndata+1:)=0 - nwave=ndata + 48000 - call unpackmsg(dgen,msgsent) - if(flip.lt.0.0) then - do i=22,1,-1 - if(msgsent(i:i).ne.' ') goto 10 + !-------------------------------------------------------------------- + ! Pad and finalize + !-------------------------------------------------------------------- + cwave(ndata+1:) = (0.0, 0.0) + nwave = ndata + 48000 + + call unpackmsg(dgen, msgsent) + + if (flip .lt. 0.d0) then + do i = 22, 1, -1 + if (msgsent(i:i) .ne. ' ') exit enddo -10 msgsent=msgsent(1:i)//' OOO' + msgsent = msgsent(1:i) // ' OOO' endif - if(nsendingsh.eq.1) then - if(nspecial.eq.2) msgsent='RO' - if(nspecial.eq.3) msgsent='RRR' - if(nspecial.eq.4) msgsent='73' + if (nsendingsh .eq. 1) then + if (nspecial .eq. 2) msgsent = 'RO' + if (nspecial .eq. 3) msgsent = 'RRR' + if (nspecial .eq. 4) msgsent = '73' endif - return end subroutine cgen65 + +end module cgen65_mod diff --git a/map65/libm65/chkhist.f90 b/map65/libm65/chkhist.f90 index c814c3ca..51d1ee72 100644 --- a/map65/libm65/chkhist.f90 +++ b/map65/libm65/chkhist.f90 @@ -1,23 +1,49 @@ -subroutine chkhist(mrsym,nmax,ipk) +module chkhist_mod + implicit none +contains - integer mrsym(63) - integer hist(0:63) +subroutine chkhist(mrsym, nmax, ipk) + implicit none - do i=0,63 - hist(i)=0 + !-------------------------------------------------------------------- + ! Arguments + !-------------------------------------------------------------------- + integer, intent(in) :: mrsym(63) + integer, intent(out) :: nmax + integer, intent(out) :: ipk + + !-------------------------------------------------------------------- + ! Locals + !-------------------------------------------------------------------- + integer :: hist(0:63) + integer :: i, j + + !-------------------------------------------------------------------- + ! Initialize histogram + !-------------------------------------------------------------------- + do i = 0, 63 + hist(i) = 0 enddo - do j=1,63 - i=mrsym(j) - hist(i)=hist(i)+1 + + !-------------------------------------------------------------------- + ! Count occurrences + !-------------------------------------------------------------------- + do j = 1, 63 + i = mrsym(j) + hist(i) = hist(i) + 1 enddo - nmax=0 - do i=0,63 - if(hist(i).gt.nmax) then - nmax=hist(i) - ipk=i+1 + !-------------------------------------------------------------------- + ! Find maximum bin and its index + !-------------------------------------------------------------------- + nmax = 0 + do i = 0, 63 + if (hist(i) > nmax) then + nmax = hist(i) + ipk = i + 1 endif enddo - return end subroutine chkhist + +end module chkhist_mod diff --git a/map65/libm65/chkmsg.f90 b/map65/libm65/chkmsg.f90 index 457a8092..9bf86780 100644 --- a/map65/libm65/chkmsg.f90 +++ b/map65/libm65/chkmsg.f90 @@ -1,31 +1,61 @@ -subroutine chkmsg(message,cok,nspecial,flip) +module chkmsg_mod + implicit none +contains - character message*22,cok*3 +subroutine chkmsg(message, cok, nspecial, flip) + implicit none - nspecial=0 - flip=1.0 - cok=" " + !-------------------------------------------------------------------- + ! Arguments + !-------------------------------------------------------------------- + character(len=22), intent(inout) :: message ! modified if OOO/OO removed + character(len=3), intent(out) :: cok + integer, intent(out) :: nspecial + real, intent(out) :: flip - do i=22,1,-1 - if(message(i:i).ne.' ') go to 10 + !-------------------------------------------------------------------- + ! Locals + !-------------------------------------------------------------------- + integer :: i + + !-------------------------------------------------------------------- + ! Initialization + !-------------------------------------------------------------------- + nspecial = 0 + flip = 1.0d0 + cok = ' ' + + !-------------------------------------------------------------------- + ! Find last non‑blank character + !-------------------------------------------------------------------- + do i = 22, 1, -1 + if (message(i:i) .ne. ' ') exit enddo - i=22 - -10 if(i.ge.11) then - if ((message(i-3:i).eq.' OOO') .or. (message(20:22).eq.' OO')) then - cok='OOO' - flip=-1.0 - if(message(20:22).eq.' OO') then - message=message(1:19) + if (i == 0) i = 22 ! defensive fallback + + !-------------------------------------------------------------------- + ! Detect trailing OOO / OO shorthand + !-------------------------------------------------------------------- + if (i >= 11) then + if ( (message(i-3:i) == ' OOO') .or. (message(20:22) == ' OO') ) then + cok = 'OOO' + flip = -1.0d0 + + if (message(20:22) == ' OO') then + message = message(1:19) else - message=message(1:i-4) + message = message(1:i-4) endif endif endif - if(message(1:3).eq.'RO ') nspecial=2 - if(message(1:4).eq.'RRR ') nspecial=3 - if(message(1:3).eq.'73 ') nspecial=4 + !-------------------------------------------------------------------- + ! Detect leading shorthand messages + !-------------------------------------------------------------------- + if (message(1:3) == 'RO ') nspecial = 2 + if (message(1:4) == 'RRR ') nspecial = 3 + if (message(1:3) == '73 ') nspecial = 4 - return end subroutine chkmsg + +end module chkmsg_mod diff --git a/map65/libm65/coord.f90 b/map65/libm65/coord.f90 index 8934b612..62bd9a42 100644 --- a/map65/libm65/coord.f90 +++ b/map65/libm65/coord.f90 @@ -1,40 +1,62 @@ -SUBROUTINE COORD(A0,B0,AP,BP,A1,B1,A2,B2) - -! Examples: -! 1. From ha,dec to az,el: -! call coord(pi,pio2-lat,0.,lat,ha,dec,az,el) -! 2. From az,el to ha,dec: -! call coord(pi,pio2-lat,0.,lat,az,el,ha,dec) -! 3. From ra,dec to l,b -! call coord(4.635594495,-0.504691042,3.355395488,0.478220215, -! ra,dec,l,b) -! 4. From l,b to ra,dec -! call coord(1.705981071d0,-1.050357016d0,2.146800277d0, -! 0.478220215d0,l,b,ra,dec) -! 5. From ra,dec to ecliptic latitude (eb) and longitude (el): -! call coord(0.d0,0.d0,-pio2,pio2-23.443*pi/180,ra,dec,el,eb) -! 6. From ecliptic latitude (eb) and longitude (el) to ra,dec: -! call coord(0.d0,0.d0,-pio2,pio2-23.443*pi/180,el,eb,ra,dec) - - SB0=sin(B0) - CB0=cos(B0) - SBP=sin(BP) - CBP=cos(BP) - SB1=sin(B1) - CB1=cos(B1) - SB2=SBP*SB1 + CBP*CB1*cos(AP-A1) - CB2=SQRT(1.e0-SB2**2) - B2=atan(SB2/CB2) - SAA=sin(AP-A1)*CB1/CB2 - CAA=(SB1-SB2*SBP)/(CB2*CBP) - CBB=SB0/CBP - SBB=sin(AP-A0)*CB0 - SA2=SAA*CBB-CAA*SBB - CA2=CAA*CBB+SAA*SBB - TA2O2=0.0 !Shut up compiler warnings. -db - IF(CA2.LE.0.e0) TA2O2=(1.e0-CA2)/SA2 - IF(CA2.GT.0.e0) TA2O2=SA2/(1.e0+CA2) - A2=2.e0*atan(TA2O2) - IF(A2.LT.0.e0) A2=A2+6.2831853 - RETURN -END SUBROUTINE COORD +module coord_mod + implicit none +contains + +subroutine coord(A0, B0, AP, BP, A1, B1, A2, B2) + use iso_fortran_env, only: real32, real64 + implicit none + + !-------------------------------------------------------------------- + ! Arguments (all double precision) + !-------------------------------------------------------------------- + real(real32), intent(in) :: A0, B0, AP, BP + real(real32), intent(in) :: A1, B1 + real(real32), intent(out) :: A2, B2 + + !-------------------------------------------------------------------- + ! Locals + !-------------------------------------------------------------------- + real(real64) :: SB0, CB0, SBP, CBP, SB1, CB1 + real(real64) :: SB2, CB2, SAA, CAA, CBB, SBB + real(real64) :: SA2, CA2, TA2O2 + + !-------------------------------------------------------------------- + ! Compute sines and cosines + !-------------------------------------------------------------------- + SB0 = sin(B0) + CB0 = cos(B0) + SBP = sin(BP) + CBP = cos(BP) + SB1 = sin(B1) + CB1 = cos(B1) + + !-------------------------------------------------------------------- + ! Core spherical rotation + !-------------------------------------------------------------------- + SB2 = SBP*SB1 + CBP*CB1*cos(AP - A1) + CB2 = sqrt(1.0d0 - SB2**2) + B2 = atan(SB2 / CB2) + + SAA = sin(AP - A1) * CB1 / CB2 + CAA = (SB1 - SB2*SBP) / (CB2*CBP) + + CBB = SB0 / CBP + SBB = sin(AP - A0) * CB0 + + SA2 = SAA*CBB - CAA*SBB + CA2 = CAA*CBB + SAA*SBB + + !-------------------------------------------------------------------- + ! atan2-like reconstruction using stable formula + !-------------------------------------------------------------------- + TA2O2 = 0.0d0 + if (CA2 <= 0.0d0) TA2O2 = (1.0d0 - CA2) / SA2 + if (CA2 > 0.0d0) TA2O2 = SA2 / (1.0d0 + CA2) + + A2 = 2.0d0 * atan(TA2O2) + + if (A2 < 0.0d0) A2 = A2 + 6.2831853071795864d0 + +end subroutine coord + +end module coord_mod diff --git a/map65/libm65/datcom_ptrs_mod.f90 b/map65/libm65/datcom_ptrs_mod.f90 new file mode 100644 index 00000000..a507168e --- /dev/null +++ b/map65/libm65/datcom_ptrs_mod.f90 @@ -0,0 +1,126 @@ +module datcom_ptrs_mod + use iso_c_binding + implicit none + + ! Fortran pointer targets + real(c_float), pointer, contiguous :: dd(:,:) => null() ! [4, 5760000] + real(c_float), pointer, contiguous :: ss(:,:,:) => null() ! [4, 322, NFFT] + real(c_float), pointer, contiguous :: savg(:,:) => null() ! [4, NFFT] + real(c_float), pointer, contiguous :: dd_old(:,:) => null() ! [4, 5760000] + real(c_float), pointer, contiguous :: ss_old(:,:,:) => null() ! [4, 322, NFFT] + real(c_float), pointer, contiguous :: savg_old(:,:) => null() ! [4, NFFT] + + ! Pointers used by decode0 / narrowband decoder + real(c_float), pointer, contiguous :: dd_use(:,:) => null() + real(c_float), pointer, contiguous :: ss_use(:,:,:)=> null() + real(c_float), pointer, contiguous :: savg_use(:,:)=> null() + + ! Scalar values + integer, parameter :: NFFT=32768 !Length of FFTs + integer(c_int) :: junk1 = 0, junk2 = 0, quitid = 0 + +contains + + subroutine snapshot_buffers() bind(C) + dd_old(:,:) = dd(:,:) + ss_old(:,:,:) = ss(:,:,:) + savg_old(:,:) = savg(:,:) + end subroutine + + ! Helper subroutine to copy fixed-length Fortran string to C buffer + subroutine move_chars(dest, dest_len, src) + integer(c_int), intent(in) :: dest_len + character(kind=c_char), intent(out) :: dest(dest_len) + character(len=*), intent(in) :: src + integer :: i, n + + n = min(len(src), dest_len) + do i = 1, n + dest(i) = src(i:i) + end do + end subroutine move_chars + + subroutine set_dd_ptr(ptr, dim1, dim2) bind(C, name="set_dd_ptr") + use iso_c_binding + implicit none + type(c_ptr), value :: ptr + integer(c_int), value :: dim1, dim2 + call c_f_pointer(ptr, dd, [dim1, dim2]) + print *, "Fortran: dd pointer associated with dimensions", dim1, dim2 + end subroutine + + subroutine set_ss_ptr(ptr, dim1, dim2, dim3) bind(C, name="set_ss_ptr") + use iso_c_binding + implicit none + type(c_ptr), value :: ptr + integer(c_int), value :: dim1, dim2, dim3 + call c_f_pointer(ptr, ss, [dim1, dim2, dim3]) + print *, "Fortran: ss pointer associated with dimensions", dim1, dim2, dim3 + end subroutine + + subroutine set_savg_ptr(ptr, dim1, dim2) bind(C, name="set_savg_ptr") + use iso_c_binding + implicit none + type(c_ptr), value :: ptr + integer(c_int), value :: dim1, dim2 + call c_f_pointer(ptr, savg, [dim1, dim2]) + print *, "Fortran: savg pointer associated with dimensions", dim1, dim2 + end subroutine + + subroutine set_dd_old_ptr(ptr, dim1, dim2) bind(C, name="set_dd_old_ptr") + use iso_c_binding + implicit none + type(c_ptr), value :: ptr + integer(c_int), value :: dim1, dim2 + call c_f_pointer(ptr, dd_old, [dim1, dim2]) + print *, "Fortran: dd_old pointer associated with dimensions", dim1, dim2 + end subroutine + + subroutine set_ss_old_ptr(ptr, dim1, dim2, dim3) bind(C, name="set_ss_old_ptr") + use iso_c_binding + implicit none + type(c_ptr), value :: ptr + integer(c_int), value :: dim1, dim2, dim3 + call c_f_pointer(ptr, ss_old, [dim1, dim2, dim3]) + print *, "Fortran: ss_old pointer associated with dimensions", dim1, dim2, dim3 + end subroutine + + subroutine set_savg_old_ptr(ptr, dim1, dim2) bind(C, name="set_savg_old_ptr") + use iso_c_binding + implicit none + type(c_ptr), value :: ptr + integer(c_int), value :: dim1, dim2 + call c_f_pointer(ptr, savg_old, [dim1, dim2]) + print *, "Fortran: savg_old pointer associated with dimensions", dim1, dim2 + end subroutine + + function get_junk1() bind(C, name="get_junk1") + integer(c_int) :: get_junk1 + get_junk1 = junk1 + end function + + function get_junk2() bind(C, name="get_junk2") + integer(c_int) :: get_junk2 + get_junk2 = junk2 + end function + +subroutine set_quitid(val) bind(C, name="set_quitid") + use iso_c_binding + integer(c_long_long), value :: val + quitid = val + ! print*,'DATCOM_PTRS_MOD QUITID is:',quitid + end subroutine + + subroutine set_junk1(val) bind(C, name="set_junk1") + use iso_c_binding + integer(c_int), value :: val + junk1 = val + end subroutine + + subroutine set_junk2(val) bind(C, name="set_junk2") + use iso_c_binding + integer(c_int), value :: val + junk2 = val + end subroutine + +end module datcom_ptrs_mod diff --git a/map65/libm65/dcoord.f90 b/map65/libm65/dcoord.f90 index 5ef6877a..53924c9f 100644 --- a/map65/libm65/dcoord.f90 +++ b/map65/libm65/dcoord.f90 @@ -1,40 +1,61 @@ -SUBROUTINE DCOORD(A0,B0,AP,BP,A1,B1,A2,B2) - - implicit real*8 (a-h,o-z) -! Examples: -! 1. From ha,dec to az,el: -! call coord(pi,pio2-lat,0.,lat,ha,dec,az,el) -! 2. From az,el to ha,dec: -! call coord(pi,pio2-lat,0.,lat,az,el,ha,dec) -! 3. From ra,dec to l,b -! call coord(4.635594495,-0.504691042,3.355395488,0.478220215, -! ra,dec,l,b) -! 4. From l,b to ra,dec -! call coord(1.705981071d0,-1.050357016d0,2.146800277d0, -! 0.478220215d0,l,b,ra,dec) -! 5. From ecliptic latitude (eb) and longitude (el) to ra, dec: -! call coord(0.d0,0.d0,-pio2,pio2-23.443*pi/180,ra,dec,el,eb) - - SB0=sin(B0) - CB0=cos(B0) - SBP=sin(BP) - CBP=cos(BP) - SB1=sin(B1) - CB1=cos(B1) - SB2=SBP*SB1 + CBP*CB1*cos(AP-A1) - CB2=SQRT(1.D0-SB2**2) - B2=atan(SB2/CB2) - SAA=sin(AP-A1)*CB1/CB2 - CAA=(SB1-SB2*SBP)/(CB2*CBP) - CBB=SB0/CBP - SBB=sin(AP-A0)*CB0 - SA2=SAA*CBB-CAA*SBB - CA2=CAA*CBB+SAA*SBB - TA2O2=0.0 !Shut up compiler warnings. -db - IF(CA2.LE.0.D0) TA2O2=(1.D0-CA2)/SA2 - IF(CA2.GT.0.D0) TA2O2=SA2/(1.D0+CA2) - A2=2.D0*atan(TA2O2) - IF(A2.LT.0.D0) A2=A2+6.2831853071795864D0 - - RETURN -END SUBROUTINE DCOORD +module dcoord_mod + implicit none +contains + +subroutine dcoord(A0, B0, AP, BP, A1, B1, A2, B2) + implicit none + + !-------------------------------------------------------------------- + ! Arguments (all double precision) + !-------------------------------------------------------------------- + real(8), intent(in) :: A0, B0, AP, BP + real(8), intent(in) :: A1, B1 + real(8), intent(out) :: A2, B2 + + !-------------------------------------------------------------------- + ! Locals + !-------------------------------------------------------------------- + real(8) :: SB0, CB0, SBP, CBP, SB1, CB1 + real(8) :: SB2, CB2, SAA, CAA, CBB, SBB + real(8) :: SA2, CA2, TA2O2 + + !-------------------------------------------------------------------- + ! Compute sines and cosines + !-------------------------------------------------------------------- + SB0 = sin(B0) + CB0 = cos(B0) + SBP = sin(BP) + CBP = cos(BP) + SB1 = sin(B1) + CB1 = cos(B1) + + !-------------------------------------------------------------------- + ! Core spherical rotation + !-------------------------------------------------------------------- + SB2 = SBP*SB1 + CBP*CB1*cos(AP - A1) + CB2 = sqrt(1.0d0 - SB2**2) + B2 = atan(SB2 / CB2) + + SAA = sin(AP - A1) * CB1 / CB2 + CAA = (SB1 - SB2*SBP) / (CB2*CBP) + + CBB = SB0 / CBP + SBB = sin(AP - A0) * CB0 + + SA2 = SAA*CBB - CAA*SBB + CA2 = CAA*CBB + SAA*SBB + + !-------------------------------------------------------------------- + ! atan2-like reconstruction using stable formula + !-------------------------------------------------------------------- + TA2O2 = 0.0d0 + if (CA2 <= 0.0d0) TA2O2 = (1.0d0 - CA2) / SA2 + if (CA2 > 0.0d0) TA2O2 = SA2 / (1.0d0 + CA2) + + A2 = 2.0d0 * atan(TA2O2) + + if (A2 < 0.0d0) A2 = A2 + 6.2831853071795864d0 + +end subroutine dcoord + +end module dcoord_mod diff --git a/map65/libm65/debug_log.f90 b/map65/libm65/debug_log.f90 new file mode 100644 index 00000000..d91b969b --- /dev/null +++ b/map65/libm65/debug_log.f90 @@ -0,0 +1,42 @@ +module debug_log + implicit none + integer, save :: dbg_unit = -1 + logical, save :: dbg_opened = .false. + logical, save :: dbg_enabled = .false. ! master switch; set .true./.false. from run_m65 to enable/disable all dbg() output +contains + subroutine ensure_log_open() + if (.not. dbg_opened) then + open(newunit=dbg_unit, file='w3sz_debug.log', status='unknown', & + action='write', position='append') + dbg_opened = .true. + end if + end subroutine ensure_log_open + + subroutine dbg(msg) + character(len=*), intent(in) :: msg + if (.not. dbg_enabled) return + call ensure_log_open() + write(dbg_unit,'(A)') trim(msg) + flush(dbg_unit) + end subroutine dbg + + pure function itoa(i) result(s) + integer, intent(in) :: i + character(len=32) :: s + write(s,'(I0)') i + end function itoa + + pure function rtoa(x) result(s) + real, intent(in) :: x + character(len=64) :: s + write(s,'(G16.8)') x + end function rtoa + + pure function itoa8(i) result(s) + integer(8), intent(in) :: i + character(len=32) :: s + write(s,'(I0)') i + end function itoa8 + + +end module debug_log diff --git a/map65/libm65/decode0.f90 b/map65/libm65/decode0.f90 index 438079f1..26a90366 100644 --- a/map65/libm65/decode0.f90 +++ b/map65/libm65/decode0.f90 @@ -1,71 +1,200 @@ -subroutine decode0(dd,ss,savg,nstandalone) - - use timer_module, only: timer - parameter (NSMAX=60*96000) - - real*4 dd(4,NSMAX),ss(4,322,NFFT),savg(4,NFFT) - real*8 fcenter - integer hist(0:32768) - logical ldecoded - character mycall*12,hiscall*12,mygrid*6,hisgrid*6,datetime*20 - character mycall0*12,hiscall0*12,hisgrid0*6 - common/npar/fcenter,nutc,idphi,mousedf,mousefqso,nagain, & - ndepth,ndiskdat,neme,newdat,nfa,nfb,nfcal,nfshift, & - mcall3,nkeep,ntol,nxant,nrxlog,nfsample,nxpol,nmode, & - ndop00,nsave,max_drift,nhsym,mycall,mygrid,hiscall,hisgrid,datetime - common/early/nhsym1,nhsym2,ldecoded(32768) - common/decodes/ndecodes - data neme0/-99/,mcall3b/1/ - save - - call sec0(0,tquick) - call timer('decode0 ',0) - if(newdat.ne.0) then - nz=96000*nhsym/5.3833 - hist=0 - do i=1,nz - j1=min(abs(dd(1,i)),32768.0) - hist(j1)=hist(j1)+1 - j2=min(abs(dd(2,i)),32768.0) - hist(j2)=hist(j2)+1 - j3=min(abs(dd(3,i)),32768.0) - hist(j3)=hist(j3)+1 - j4=min(abs(dd(4,i)),32768.0) - hist(j4)=hist(j4)+1 - enddo - m=0 - do i=0,32768 - m=m+hist(i) - if(m.ge.2*nz) go to 10 - enddo -10 rmsdd=1.5*i - endif - ndphi=0 - if(iand(nrxlog,8).ne.0) ndphi=1 - - if(mycall.ne.mycall0 .or. hiscall.ne.hiscall0 .or. & - hisgrid.ne.hisgrid0 .or. mcall3.ne.0 .or. neme.ne.neme0) mcall3b=1 +module decode0_mod + implicit none +contains + + subroutine decode0(nstandalone) bind(C, name='decode0_') + + use iso_c_binding, only: c_int + use timer_module, only: timer + use npar_ptrs_mod + use datcom_ptrs_mod, only: NFFT, dd, dd_old, dd_use, ss, ss_old, savg, savg_old, ss_use, savg_use + use debug_log, only: dbg, itoa, rtoa + use sec_midn_mod, only: sec_midn + use map65a_mod + use stdout_channel_mod, only: write_stdout + use decodes_mod, only: ndecodes, nhsym1, nhsym2 + use sec0_mod, only:sec0 + + implicit none + + integer(c_int), intent(in) :: nstandalone + integer hist(0:32768) + integer i, j1, j2, j3, j4, m, mcall3b, ndphi, neme0, nsum + integer :: ndecdone + real :: tdec, tquick, rmsdd + integer nz + integer :: nhsym0 + integer :: newdat0 + character(len=128) :: line + character mycall0*12, hiscall0*12, hisgrid0*6 + logical :: first_mcall3b_check + + data neme0/-99/, mcall3b/0/, mycall0/' '/, hiscall0/' '/, hisgrid0/' '/ + data first_mcall3b_check/.true./ + + save + + ! The decoder owns the claimed parameters until this call returns. + nhsym0 = nhsym + newdat0 = newdat + + ! TEMP diagnostic 2026-09-10 for the missing-final-pass / incomplete- + ! data-set investigation. + call dbg('decode0: ENTRY at t=' // rtoa(sec_midn()) // & + ' nhsym0=' // itoa(nhsym0) // ' newdat0=' // itoa(newdat0) // & + ' manualDecodeFlag=' // itoa(manualDecodeFlag) // & + ' nagain=' // itoa(nagain) // ' ndiskdat=' // itoa(ndiskdat)) + + ! newdat is forced to 1 by decode() for every call (manual or + ! automatic); it does not by itself mean "the live buffers just + ! finished a fresh accumulation." nagain=1 marks a manual repeat + ! (Decode button / Find Delta Phi), which must not refresh dd_old + ! from a live buffer that may still be mid-fill. + if (newdat0 /= 0 .and. manualDecodeFlag == 0 .and. nagain == 0) then + dd_old = dd + ss_old = ss + savg_old = savg + call dbg('decode0: dd_old REFRESHED from live dd at t=' // rtoa(sec_midn()) // ' nhsym0=' // itoa(nhsym0)) + else + call dbg('decode0: dd_old NOT refreshed (reusing prior snapshot) at t=' // rtoa(sec_midn()) // & + ' nhsym0=' // itoa(nhsym0) // ' nagain=' // itoa(nagain)) + endif + + nkeep = 20 + + call sec0(0, tquick) + call timer('decode0 ', 0) - mycall0=mycall - hiscall0=hiscall - hisgrid0=hisgrid - neme0=neme - - call timer('map65a ',0) - call map65a(dd,ss,savg,newdat,nutc,fcenter,ntol,idphi,nfa,nfb, & - mousedf,mousefqso,nagain,ndecdone,nfshift,ndphi,max_drift, & - nfcal,nkeep,mcall3b,nsum,nsave,nxant,mycall,mygrid, & - neme,ndepth,nstandalone,hiscall,hisgrid,nhsym,nfsample, & - ndiskdat,nxpol,nmode,ndop00) - call timer('map65a ',1) - call timer('decode0 ',1) - - call sec0(1,tdec) - if(nhsym.eq.nhsym1) write(*,1010) nsum,nsave,nstandalone,nhsym,tdec -1010 format('<EarlyFinished>',3i4,i6,f6.2) - if(nhsym.eq.nhsym2) write(*,1012) nsum,nsave,nstandalone,nhsym,tdec,ndecodes -1012 format('<DecodeFinished>',3i4,i6,f6.2,i5) - flush(6) - - return -end subroutine decode0 + ! Always decode from the snapshot (dd_old/ss_old/savg_old) taken above, + ! never the live dd/ss/savg. The nhsym2 pass routinely runs past the + ! minute boundary (several seconds), and symspec_() on the GUI thread + ! resets/overwrites the live buffers for the next cycle unconditionally + ! as soon as new UDP data arrives -- with no lock between the two + ! threads. Without this, a still-running decode reads a mix of this + ! cycle's and next cycle's data for candidates it hasn't reached yet + ! in its frequency sweep. + dd_use => dd_old + ss_use => ss_old + savg_use => savg_old + + if (newdat0 .ne. 0 .or. manualDecodeFlag /= 0) then + nz = int( real(nrate_active, kind=real64) * nhsym0 / 5.3833_real64 ) + hist = 0 + do i = 1, nz + j1 = int(min(abs(dd_use(1, i)), 32768.0)) + hist(j1) = hist(j1) + 1 + j2 = int(min(abs(dd_use(2, i)), 32768.0)) + hist(j2) = hist(j2) + 1 + j3 = int(min(abs(dd_use(3, i)), 32768.0)) + hist(j3) = hist(j3) + 1 + j4 = int(min(abs(dd_use(4, i)), 32768.0)) + hist(j4) = hist(j4) + 1 + enddo + m = 0 + do i = 0, 32768 + m = m + hist(i) + if (m .ge. 2*nz) go to 10 + enddo +10 rmsdd = 1.5*i + endif + ndphi = 0 + if (iand(nrxlog, 8) .ne. 0) ndphi = 1 + + ! Seed mycall0/hiscall0/hisgrid0/neme0 from the real values on the + ! first call instead of blank sentinels, so the mismatch check below + ! only fires on a genuine later change, not on startup. + if (first_mcall3b_check) then + mycall0 = mycall + hiscall0 = hiscall + hisgrid0 = hisgrid + neme0 = neme + first_mcall3b_check = .false. + endif + + if (mycall .ne. mycall0 .or. hiscall .ne. hiscall0 .or. & + hisgrid .ne. hisgrid0 .or. mcall3 .ne. 0 .or. neme .ne. neme0) mcall3b = 1 + + mycall0 = mycall + hiscall0 = hiscall + hisgrid0 = hisgrid + neme0 = neme + + ! Manual decode: force a single nhsym2-style cycle and always emit DecodeFinished + if (manualDecodeFlag /= 0) then + nhsym0 = nhsym2 + call announce_decode_pass('manual') + + call timer('map65a ', 0) + call map65a(dd_use, newdat0, nutc, fcenter, ntol, idphi, nfa, nfb, & + mousedf, mousefqso, nagain, ndecdone, nfshift, ndphi, max_drift, & + nfcal, nkeep, mcall3b, nsum, nsave, nxant, mycall, mygrid, & + neme, ndepth, nstandalone, hiscall, hisgrid, nhsym0, nfsample, & + ndiskdat, nxpol, nmode, ndop00) + call timer('map65a ', 1) + call timer('decode0 ', 1) + + call sec0(1, tdec) + + write (line, '("<DecodeFinished>",3I4,I6,F6.2,I5,1X,I0)') & + nsum, nsave, nstandalone, nhsym0, tdec, ndecodes, active_request_id + call write_stdout(trim(line)//new_line('a')) + + call dbg('decode0: MANUAL path RETURNING at t=' // rtoa(sec_midn())) + + return + + else + + ! Normal wideband path: nhsym1 (EarlyFinished) + nhsym2 (DecodeFinished) + if (ndiskdat /= 0) then + call announce_decode_pass('disk') + else if (nhsym0 == nhsym1) then + call announce_decode_pass('early') + else if (nhsym0 == nhsym2) then + call announce_decode_pass('final') + else + call announce_decode_pass('unknown') + endif + call timer('map65a ', 0) + call map65a(dd_use, newdat0, nutc, fcenter, ntol, idphi, nfa, nfb, & + mousedf, mousefqso, nagain, ndecdone, nfshift, ndphi, max_drift, & + nfcal, nkeep, mcall3b, nsum, nsave, nxant, mycall, mygrid, & + neme, ndepth, nstandalone, hiscall, hisgrid, nhsym0, nfsample, & + ndiskdat, nxpol, nmode, ndop00) + call timer('map65a ', 1) + call timer('decode0 ', 1) + + call sec0(1, tdec) + + if (nhsym0 == nhsym1) then + write (line, '("<EarlyFinished>",3I4,I6,F6.2)') & + nsum, nsave, nstandalone, nhsym0, tdec + call write_stdout(trim(line)//new_line('a')) + end if + + ! A manual repeat decode (Decode button / Find Delta Phi) is always a + ! single, complete request regardless of nhsym, which only reflects + ! the automatic per-minute cycle and may never equal nhsym2 if no + ! automatic decode has run yet this session. + if (nhsym0 == nhsym2 .or. nagain /= 0) then + write (line, '("<DecodeFinished>",3I4,I6,F6.2,I5,1X,I0)') & + nsum, nsave, nstandalone, nhsym0, tdec, ndecodes, active_request_id + call write_stdout(trim(line)//new_line('a')) + end if + + call dbg('decode0: WIDEBAND path RETURNING at t=' // rtoa(sec_midn())) + + return + end if + end subroutine decode0 + + subroutine announce_decode_pass(pass_name) + use stdout_channel_mod, only: write_stdout + implicit none + + character(len=*), intent(in) :: pass_name + + call write_stdout('<Map65DecodePass> '//trim(pass_name)//new_line('a')) + end subroutine announce_decode_pass + +end module decode0_mod diff --git a/map65/libm65/decode1a.f90 b/map65/libm65/decode1a.f90 index 4219c004..691593fd 100644 --- a/map65/libm65/decode1a.f90 +++ b/map65/libm65/decode1a.f90 @@ -1,3 +1,7 @@ +module decode1a_mod + implicit none +contains + subroutine decode1a(dd,newdat,f0,nflip,mode65,nfsample,xpol, & mycall,hiscall,hisgrid,neme,ndepth,nqd,dphi,ndphi, & nutc,nkhz,ndf,ipol,ntol,sync2,a,dt,pol,nkv,nhist,nsum,nsave, & @@ -6,29 +10,72 @@ subroutine decode1a(dd,newdat,f0,nflip,mode65,nfsample,xpol, & ! Apply AFC corrections to a candidate JT65 signal, then decode it. use timer_module, only: timer - parameter (NMAX=60*96000) !Samples per 60 s - real*4 dd(4,NMAX) !92 MB: raw data from Linrad timf2 - complex cx(NMAX/64), cy(NMAX/64) !Data at 1378.125 samples/s - complex c5x(NMAX/256),c5y(NMAX/256) !Data at 344.53125 Hz + use iso_c_binding, only: c_ptr, c_loc + use, intrinsic :: ieee_arithmetic, only: ieee_is_finite + use debug_log + use afc65b_mod + use filbig_mod + use decode65b_mod + use s3avg_mod + use four2a_mod + use timf2_mod + use fil6521_mod + use twkfreq_xy_mod + use npar_ptrs_mod, only: nsmax_active + use sec_midn_mod, only: sec_midn + + implicit none + + real(real32), intent(in) :: dd(4, nsmax_active) !92 MB: raw data from Linrad timf2 + integer, intent(in) :: nflip, mode65, nfsample + logical, intent(in) :: xpol + character(len=12), intent(in) :: mycall, hiscall + character(len=6), intent(in) :: hisgrid + integer, intent(in) :: neme, ndepth, nqd, ndphi + real, intent(in) :: dphi + real(real64), intent(in) :: f0 + integer, intent(in) :: nutc, nkhz, ndf, ntol + integer, intent(inout) :: ipol + real, intent(inout):: sync2, a(5), dt, pol, qual + integer, intent(inout):: nkv, nhist, nsum, nsave, newdat + character(len=22), intent(out) :: decoded + + complex cx(nsmax_active/64), cy(nsmax_active/64) !Data at 1378.125 samples/s + complex c5x(nsmax_active/256), c5y(nsmax_active/256) !Data at 344.53125 Hz + complex c5a(512) complex z real s2(66,126) real s3(64,63),sy(63) - real a(5) - logical first,xpol - character decoded*22 - character mycall*12,hiscall*12,hisgrid*6 + + real :: aa, bb, ccfbest, dt00, flip + real :: dtbest, fsample, sq0, sqa, sqb, syncbest + integer :: i, i0, ihzdiff, j, jj, jjjmax, jjjmin, k, n, n5 + integer :: n6, nadd, nfft, nhz, nhz0, npol, nsym, nutc0, nz + logical first + +! real(kind=8) :: s2sum, s2mean +! integer :: ii,kk + +! real(c_double), dimension(*) :: dd data first/.true./,jjjmin/1000/,jjjmax/-1000/ - data nutc0/-999/,nhz0/-9999999/ + data nutc0/-999/,nhz0/-9999999/ save - + ! Mix sync tone to baseband, low-pass filter, downsample to 1378.125 Hz dt00=dt call timer('filbig ',0) - call filbig(dd,NMAX,f0,newdat,nfsample,xpol,cx,cy,n5) -! NB: cx, cy have sample rate 96000*77125/5376000 = 1378.125 Hz + + if (.not. ieee_is_finite(f0)) then + write(*,*) 'DECODE1A: bad f0, skipping filbig. f0=', f0 + return + end if + call filbig(dd, nsmax_active, f0, newdat, nfsample, xpol, cx, cy, n5) + call timer('filbig ',1) - if(mode65.eq.0) goto 900 + +! NB: cx, cy have sample rate 96000*77125/5376000 = 1378.125 Hz + if(mode65.eq.0) return sqa=0. sqb=0. do i=1,n5 @@ -50,10 +97,14 @@ subroutine decode1a(dd,newdat,f0,nflip,mode65,nfsample,xpol, & if(xpol) then c5y(:nadd)=0. call fil6521(cy,n5,c5y(nadd+1),n6) + else + c5y(:n6+nadd)=0. endif n6=n6+nadd - fsample=1378.125/4. + ! JT65 uses quarter-rate for symbol timing + fsample = 1378.125/4.0 + a(5)=dt00 i0=nint((a(5)+0.5)*fsample) - 2 + nadd if(i0.lt.1) then @@ -63,10 +114,30 @@ subroutine decode1a(dd,newdat,f0,nflip,mode65,nfsample,xpol, & endif nz=n6+1-i0 + ! 2026-09-12: instrumentation for the "identical anomalous dtbest despite + ! identical, legitimate dt00" investigation. dt00 itself is now confirmed + ! correct and consistent between working (nqd=1) and failing (nqd=0) + ! decodes of the same signal (traced to ccf65's lagpk, a genuine + ! correlation-peak lag, not a fallback constant) -- so the actual sample + ! window afc65b searches (c5x/c5y from i0 to i0+nz-1) is the next place to + ! look. Logging i0/nz and a cheap fingerprint (sum of magnitudes) of that + ! exact window so a live capture can show directly whether the underlying + ! data itself differs between a working and failing case. + if (nz .ge. 1 .and. i0 .ge. 1 .and. i0 + nz - 1 .le. nsmax_active/256) then + call dbg('decode1a: pre-afc65b at t=' // rtoa(sec_midn()) // & + ' i0=' // itoa(i0) // ' nz=' // itoa(nz) // ' n5=' // itoa(n5) // & + ' n6=' // itoa(n6) // ' dt00=' // rtoa(dt00) // & + ' c5x_sum_abs=' // rtoa(sum(abs(c5x(i0:i0+nz-1)))) // & + ' c5x_i0=' // rtoa(real(c5x(i0))) // ',' // rtoa(aimag(c5x(i0)))) + else + call dbg('decode1a: pre-afc65b at t=' // rtoa(sec_midn()) // & + ' i0=' // itoa(i0) // ' nz=' // itoa(nz) // ' (OUT OF RANGE, skipping fingerprint)') + endif + ! We're looking only at sync tone here... so why not downsample by another ! factor of 1/8, say? Should be a significant execution speed-up. ! Best fit for DF, f1, f2, pol - call afc65b(c5x(i0),c5y(i0),nz,fsample,nflip,ipol,xpol,ndphi,a,ccfbest,dtbest) +call afc65b(c5x(i0), c5y(i0), nz, fsample, nflip, ipol, xpol, ndphi, a, ccfbest, dtbest) pol=a(4)/57.2957795 aa=cos(pol) @@ -74,6 +145,13 @@ subroutine decode1a(dd,newdat,f0,nflip,mode65,nfsample,xpol, & sq0=aa*aa*sqa + bb*bb*sqb sync2=3.7*ccfbest/sq0 + ! TEMP diagnostic 2026-09-10 for the freq/time-sync-vs-false-decode investigation. + call dbg('decode1a: afc65b fit at t=' // rtoa(sec_midn()) // & + ' f0=' // rtoa(real(f0)) // ' dt00=' // rtoa(dt00) // ' dtbest=' // rtoa(dtbest) // & + ' ccfbest=' // rtoa(ccfbest) // ' a1(df)=' // rtoa(a(1)) // ' a2=' // rtoa(a(2)) // & + ' a3=' // rtoa(a(3)) // ' a4(pol_deg)=' // rtoa(a(4)) // ' sync2=' // rtoa(sync2) // & + ' nflip=' // itoa(nflip) // ' ipol=' // itoa(ipol)) + ! Apply AFC corrections to the time-domain signal ! Now we are back to using the 1378.125 Hz sample rate, enough to ! accommodate the full JT65C bandwidth. @@ -87,7 +165,9 @@ subroutine decode1a(dd,newdat,f0,nflip,mode65,nfsample,xpol, & nsym=126 nfft=512 - j=(dt00+dtbest+2.685)*1378.125 + j = (dt00 + dtbest + 2.685)*1378.125 +! fs_out = real(n5) / 60.0 ! actual sample rate from filbig +! j = (dt00 + dtbest + 2.685) * fs_out if(j.lt.0) j=0 @@ -98,7 +178,7 @@ subroutine decode1a(dd,newdat,f0,nflip,mode65,nfsample,xpol, & ! do n=1,mode65 do n=1,1 do i=1,nfft - j=min(j+1,NMAX/64) + j = min(j+1, nsmax_active/64) c5a(i)=aa*cx(j) + bb*cy(j) enddo call four2a(c5a,nfft,1,1,1) @@ -120,8 +200,22 @@ subroutine decode1a(dd,newdat,f0,nflip,mode65,nfsample,xpol, & flip=nflip call timer('dec65b ',0) + +! After filling s2(66,126), just before: +! call decode65b(...) + +!s2sum = 0.0d0 +!do kk = 1, nsym +! do ii = 1, 66 +! s2sum = s2sum + dble(s2(ii,kk)) +! end do +!end do + +!s2mean = s2sum / dble(66*nsym) + call decode65b(s2,flip,mycall,hiscall,hisgrid,mode65,neme,ndepth, & nqd,nkv,nhist,qual,decoded,s3,sy) + dt=dt00 + dtbest + 1.7 call timer('dec65b ',1) @@ -134,12 +228,13 @@ subroutine decode1a(dd,newdat,f0,nflip,mode65,nfsample,xpol, & nsave=mod(nsave-1,64)+1 npol=nint(57.296*pol) - call s3avg(nsave,mode65,nutc,nhz,xdt,npol,ntol,s3,nsum,nkv,decoded) + call s3avg(nsave,mode65,nutc,nhz,dt,npol,nflip,ntol,s3,nsum,nkv,decoded) syncbest=sync2 nhz0=nhz endif nutc0=nutc endif - -900 return + end subroutine decode1a + +end module decode1a_mod diff --git a/map65/libm65/decode65b.f90 b/map65/libm65/decode65b.f90 index 9b3ebccd..694cbccb 100644 --- a/map65/libm65/decode65b.f90 +++ b/map65/libm65/decode65b.f90 @@ -1,12 +1,32 @@ +module decode65b_mod + implicit none +contains + subroutine decode65b(s2,flip,mycall,hiscall,hisgrid,mode65,neme,ndepth, & nqd,nkv,nhist,qual,decoded,s3,sy) + + use deep65_mod + use extract_mod + use pr_mod + use setup65_mod + use debug_log, only: dbg, itoa + + real, intent(in) :: s2(66,126) + real, intent(out) :: s3(64,63), sy(63) + real, intent(in) :: flip + real, intent(inout) :: qual + integer, intent(in) :: mode65, neme, ndepth, nqd + integer, intent(inout) :: nhist + integer, intent(out) :: nkv + character(len=12), intent(in) :: mycall, hiscall + character(len=6), intent(in) :: hisgrid + character(len=22), intent(out) :: decoded - real s2(66,126) - real s3(64,63),sy(63) + integer :: nadd,ncount,i,j,k logical first,ltext - character decoded*22,deepmsg*22 - character mycall*12,hiscall*12,hisgrid*6 - common/prcom/pr(126),mdat(126),mref(126,2),mdat2(126),mref2(126,2) + character deepmsg*22 + integer :: mrs(63), mrs2(63) + data deepmsg/' '/ data first/.true./ save @@ -25,7 +45,13 @@ subroutine decode65b(s2,flip,mycall,hiscall,hisgrid,mode65,neme,ndepth, & enddo nadd=mode65 - call extract(s3,nadd,ncount,nhist,decoded,ltext) !Extract the message +! write(*,*) 'DECODE65B: flip=', flip, ' mode65=', mode65, ' ndepth=', ndepth, ' neme=', neme +! write(*,*) 'DECODE65B: nhist in=', nhist +! write(*,*) 'DECODE65B: first few s3(:,1) = ', s3(1:10,1) +! write(*,*) 'DECODE65B: mdat(1:10) = ', mdat(1:10) +! write(*,*) 'DECODE65B: mdat2(1:10) = ', mdat2(1:10) + + call extract(s3,nadd,ncount,nhist,decoded,ltext,mrs,mrs2) !Extract the message ! Suppress "birdie messages" and other garbage decodes: if(decoded(1:7).eq.'000AAA ') ncount=-1 if(decoded(1:7).eq.'0L6MWK ') ncount=-1 @@ -36,13 +62,36 @@ subroutine decode65b(s2,flip,mycall,hiscall,hisgrid,mode65,neme,ndepth, & decoded=' ' endif + ! TEMP diagnostic 2026-09-10 for the false-JT65-decode investigation. + call dbg('decode65b: extract() done, ncount=' // itoa(ncount) // ' nkv=' // itoa(nkv) // & + ' hard_decoded="' // trim(decoded) // '" nqd=' // itoa(nqd) // ' flip=' // itoa(nint(flip)) // & + ' ndepth=' // itoa(ndepth) // & + ' will_run_deep65=' // itoa(merge(1,0, ndepth.ge.1 .and. (nqd.eq.1 .or. flip.eq.1.0)))) + qual=0. if(ndepth.ge.1 .and. (nqd.eq.1 .or. flip.eq.1.0)) then - call deep65(s3,mode65,neme,flip,mycall,hiscall,hisgrid,deepmsg,qual) + call deep65(s3,mode65,neme,flip,mycall,hiscall,hisgrid,deepmsg,qual,mrs,mrs2) if(nqd.ne.1 .and. qual.lt.10.0) qual=0.0 if(ndepth.lt.2 .and. qual.lt.6.0) qual=0.0 endif - if(nkv.eq.0 .and. qual.ge.1.0) decoded=deepmsg + + ! Deep Search's AP guess overrides extract()'s hard decode whenever + ! qual.ge.1.0, regardless of nkv (whether extract() itself reported + ! success). A "successful" hard Reed-Solomon decode doesn't guarantee a + ! real message -- JT65's RS code has a nonzero false-positive rate, and a + ! qual.ge.1.0 Deep Search match is far more likely to be correct than a + ! false RS accept. This cutoff is not immune to a low-but-nonzero + ! marginal-qual false accept of its own; see the PR's false-decode-rate + ! discussion for known residual cases. + if (qual.ge.1.0) then + decoded=deepmsg + nkv=0 + endif + + call dbg('decode65b: final decoded="' // trim(decoded) // '" nkv=' // itoa(nkv) // ' qual=' // itoa(nint(qual))) return end subroutine decode65b + +end module decode65b_mod + diff --git a/map65/libm65/decode_request_mutex.cpp b/map65/libm65/decode_request_mutex.cpp new file mode 100644 index 00000000..999512e6 --- /dev/null +++ b/map65/libm65/decode_request_mutex.cpp @@ -0,0 +1,15 @@ +#include <mutex> + +namespace { +std::mutex request_mutex; +} + +extern "C" void lock_decode_requests() +{ + request_mutex.lock(); +} + +extern "C" void unlock_decode_requests() +{ + request_mutex.unlock(); +} diff --git a/map65/libm65/decodes_mod.f90 b/map65/libm65/decodes_mod.f90 new file mode 100644 index 00000000..3479fbb4 --- /dev/null +++ b/map65/libm65/decodes_mod.f90 @@ -0,0 +1,43 @@ +module decodes_mod + + use npar_ptrs_mod, only: nfft_active + + implicit none + + integer :: ndecodes = 0 + integer :: nhsym1 = 0, nhsym2 = 0 + logical, allocatable :: ldecoded(:) + ! JT65 bins already decoded in this accumulation cycle. Retaining them + ! across early/final calls avoids reporting the same signal twice; + ! select_unique_decodes() only compares results within one call. + logical, allocatable :: ljt65decoded(:) + integer :: mcall3a = 0 + +contains + + subroutine decodes_init() + ! (Re)allocate ldecoded/ljt65decoded to match the active symspec FFT length. + if (allocated(ldecoded)) then + if (size(ldecoded) /= nfft_active) then + deallocate(ldecoded) + end if + end if + + if (.not. allocated(ldecoded)) then + allocate(ldecoded(nfft_active)) + ldecoded = .false. + end if + + if (allocated(ljt65decoded)) then + if (size(ljt65decoded) /= nfft_active) then + deallocate(ljt65decoded) + end if + end if + + if (.not. allocated(ljt65decoded)) then + allocate(ljt65decoded(nfft_active)) + ljt65decoded = .false. + end if + end subroutine decodes_init + +end module decodes_mod diff --git a/map65/libm65/deep65.f90 b/map65/libm65/deep65.f90 index d684cd15..dfe83751 100644 --- a/map65/libm65/deep65.f90 +++ b/map65/libm65/deep65.f90 @@ -1,110 +1,222 @@ -subroutine deep65(s3,mode65,neme,flip,mycall,hiscall,hisgrid,decoded,qual) +module deep65_mod + implicit none - use timer_module, only: timer - parameter (MAXCALLS=10000,MAXRPT=63) - real s3(64,63) - character callsign*12,grid*4,message*22,hisgrid*6,c*1,ceme*3 - character*12 mycall,hiscall - character*22 decoded,bestmsg - character*22 testmsg(2*MAXCALLS + 2 + MAXRPT) - character*15 callgrid(MAXCALLS) - character*180 line - character*4 rpt(MAXRPT) - integer ncode(63,2*MAXCALLS + 2 + MAXRPT) - real pp(2*MAXCALLS + 2 + MAXRPT) - common/mrscom/ mrs(63),mrs2(63) - common/c3com/ mcall3a - data rpt/'-01','-02','-03','-04','-05', & - '-06','-07','-08','-09','-10', & - '-11','-12','-13','-14','-15', & - '-16','-17','-18','-19','-20', & - '-21','-22','-23','-24','-25', & - '-26','-27','-28','-29','-30', & - 'R-01','R-02','R-03','R-04','R-05', & - 'R-06','R-07','R-08','R-09','R-10', & - 'R-11','R-12','R-13','R-14','R-15', & - 'R-16','R-17','R-18','R-19','R-20', & - 'R-21','R-22','R-23','R-24','R-25', & - 'R-26','R-27','R-28','R-29','R-30', & - 'RO','RRR','73'/ - save + ! MAXCALLS/testmsg/ncode/callgrid/pp/ntot are module-scoped so that a + ! separate subroutine, build_call3_candidates() below, can be called once + ! eagerly from run_m65.f90 at startup and build the same cached candidate + ! list before the decoder ever needs it, instead of the first real decode + ! paying for it. + integer, parameter :: MAXRPT = 63 + integer, save :: MAXCALLS = 0, narr = 0, ntot = 0 + character(len=22), allocatable, save :: testmsg(:) + character(len=15), allocatable, save :: callgrid(:) + integer, allocatable, save :: ncode(:,:) + real, allocatable, save :: pp(:) + character(len=12), save :: cached_mycall = '', cached_hiscall = '' + character(len=6), save :: cached_hisgrid = '' + integer, save :: cached_neme = 0 - if(mcall3a.eq.0) go to 30 - - call timer('deep65a ',0) - mcall3a=0 - rewind 23 - k=0 - icall=0 - do n=1,MAXCALLS - if(n.eq.1) then - callsign=hiscall - do i=4,12 - if(ichar(callsign(i:i)).eq.0) callsign(i:i)=' ' - enddo - grid=hisgrid(1:4) - if(ichar(grid(3:3)).eq.0) grid(3:3)=' ' - if(ichar(grid(4:4)).eq.0) grid(4:4)=' ' - else - read(23,1002,end=20) line -1002 format (A80) - if(line(1:4).eq.'ZZZZ') go to 20 - if(line(1:2).eq.'//') go to 10 - i1=index(line,',') - if(i1.lt.4) go to 10 - i2=index(line(i1+1:),',') - if(i2.lt.5) go to 10 - i2=i2+i1 - i3=index(line(i2+1:),',') - if(i3.lt.1) i3=index(line(i2+1:),' ') - i3=i2+i3 - callsign=line(1:i1-1) - grid=line(i1+1:i2-1) - ceme=line(i2+1:i3-1) - if(neme.eq.1 .and. ceme.ne.'EME') go to 10 - endif +contains + + ! Encoding the full CALL3.TXT list is expensive. Reuse candidates only + ! while the file and their station settings match. + subroutine build_call3_candidates(mycall, hiscall, hisgrid, neme) + use decodes_mod, only: mcall3a + use encode65_mod + use debug_log, only: dbg, itoa, rtoa + use sec_midn_mod, only: sec_midn + use timer_module, only: timer + implicit none + + character(len=12), intent(in) :: mycall, hiscall + character(len=6), intent(in) :: hisgrid + integer, intent(in) :: neme + + character callsign*12, grid*4, message*22, ceme*3 + character(len=180) line + character(len=4) :: rpt(MAXRPT) + integer :: nlines_in_file, ios + integer :: i, i1, i2, i3, icall, k, j1, j2, j3, j4, m, mz, n + + data rpt/'-01','-02','-03','-04','-05', & + '-06','-07','-08','-09','-10', & + '-11','-12','-13','-14','-15', & + '-16','-17','-18','-19','-20', & + '-21','-22','-23','-24','-25', & + '-26','-27','-28','-29','-30', & + 'R-01','R-02','R-03','R-04','R-05', & + 'R-06','R-07','R-08','R-09','R-10', & + 'R-11','R-12','R-13','R-14','R-15', & + 'R-16','R-17','R-18','R-19','R-20', & + 'R-21','R-22','R-23','R-24','R-25', & + 'R-26','R-27','R-28','R-29','R-30', & + 'RO','RRR','73'/ + save rpt + + call dbg('build_call3_candidates: entry, mcall3a=' // itoa(mcall3a) // ' cached ntot=' // itoa(ntot)) + + if (mcall3a.eq.0 .and. allocated(testmsg) .and. & + mycall.eq.cached_mycall .and. hiscall.eq.cached_hiscall .and. & + hisgrid.eq.cached_hisgrid .and. neme.eq.cached_neme) return + + k = 0 + ntot = 0 + + call timer('deep65a ', 0) + mcall3a = 0 + + ! CALL3.TXT is normally already open on unit 23 by the time map65a() + ! calls deep65() (see map65a.f90's own open() near its top, run before + ! every decode). When this is called eagerly from run_m65.f90, before + ! any decode has happened, nothing has opened it yet -- open it here + ! too. Re-opening an already-open unit on the same file is harmless. + !### Should use AppDir! ### + open (23, file='CALL3.TXT', status='unknown') + + ! Count actual lines in CALL3.TXT so the candidate-list arrays can be + ! sized to fit the whole file, then size arrays large enough for every + ! line to become a real candidate, generously covering the n=1 + ! (hiscall) special case that can expand into up to MAXRPT+1 + ! report-message variants. + rewind 23 + nlines_in_file = 0 + do + read(23, '(A)', iostat=ios) line + if (ios /= 0) exit + nlines_in_file = nlines_in_file + 1 + end do + rewind 23 + + MAXCALLS = max(nlines_in_file + 1, 100) ! +1 for the n=1 hiscall slot + narr = 2*(MAXCALLS + MAXRPT + 1) + + if (allocated(testmsg)) deallocate(testmsg) + if (allocated(ncode)) deallocate(ncode) + if (allocated(callgrid)) deallocate(callgrid) + if (allocated(pp)) deallocate(pp) + allocate(testmsg(narr)) + allocate(ncode(63,narr)) + allocate(callgrid(MAXCALLS)) + allocate(pp(narr)) - icall=icall+1 - j1=index(mycall,' ') - 1 - if(j1.le.-1) j1=12 - if(j1.lt.3) j1=6 - j2=index(callsign,' ') - 1 - if(j2.le.-1) j2=12 - if(j2.lt.3) j2=6 - j3=index(mycall,'/') ! j3>0 means compound mycall - j4=index(callsign,'/') ! j4>0 means compound hiscall - callgrid(icall)=callsign(1:j2) - - mz=1 + call dbg('build_call3_candidates: rebuilding candidate list, nlines_in_file=' // itoa(nlines_in_file) // & + ' MAXCALLS=' // itoa(MAXCALLS)) + call dbg('build_call3_candidates: candidate-encoding loop STARTING at t=' // rtoa(sec_midn())) + + k=0 + icall=0 + do n=1,MAXCALLS + if(n.eq.1) then + callsign=hiscall + do i=4,12 + if(ichar(callsign(i:i)).eq.0) callsign(i:i)=' ' + enddo + grid=hisgrid(1:4) + if(ichar(grid(3:3)).eq.0) grid(3:3)=' ' + if(ichar(grid(4:4)).eq.0) grid(4:4)=' ' + else + read(23,1002,end=20) line +1002 format (A80) + if(line(1:4).eq.'ZZZZ') go to 20 + if(line(1:2).eq.'//') go to 10 + i1=index(line,',') + if(i1.lt.4) go to 10 + i2=index(line(i1+1:),',') + if(i2.lt.5) go to 10 + i2=i2+i1 + i3=index(line(i2+1:),',') + if(i3.lt.1) i3=index(line(i2+1:),' ') + i3=i2+i3 + callsign=line(1:i1-1) + grid=line(i1+1:i2-1) + ceme=line(i2+1:i3-1) + if(neme.eq.1 .and. ceme.ne.'EME') go to 10 + endif + + icall=icall+1 + j1=index(mycall,' ') - 1 + if(j1.le.-1) j1=12 + if(j1.lt.3) j1=6 + j2=index(callsign,' ') - 1 + if(j2.le.-1) j2=12 + if(j2.lt.3) j2=6 + j3=index(mycall,'/') ! j3>0 means compound mycall + j4=index(callsign,'/') ! j4>0 means compound hiscall + callgrid(icall)=callsign(1:j2) + + mz=1 ! Allow MyCall + HisCall + rpt (?) - if(n.eq.1 .and. j3.lt.1 .and. j4.lt.1 .and. callsign(1:6).ne.' ') & - mz=MAXRPT+1 - do m=1,mz - if(m.gt.1) grid=rpt(m-1) - if(j3.lt.1 .and.j4.lt.1) callgrid(icall)=callsign(1:j2)//' '//grid - message=mycall(1:j1)//' '//callgrid(icall) - k=k+1 - testmsg(k)=message - call encode65(message,ncode(1,k)) - + if(n.eq.1 .and. j3.lt.1 .and. j4.lt.1 .and. callsign(1:6).ne.' ') & + mz=MAXRPT+1 + do m=1,mz + if(m.gt.1) grid=rpt(m-1) + if(j3.lt.1 .and.j4.lt.1) callgrid(icall)=callsign(1:j2)//' '//grid + message=mycall(1:j1)//' '//callgrid(icall) + k=k+1 + testmsg(k)=message + call encode65(message,ncode(1,k)) + ! Insert CQ message - if(j4.lt.1) callgrid(icall)=callsign(1:j2)//' '//grid - message='CQ '//callgrid(icall) - k=k+1 - testmsg(k)=message - call encode65(message,ncode(1,k)) - enddo -10 continue - enddo + if(j4.lt.1) callgrid(icall)=callsign(1:j2)//' '//grid + message='CQ '//callgrid(icall) + k=k+1 + testmsg(k)=message + call encode65(message,ncode(1,k)) + enddo +10 continue + enddo + +20 continue + ntot=k + cached_mycall=mycall + cached_hiscall=hiscall + cached_hisgrid=hisgrid + cached_neme=neme + call timer('deep65a ',1) + call dbg('build_call3_candidates: candidate-encoding loop DONE at t=' // rtoa(sec_midn()) // ' ntot=' // itoa(ntot)) + end subroutine build_call3_candidates -20 continue - ntot=k - call timer('deep65a ',1) +subroutine deep65(s3,mode65,neme,flip,mycall,hiscall,hisgrid,decoded,qual,mrs,mrs2) + + use timer_module, only: timer + use debug_log, only: dbg, itoa + implicit none -30 continue + real, intent(in) :: s3(64,63) + integer, intent(in) :: mode65, neme + real, intent(in) :: flip + character(len=12), intent(in) :: mycall, hiscall + character(len=6), intent(in) :: hisgrid + character(len=22), intent(out) :: decoded + real, intent(out) :: qual + integer, intent(in) :: mrs(63), mrs2(63) + + character(len=22) bestmsg + character c*1 + integer i,ip1,j,k + real bias,p,p1,p2,ref,ref0,sum + integer :: n_g4swx, n_dg2ycb + data ip1/1/ ! Default safety, in case ntot ends up 0 the very first time + save + + call build_call3_candidates(mycall, hiscall, hisgrid, neme) + + ! TEMP diagnostic 2026-09-10: confirm whether the currently-loaded candidate + ! list (whether just rebuilt or reused from cache) actually contains the + ! callsigns known to be in CALL3.TXT right now. + n_g4swx = 0 + n_dg2ycb = 0 + do k = 1, ntot + if (index(testmsg(k), 'G4SWX') > 0) n_g4swx = n_g4swx + 1 + if (index(testmsg(k), 'DG2YCB') > 0) n_dg2ycb = n_dg2ycb + 1 + end do + call dbg('deep65: about to score, ntot=' // itoa(ntot) // & + ' n_g4swx_in_list=' // itoa(n_g4swx) // & + ' n_dg2ycb_in_list=' // itoa(n_dg2ycb)) call timer('deep65b ',0) ref0=0. do j=1,63 + ref0=ref0 + s3(mrs(j),j) enddo @@ -141,7 +253,7 @@ subroutine deep65(s3,mode65,neme,flip,mycall,hiscall,hisgrid,decoded,qual) if(mode65.ge.4) bias=max(1.04*p2,0.505) if(p2.eq.p1 .and. p1.ne.-1.e30) then - open(77,file='error.log',status='unknown',access='append') + open(77, file='error.log', status='unknown', position='append') write(77,*) p1,p2,ip1,bestmsg close(77) endif @@ -159,6 +271,11 @@ subroutine deep65(s3,mode65,neme,flip,mycall,hiscall,hisgrid,decoded,qual) endif decoded(22:22)=c + ! TEMP diagnostic 2026-09-10. + call dbg('deep65: result ip1=' // itoa(ip1) // ' p1=' // itoa(nint(100*p1)) // & + ' p2=' // itoa(nint(100*p2)) // ' bias=' // itoa(nint(100*bias)) // & + ' qual=' // itoa(nint(qual)) // ' bestmsg="' // trim(testmsg(max(ip1,1))) // '"') + ! Make sure everything is upper case. do i=1,22 if(decoded(i:i).ge.'a' .and. decoded(i:i).le.'z') & @@ -168,3 +285,5 @@ subroutine deep65(s3,mode65,neme,flip,mycall,hiscall,hisgrid,decoded,qual) return end subroutine deep65 + +end module deep65_mod diff --git a/map65/libm65/deg2grid.f90 b/map65/libm65/deg2grid.f90 index 9ca3602f..442648fc 100644 --- a/map65/libm65/deg2grid.f90 +++ b/map65/libm65/deg2grid.f90 @@ -1,30 +1,55 @@ -subroutine deg2grid(dlong0,dlat,grid) - - real dlong !West longitude (deg) - real dlat !Latitude (deg) - character grid*6 - - dlong=dlong0 - if(dlong.lt.-180.0) dlong=dlong+360.0 - if(dlong.gt.180.0) dlong=dlong-360.0 - -! Convert to units of 5 min of longitude, working east from 180 deg. - nlong=60.0*(180.0-dlong)/5.0 - n1=nlong/240 !20-degree field - n2=(nlong-240*n1)/24 !2 degree square - n3=nlong-240*n1-24*n2 !5 minute subsquare - grid(1:1)=char(ichar('A')+n1) - grid(3:3)=char(ichar('0')+n2) - grid(5:5)=char(ichar('a')+n3) - -! Convert to units of 2.5 min of latitude, working north from -90 deg. - nlat=60.0*(dlat+90)/2.5 - n1=nlat/240 !10-degree field - n2=(nlat-240*n1)/24 !1 degree square - n3=nlat-240*n1-24*n2 !2.5 minuts subsquare - grid(2:2)=char(ichar('A')+n1) - grid(4:4)=char(ichar('0')+n2) - grid(6:6)=char(ichar('a')+n3) - - return +module deg2grid_mod + implicit none +contains + +subroutine deg2grid(dlong0, dlat, grid) + implicit none + + !-------------------------------------------------------------------- + ! Arguments + !-------------------------------------------------------------------- + real, intent(in) :: dlong0 ! West longitude (deg) + real, intent(in) :: dlat ! Latitude (deg) + character(len=6), intent(out) :: grid ! Maidenhead grid + + !-------------------------------------------------------------------- + ! Locals + !-------------------------------------------------------------------- + real :: dlong + integer :: nlong, nlat + integer :: n1, n2, n3 + + !-------------------------------------------------------------------- + ! Normalize longitude to [-180, 180] + !-------------------------------------------------------------------- + dlong = dlong0 + if (dlong < -180.0) dlong = dlong + 360.0 + if (dlong > 180.0) dlong = dlong - 360.0 + + !-------------------------------------------------------------------- + ! Longitude → grid characters 1,3,5 + !-------------------------------------------------------------------- + nlong = 60.0 * (180.0 - dlong) / 5.0 + n1 = nlong / 240 ! 20-degree field + n2 = (nlong - 240*n1) / 24 ! 2-degree square + n3 = nlong - 240*n1 - 24*n2 ! 5-minute subsquare + + grid(1:1) = char(ichar('A') + n1) + grid(3:3) = char(ichar('0') + n2) + grid(5:5) = char(ichar('a') + n3) + + !-------------------------------------------------------------------- + ! Latitude → grid characters 2,4,6 + !-------------------------------------------------------------------- + nlat = 60.0 * (dlat + 90.0) / 2.5 + n1 = nlat / 240 ! 10-degree field + n2 = (nlat - 240*n1) / 24 ! 1-degree square + n3 = nlat - 240*n1 - 24*n2 ! 2.5-minute subsquare + + grid(2:2) = char(ichar('A') + n1) + grid(4:4) = char(ichar('0') + n2) + grid(6:6) = char(ichar('a') + n3) + end subroutine deg2grid + +end module deg2grid_mod diff --git a/map65/libm65/demod64a.f90 b/map65/libm65/demod64a.f90 index 3b8ee03c..40160cab 100644 --- a/map65/libm65/demod64a.f90 +++ b/map65/libm65/demod64a.f90 @@ -1,4 +1,8 @@ -subroutine demod64a(s3,nadd,mrsym,mrprob,mr2sym,mr2prob,ntest,nlow) +module demod64a_mod + implicit none +contains + +subroutine demod64a(s3,nadd,mrsym,mrprob,mr2sym,mr2prob,ntest,nlow,mrs,mrs2) ! Demodulate the 64-bin spectra for each of 63 symbols in a frame. @@ -8,12 +12,21 @@ subroutine demod64a(s3,nadd,mrsym,mrprob,mr2sym,mr2prob,ntest,nlow) ! mr2sym second most likely symbol value ! mrprob probability that mrsym was the transmitted value ! mr2prob probability that mr2sym was the transmitted value +! mrs most reliable symbol value (1-based, for deep search) +! mrs2 second most likely symbol value (1-based, for deep search) + use iso_fortran_env, only: real32, real64 + implicit none + + real(real32), intent(in) :: s3(64,63) + integer, intent(in) :: nadd + integer, intent(out) :: mrsym(63), mrprob(63) + integer, intent(out) :: mr2sym(63), mr2prob(63) + integer, intent(out) :: ntest, nlow + integer, intent(out) :: mrs(63), mrs2(63) - implicit real*8 (a-h,o-z) - real*4 s3(64,63) - real*8 fs(64) - integer mrsym(63),mrprob(63),mr2sym(63),mr2prob(63) - common/mrscom/ mrs(63),mrs2(63) + real(real64) fs(64) + integer :: i,i1,i2,j + real(real64) ::afac,scale,ave,s1,s2,p2,psum,x,fsum,p1,sum afac=1.1 * float(nadd)**0.64 scale=255.999 @@ -75,3 +88,5 @@ subroutine demod64a(s3,nadd,mrsym,mrprob,mr2sym,mr2prob,ntest,nlow) return end subroutine demod64a + +end module demod64a_mod diff --git a/map65/libm65/display.f90 b/map65/libm65/display.f90 index b5ced07c..901313c8 100644 --- a/map65/libm65/display.f90 +++ b/map65/libm65/display.f90 @@ -1,106 +1,165 @@ -subroutine display(nkeep,ftol) +module display_mod + implicit none +contains - parameter (MAXLINES=400,MX=400,MAXCALLS=500) - integer indx(MAXLINES),indx2(MX) - character*83 line(MAXLINES),line2(MX),line3(MAXLINES) - character out*63,out0*63,cfreq0*3 ! was 57,57,3 - character*6 callsign,callsign0 - character*12 freqcall(MAXCALLS) - real freqkHz(MAXLINES) - integer utc(MAXLINES),utc2(MX),utcz - real*8 f0 - save +subroutine display(nkeep, ftol) + use stdout_channel_mod, only: write_stdout + use iso_fortran_env, only: real64 + use indexx_mod, only: indexx + use debug_log, only: dbg, itoa, rtoa + use sec_midn_mod, only: sec_midn + implicit none - character(len=83) :: livecq2 - character(len=83) :: livecq3 + ! Arguments + integer, intent(in) :: nkeep + real, intent(in) :: ftol + ! Parameters + integer, parameter :: MAXLINES = 400 + integer, parameter :: MX = 400 + integer, parameter :: MAXCALLS = 500 + + ! Locals + integer :: indx(MAXLINES), indx2(MX) + character(len=83) :: line(MAXLINES), line2(MX), line3(MAXLINES) + character(len=63) :: out, out0 + character(len=3) :: cfreq0 + character(len=6) :: callsign, callsign0 + ! N6NU 2026-05-24: bumped 12 ? 18 to carry the 5-char ndf (signed + ! Hz offset within kHz) alongside cfreq0 in the "&" bandmap line. + ! The C++ overlay handler (mainwindow.cpp processStdOut) reads + ! both fields and places the tick at nkHz + ndf/1000 instead of + ! integer kHz, which was up to �500 Hz off on signals with + ! non-zero ndf. + character(len=18) :: freqcall(MAXCALLS) + + real :: freqkHz(MAXLINES) + integer :: utc(MAXLINES), utc2(MX), utcz + real(real64) :: f0 + + character(len=83) :: livecq2, livecq3 + character(len=128) :: linenew + character(len=64) :: linenew2 integer :: io_status integer :: ndf, nh, nm + integer :: i, j, j0, k, k3, kz + integer :: nz, nage, iage, nquad + integer :: i0, i1, i2, len, nc, m, nstart + + ! Initialize some scalars/arrays defensively + out0 = ' ' + cfreq0 = ' ' + callsign0 = ' ' + freqcall = ' ' + + ! TEMP diagnostic 2026-09-10 for the "decode reaches map65_rx.log but not + ! the Messages window" investigation -- this is the entry point for the + ! ENTIRE "@"/"&" (Messages/Band Map window) pipeline; nothing gets to + ! those windows except through here. + call dbg('display: ENTRY at t=' // rtoa(sec_midn()) // ' nkeep=' // itoa(nkeep)) - out0=' ' + !------------------ Read and filter valid lines --------------------- rewind(26) + nz = 0 - do i=1,MAXLINES + do i = 1, MAXLINES read(26,1010,end=10) line(i) -1010 format(a83) ! was a77 - read(line(i), 1020, iostat=io_status) f0, ndf, nh, nm +1010 format(a83) + read(line(i),1020,iostat=io_status) f0, ndf, nh, nm 1020 format(f8.3,i5,25x,i3,i2) - if (io_status /= 0) then - ! Handle error: skip - continue - end if - utc(i)=60*nh + nm - freqkHz(i)=1000.d0*(f0-144.d0) + 0.001d0*ndf + + if (io_status /= 0) cycle + + utc(i) = 60*nh + nm + freqkHz(i) = 1000.d0*(f0 - 144.d0) + 0.001d0*ndf enddo 10 backspace(26) - nz=i-1 - utcz=utc(nz) + nz = i -1 + call dbg('display: read from unit 26, raw record count nz=' // itoa(nz)) + if (nz >= 1) utcz = utc(nz) nz=nz-1 - if(nz.lt.1) go to 999 - nquad=max(nkeep/4,3) - do i=1,nz - nage=utcz-utc(i) - if(nage.lt.0) nage=nage+1440 - iage=nage/nquad - write(line(i)(79:80),1021) iage ! was 73:74 + if (nz < 1) then + call dbg('display: EARLY RETURN, nz<1 after decrement -- no records to emit') + return + endif + nquad = max(nkeep/4, 3) + do i = 1, nz + nage = utcz - utc(i) + if (nage < 0) nage = nage + 1440 + iage = nage / nquad + write(line(i)(79:80),1021) iage 1021 format(i2) enddo - nage=utcz-utc(1) - if(nage.lt.0) nage=nage+1440 - if(nage.gt.nkeep) then - do i=1,nz - nage=utcz-utc(i) - if(nage.lt.0) nage=nage+1440 - if(nage.le.nkeep) go to 20 + nage = utcz - utc(1) + if (nage < 0) nage = nage + 1440 + if (nage > nkeep) then + do i = 1, nz + nage = utcz - utc(i) + if (nage < 0) nage = nage + 1440 + if (nage <= nkeep) go to 20 enddo -20 i0=i - nz=nz-i0+1 +20 i0 = i + nz = nz - i0 + 1 rewind(26) - if(nz.lt.1) go to 999 - do i=1,nz - j=i+i0-1 - line(i)=line(j) - utc(i)=utc(j) - freqkHz(i)=freqkHz(j) + if (nz < 1) return + do i = 1, nz + j = i + i0 - 1 + line(i) = line(j) + utc(i) = utc(j) + freqkHz(i) = freqkHz(j) write(26,1022) line(i) -1022 format(a83) ! was a77 +1022 format(a83) enddo + ! Rewriting fewer records than the file previously held does not + ! shrink it -- the old, longer tail stays on disk past this point. + ! Without truncating here, a later rewind+read pass reads straight + ! through into that stale leftover data and resurrects entries this + ! trim was supposed to drop for good, causing unbounded growth of + ! the Messages window over a long session regardless of nkeep. + ! endfile leaves the file positioned after the EOF marker it just + ! wrote, and Fortran forbids further sequential I/O from there + ! without repositioning first -- backspace moves back onto that + ! marker so the next append (map65a.f90/q65b.F90) can write there. + endfile(26) + backspace(26) endif - call flush(26) - call indexx(freqkHz,nz,indx) + flush(26) + call indexx(freqkHz, nz, indx) - nstart=1 - k3=0 - k=1 - m=indx(1) - if(m.lt.1 .or. m.gt.MAXLINES) then - print*,'Error in display.f90: ',nz,m - m=1 + nstart = 1 + k3 = 0 + k = 1 + m = indx(1) + + if (m < 1 .or. m > MAXLINES) then + write(linenew,'(A,1X,I0,1X,I0)') 'Error in display.f90:', nz, m + call write_stdout(trim(linenew)//new_line('a')) + m = 1 endif - line2(1)=line(m) - utc2(1)=utc(m) - do i=2,nz - j0=indx(i-1) - j=indx(i) - if(freqkHz(j)-freqkHz(j0).gt.2.0*ftol) then - if(nstart.eq.0) then - k=k+1 - line2(k)="" - utc2(k)=-1 + line2(1) = line(m) + utc2(1) = utc(m) + do i = 2, nz + j0 = indx(i-1) + j = indx(i) + if (freqkHz(j) - freqkHz(j0) > 2.0*ftol) then + if (nstart == 0) then + k = k + 1 + line2(k) = "" + utc2(k) = -1 endif - kz=k + kz = k if(nstart.eq.1) then - call indexx(float(utc2(1:kz)),kz,indx2) + call indexx(float(utc2(1:kz)), kz, indx2) k3=0 - do k=1,kz - k3=min(k3+1,400) - line3(k3)=line2(indx2(k)) - enddo - nstart=0 + do k = 1, kz + k3 = min(k3+1, MAXLINES) + line3(k3) = line2(indx2(k)) + enddo + nstart = 0 else call indexx(float(utc2(1:kz)),kz,indx2) do k=1,kz @@ -108,77 +167,93 @@ subroutine display(nkeep,ftol) line3(k3)=line2(indx2(k)) enddo endif - k=0 + k= 0 endif - if(i.eq.nz) then - k=k+1 - line2(k)="" - utc2(k)=-1 + if (i == nz) then + k = k + 1 + line2(k) = "" + utc2(k) = -1 endif - k=k+1 - line2(k)=line(j) - utc2(k)=utc(j) + k = k + 1 + line2(k) = line(j) + utc2(k) = utc(j) j0=j enddo - kz=k - call indexx(float(utc2(1:kz)),kz,indx2) - do k=1,kz - k3=min(k3+1,400) - line3(k3)=line2(indx2(k)) + kz = k + call indexx(float(utc2(1:kz)), kz, indx2) + do k = 1, kz + k3 = min(k3+1, MAXLINES) + line3(k3) = line2(indx2(k)) enddo rewind 19 rewind 20 cfreq0=' ' - nc=0 + nc = 0 callsign0=' ' - do k=1,k3 - out=line3(k)(1:13)//line3(k)(28:31)//line3(k)(39:45)// & - line3(k)(35:38)//line3(k)(46:80) ! was 46:74 - livecq2=line3(k) - if(out(6:8).ne.' ') then - cfreq0=out(6:8) + call dbg('display: about to walk k3=' // itoa(k3) // ' sorted records for "@" emission') + do k = 1, k3 + out = line3(k)(1:13)//line3(k)(28:31)//line3(k)(39:45)// & + line3(k)(35:38)//line3(k)(46:80) + livecq2 = line3(k) + if (out(6:8) /= ' ') then + cfreq0 = out(6:8) ! Suppress listing duplicate (same time, decoded message, and frequency) - if(out(19:22).ne.out0(19:22) .or. out(31:55).ne.out0(31:55) .or. & - out(6:8).ne.out0(6:8)) then - livecq3 = out(1:61) // ' ' // livecq2(23:27) // ' ' // livecq2(79:83) ! was 1:55 and 73:77 - write(*,1030) livecq3 -1030 format('@',a83) ! was a77 - out0=out + if (out(19:22) /= out0(19:22) .or. out(31:55) /= out0(31:55) .or. & + out(6:8) /= out0(6:8)) then + livecq3 = out(1:61)//' '//livecq2(23:27)//' '//livecq2(79:83) + write(linenew,'("@",A)') trim(livecq3) + call write_stdout(trim(linenew)//new_line('a')) + call dbg('display: k=' // itoa(k) // ' "@" EMITTED freq=' // out(6:8) // & + ' utc=' // out(19:22) // ' msg="' // trim(out(31:55)) // '"') + out0 = out + else + call dbg('display: k=' // itoa(k) // ' "@" SUPPRESSED (matches out0) freq=' // out(6:8) // & + ' utc=' // out(19:22) // ' msg="' // trim(out(31:55)) // & + '" -- out0 was freq=' // out0(6:8) // ' utc=' // out0(19:22) // & + ' msg="' // trim(out0(31:55)) // '"') endif - i1=index(out(31:),' ') - callsign=out(i1+31:) - i2=index(callsign,' ') - if(i2.gt.1) callsign(i2:)=' ' - if(callsign.ne.' ' .and. callsign.ne.callsign0) then - len=i2-1 - if(len.lt.0) len=6 - if(len.ge.3) then !Omit short "callsigns" - if(nc.lt.MAXCALLS) nc=nc+1 - freqcall(nc)=cfreq0//' '//callsign//line3(k)(79:80) ! was 73:74 + i1 = index(out(31:), ' ') + callsign = out(i1+31:) + i2 = index(callsign, ' ') + if (i2 > 1) callsign(i2:) = ' ' + if (callsign /= ' ' .and. callsign /= callsign0) then + len = i2 - 1 + if (len < 0) len = 6 + if (len >= 3) then + if (nc < MAXCALLS) nc = nc + 1 + freqcall(nc) = cfreq0//line3(k)(9:13)//' '//callsign//line3(k)(79:80) callsign0=callsign endif endif - if(callsign.ne.' ' .and. callsign.eq.callsign0) then - freqcall(nc)=cfreq0//' '//callsign//line3(k)(79:80) ! was 73:74 + if (callsign /= ' ' .and. callsign == callsign0) then + if (nc > 0 .and. nc <= MAXCALLS) then + freqcall(nc) = cfreq0//line3(k)(9:13)//' '//callsign//line3(k)(79:80) + endif endif + else + call dbg('display: k=' // itoa(k) // ' SKIPPED entirely (out(6:8) blank -- not a frequency record)') endif enddo + call dbg('display: done, nc(bandmap entries)=' // itoa(nc)) + +if(nc.lt.MAXCALLS) nc=nc+1 +freqcall(nc)=' ' + +if(nc.lt.MAXCALLS) nc=nc+1 +freqcall(nc)=' ' - if(nc.lt.MAXCALLS) nc=nc+1 - freqcall(nc)=' ' - if(nc.lt.MAXCALLS) nc=nc+1 - freqcall(nc)=' ' - freqcall(nc+1)=' ' - freqcall(nc+2)=' ' +if (nc+1 <= MAXCALLS) freqcall(nc+1) = ' ' +if (nc+2 <= MAXCALLS) freqcall(nc+2) = ' ' - do i=1,nc - write(*,1042) freqcall(i) !Band Map -1042 format('&',a12) + + do i = 1, nc + write(linenew2,'("&",A)') trim(freqcall(i)) + call write_stdout(trim(linenew2)//new_line('a')) enddo -999 continue - return end subroutine display + +end module display_mod diff --git a/map65/libm65/dot.f90 b/map65/libm65/dot.f90 index 5829e878..f0688098 100644 --- a/map65/libm65/dot.f90 +++ b/map65/libm65/dot.f90 @@ -1,11 +1,28 @@ -real*8 function dot(x,y) +module dot_mod + implicit none +contains - real*8 x(3),y(3) +real(8) function dot(x, y) result(r) + implicit none - dot=0.d0 - do i=1,3 - dot=dot+x(i)*y(i) + !-------------------------------------------------------------------- + ! Arguments + !-------------------------------------------------------------------- + real(8), intent(in) :: x(3), y(3) + + !-------------------------------------------------------------------- + ! Locals + !-------------------------------------------------------------------- + integer :: i + + !-------------------------------------------------------------------- + ! Compute dot product + !-------------------------------------------------------------------- + r = 0.0d0 + do i = 1, 3 + r = r + x(i) * y(i) enddo - return end function dot + +end module dot_mod diff --git a/map65/libm65/dpol.f90 b/map65/libm65/dpol.f90 index 3f8085c0..b67f9e3e 100644 --- a/map65/libm65/dpol.f90 +++ b/map65/libm65/dpol.f90 @@ -1,41 +1,76 @@ -real function dpol(mygrid,hisgrid) - -! Compute spatial polartzation offset in degrees for the present -! time, between two specified grid locators. - - character*6 MyGrid,HisGrid - real lat,lon,LST - character cdate*8,ctime2*10,czone*5 - integer it(8) - data rad/57.2957795/ - - call date_and_time(cdate,ctime2,czone,it) - nyear=it(1) - month=it(2) - nday=it(3) - nh=it(5)-it(4)/60 - nm=it(6) - ns=it(7) - uth=nh + nm/60.0 + ns/3600.0 - - call grid2deg(MyGrid,lon,lat) - call MoonDop(nyear,month,nday,uth,-lon,lat,RAMoon,DecMoon, & - LST,HA,AzMoon,ElMoon,vr,dist) - xx=sin(lat/rad)*cos(ElMoon/rad) - cos(lat/rad)* & - cos(AzMoon/rad)*sin(ElMoon/rad) - yy=cos(lat/rad)*sin(AzMoon/rad) - poloffset1=rad*atan2(yy,xx) - - call grid2deg(hisGrid,lon,lat) - call MoonDop(nyear,month,nday,uth,-lon,lat,RAMoon,DecMoon, & - LST,HA,AzMoon,ElMoon,vr,dist) - xx=sin(lat/rad)*cos(ElMoon/rad) - cos(lat/rad)* & - cos(AzMoon/rad)*sin(ElMoon/rad) - yy=cos(lat/rad)*sin(AzMoon/rad) - poloffset2=rad*atan2(yy,xx) - - dpol=mod(poloffset2-poloffset1+720.0,180.0) - if(dpol.gt.90.0) dpol=dpol-180.0 - - return +module dpol_mod + implicit none +contains + +real(8) function dpol(mygrid, hisgrid) result(r) + use moondop_mod + use grid2deg_mod, only: grid2deg + implicit none + + !-------------------------------------------------------------------- + ! Arguments + !-------------------------------------------------------------------- + character(len=6), intent(in) :: mygrid, hisgrid + + !-------------------------------------------------------------------- + ! Locals + !-------------------------------------------------------------------- + character(len=8) :: cdate + character(len=10) :: ctime2 + character(len=5) :: czone + integer :: it(8) + integer :: nyear, month, nday + integer :: nh, nm, ns + + real(4) :: lat, lon, LST, HA + real(4) :: RAMoon, DecMoon, AzMoon, ElMoon + real(4) :: vr, dist + real(4) :: xx, yy + real(4) :: poloffset1, poloffset2 + real(8), parameter :: rad = 57.2957795d0 + real(4) :: uth + + !-------------------------------------------------------------------- + ! Get current date/time + !-------------------------------------------------------------------- + call date_and_time(cdate, ctime2, czone, it) + nyear = it(1) + month = it(2) + nday = it(3) + nh = it(5) - it(4)/60 + nm = it(6) + ns = it(7) + uth = nh + nm/60.0d0 + ns/3600.0d0 + + !-------------------------------------------------------------------- + ! First grid + !-------------------------------------------------------------------- + call grid2deg(mygrid, lon, lat) + call MoonDop(nyear, month, nday, uth, -lon, lat, RAMoon, DecMoon, & + LST, HA, AzMoon, ElMoon, vr, dist) + + xx = sin(lat/rad)*cos(ElMoon/rad) - cos(lat/rad)*cos(AzMoon/rad)*sin(ElMoon/rad) + yy = cos(lat/rad)*sin(AzMoon/rad) + poloffset1 = rad * atan2(yy, xx) + + !-------------------------------------------------------------------- + ! Second grid + !-------------------------------------------------------------------- + call grid2deg(hisgrid, lon, lat) + call MoonDop(nyear, month, nday, uth, -lon, lat, RAMoon, DecMoon, & + LST, HA, AzMoon, ElMoon, vr, dist) + + xx = sin(lat/rad)*cos(ElMoon/rad) - cos(lat/rad)*cos(AzMoon/rad)*sin(ElMoon/rad) + yy = cos(lat/rad)*sin(AzMoon/rad) + poloffset2 = rad * atan2(yy, xx) + + !-------------------------------------------------------------------- + ! Final polarization offset + !-------------------------------------------------------------------- + r = mod(poloffset2 - poloffset1 + 720.0d0, 180.0d0) + if (r > 90.0d0) r = r - 180.0d0 + end function dpol + +end module dpol_mod + diff --git a/map65/libm65/encode65.f90 b/map65/libm65/encode65.f90 index 920d9c84..709c0e41 100644 --- a/map65/libm65/encode65.f90 +++ b/map65/libm65/encode65.f90 @@ -1,14 +1,33 @@ -subroutine encode65(message,sent) +module encode65_mod + use packjt, only:packmsg + use graycode_mod, only: graycode + use rs_mod, only: rs_encode_ + use interleave63_mod, only:interleave63 + implicit none +contains - use packjt - character message*22 - integer dgen(12) - integer sent(63) +subroutine encode65(message, sent) + + !-------------------------------------------------------------------- + ! Arguments + !-------------------------------------------------------------------- + character(len=22), intent(in) :: message + integer, intent(out) :: sent(63) - call packmsg(message,dgen,itype) - call rs_encode(dgen,sent) - call interleave63(sent,1) - call graycode(sent,63,1) + !-------------------------------------------------------------------- + ! Locals + !-------------------------------------------------------------------- + integer :: dgen(12) + integer :: itype + + !-------------------------------------------------------------------- + ! Encode message into 65-bit payload + !-------------------------------------------------------------------- + call packmsg(message, dgen, itype) + call rs_encode_(dgen, sent) + call interleave63(sent, 1) + call graycode(sent, 63, 1) - return end subroutine encode65 + +end module encode65_mod diff --git a/map65/libm65/extract.f90 b/map65/libm65/extract.f90 index 4d8af58a..c6b3345b 100644 --- a/map65/libm65/extract.f90 +++ b/map65/libm65/extract.f90 @@ -1,18 +1,54 @@ -subroutine extract(s3,nadd,ncount,nhist,decoded,ltext) +module extract_mod + implicit none +contains +pure logical function jt65_candidate_is_consistent(nhard,ntotal,rtt,matched_power) + integer, intent(in) :: nhard,ntotal + real, intent(in) :: rtt,matched_power + logical :: high_power_mismatch,ambiguous_high_burden + + high_power_mismatch=nhard.ge.42 .and. matched_power.ge.8.0 + ambiguous_high_burden=ntotal.ge.80 .and. & + (matched_power.ge.7.5 .or. rtt.ge.0.87) + jt65_candidate_is_consistent=.not.(high_power_mismatch .or. ambiguous_high_burden) +end function jt65_candidate_is_consistent + +subroutine extract(s3,nadd,ncount,nhist,decoded,ltext,mrs,mrs2) + + use iso_c_binding, only: c_int use packjt use timer_module, only: timer - real s3(64,63) - character decoded*22 + use pctile_mod + use demod64a_mod + use debug_log + use extract_shared_mod, only: s3a + use chkhist_mod + use graycode_mod + use graycode65_mod + use interleave63_mod, only: interleave63 + use ftrsd2_mod, only:ftrsd2_ + + real, intent(inout) :: s3(64,63) + integer, intent(in) :: nadd + integer, intent(out) :: ncount + integer, intent(inout) :: nhist + character(len=22), intent(out) :: decoded + logical, intent(out) :: ltext + integer, intent(out) :: mrs(63), mrs2(63) + integer dat4(12) integer mrsym(63),mr2sym(63),mrprob(63),mr2prob(63) - logical first,ltext + logical first integer correct(63),itmp(63) integer param(0:8) integer h0(0:11),d0(0:11) real r0(0:11) - common/test001/s3a(64,63),mrs(63),mrs2(63) !### TEST ONLY ### - + + integer :: i,ipk,naggressive,ncandidates,nd0,nerased,nfail,n + integer :: nft,nhard,nlow,nsec1,nsoft,ntest,ntotal,ntrials + integer(c_int) :: ntry(1) + real :: base,matched_power,qual,r00,rtt + ! 0 1 2 3 4 5 6 7 8 9 10 11 data h0/41,42,43,43,44,45,46,47,48,48,49,49/ data d0/71,72,73,74,76,77,78,80,81,82,83,83/ @@ -21,16 +57,13 @@ subroutine extract(s3,nadd,ncount,nhist,decoded,ltext) data first/.true./,nsec1/0/ save - + ntry(1)=0 nfail=0 call pctile(s3,4032,50,base) ! ### or, use ave from demod64a s3=s3/base s3a=s3 -1 call demod64a(s3,nadd,mrsym,mrprob,mr2sym,mr2prob,ntest,nlow) -! if(ntest.lt.50 .or. nlow.gt.20) then -! ncount=-999 !Flag bad data -! go to 900 -! endif + +1 call demod64a(s3,nadd,mrsym,mrprob,mr2sym,mr2prob,ntest,nlow,mrs,mrs2) call chkhist(mrsym,nhist,ipk) if(nhist.ge.20) then @@ -45,8 +78,9 @@ subroutine extract(s3,nadd,ncount,nhist,decoded,ltext) go to 1 endif - mrs=mrsym - mrs2=mr2sym +! mrs=mrsym +! mrs2=mr2sym +! write(*,*) 'EXTRACT: correct before interleave = ', correct(1:20) call graycode(mrsym,63,-1) call interleave63(mrsym,-1) @@ -63,7 +97,7 @@ subroutine extract(s3,nadd,ncount,nhist,decoded,ltext) param=0 call timer('ftrsd ',0) - call ftrsd2(mrsym,mrprob,mr2sym,mr2prob,ntrials,correct,param,ntry) + call ftrsd2_(mrsym,mrprob,mr2sym,mr2prob,ntrials,correct,param,ntry) call timer('ftrsd ',1) ncandidates=param(0) nhard=param(1) @@ -72,6 +106,7 @@ subroutine extract(s3,nadd,ncount,nhist,decoded,ltext) rtt=0.001*param(4) ntotal=param(5) qual=0.001*param(7) + matched_power=0.001*param(8) nd0=81 r00=0.87 if(naggressive.eq.10) then @@ -84,6 +119,7 @@ subroutine extract(s3,nadd,ncount,nhist,decoded,ltext) if(nhard.gt.h0(n)) nft=0 if(ntotal.gt.d0(n)) nft=0 if(rtt.gt.r0(n)) nft=0 + if(.not.jt65_candidate_is_consistent(nhard,ntotal,rtt,matched_power)) nft=0 ncount=-1 decoded=' ' @@ -94,13 +130,17 @@ subroutine extract(s3,nadd,ncount,nhist,decoded,ltext) do i=1,12 dat4(i)=correct(13-i) enddo + if (.not. is_valid_jt65_codeword(dat4)) then + nft=0 + go to 900 + endif do i=1,63 itmp(i)=correct(64-i) enddo correct(1:63)=itmp(1:63) call interleave63(correct,1) call graycode65(correct,63,1) - call unpackmsg(dat4,decoded) !Unpack the user message + call unpackmsg(dat4, decoded) !Unpack the user message ncount=0 if(iand(dat4(10),8).ne.0) ltext=.true. endif @@ -112,11 +152,21 @@ subroutine extract(s3,nadd,ncount,nhist,decoded,ltext) return end subroutine extract -subroutine getpp(workdat,p) +end module extract_mod - integer workdat(63) +subroutine getpp(workdat,p) + use debug_log + use extract_shared_mod, only: s3a + use graycode_mod + use interleave63_mod, only: interleave63 + + integer, intent(in) :: workdat(63) + real, intent(out) :: p + integer a(63) - common/test001/s3a(64,63),mrs(63),mrs2(63) + + integer :: i,j + real :: x,psum a(1:63)=workdat(63:1:-1) call interleave63(a,1) diff --git a/map65/libm65/extract_shared_mod.f90 b/map65/libm65/extract_shared_mod.f90 new file mode 100644 index 00000000..5fb8a141 --- /dev/null +++ b/map65/libm65/extract_shared_mod.f90 @@ -0,0 +1,5 @@ +module extract_shared_mod + implicit none + real :: s3a(64,63) = 0.0 + integer :: mrs(63) = 0, mrs2(63) = 0 +end module extract_shared_mod diff --git a/map65/libm65/fchisq.f90 b/map65/libm65/fchisq.f90 index 7d030583..4d0a5ae0 100644 --- a/map65/libm65/fchisq.f90 +++ b/map65/libm65/fchisq.f90 @@ -1,77 +1,112 @@ -real function fchisq(cx,cy,npts,fsample,nflip,a,ccfmax,dtmax) +module fchisq_mod + implicit none +contains +real function fchisq(cx, cy, npts, fsample, nflip, a, ccfmax, dtmax) use timer_module, only: timer - parameter (NMAX=60*96000) !Samples per 60 s - complex cx(npts),cy(npts) - real a(5) - complex w,wstep,za,zb,z - real ss(3000) - complex csx(0:NMAX/64),csy(0:NMAX/64) - data twopi/6.283185307/a1,a2,a3/99.,99.,99./ - save - - call timer('fchisq ',0) - baud=11025.0/4096.0 - nsps=nint(fsample/baud) !Samples per symbol - nsph=nsps/2 !Samples per half-symbol - ndiv=16 !Output ss() steps per symbol - nout=ndiv*npts/nsps - dtstep=1.0/(ndiv*baud) !Time per output step - - if(a(1).ne.a1 .or. a(2).ne.a2 .or. a(3).ne.a3) then - a1=a(1) - a2=a(2) - a3=a(3) - -! Mix and integrate the complex X and Y signals - csx(0)=0. - csy(0)=0. - w=1.0 - x0=0.5*(npts+1) - s=2.0/npts - do i=1,npts - x=s*(i-x0) - if(mod(i,100).eq.1) then - p2=1.5*x*x - 0.5 -! p3=2.5*(x**3) - 1.5*x -! p4=4.375*(x**4) - 3.75*(x**2) + 0.375 - dphi=(a(1) + x*a(2) + p2*a(3)) * (twopi/fsample) - wstep=cmplx(cos(dphi),sin(dphi)) - endif - w=w*wstep - csx(i)=csx(i-1) + w*cx(i) - csy(i)=csy(i-1) + w*cy(i) - enddo - endif - -! Compute 1/2-symbol powers at 1/16-symbol steps. - fac=1.e-4 - pol=a(4)/57.2957795 - aa=cos(pol) - bb=sin(pol) - - do i=1,nout - j=i*nsps/ndiv - k=j-nsph - ss(i)=0. - if(k.ge.1) then - za=csx(j)-csx(k) - zb=csy(j)-csy(k) - z=aa*za + bb*zb - ss(i)=fac*(real(z)**2 + aimag(z)**2) - endif - enddo - - ccfmax=0. - call timer('ccf2 ',0) - call ccf2(ss,nout,nflip,ccf,lagpk) - call timer('ccf2 ',1) - if(ccf.gt.ccfmax) then - ccfmax=ccf - dtmax=lagpk*dtstep - endif - fchisq=-ccfmax - call timer('fchisq ',1) - - return + use debug_log + use ccf2_mod + + implicit none + + !==== Arguments ============================================================ + integer, intent(in) :: npts, nflip + complex, intent(in) :: cx(npts), cy(npts) + real, intent(in) :: fsample + real, intent(inout) :: a(5) + real, intent(out) :: ccfmax, dtmax + + !==== Local variables ====================================================== + complex :: w, wstep, za, zb, z + real, allocatable :: ss(:) + complex, allocatable :: csx(:), csy(:) + + integer :: i, j, k, lagpk + integer :: ndiv, nout, nsph, nsps + + real :: dphi, dtstep, fac + real :: p2, pol, s, twopi, x, x0, baud + + !==== Initialize outputs =================================================== + ccfmax = 0.0 + dtmax = 0.0 + + !==== Constants ============================================================ + twopi = 6.283185307 + baud = 11025.0 / 4096.0 + + !==== Symbol timing ======================================================== + nsps = nint(fsample / baud) + nsph = nsps / 2 + ndiv = 16 + nout = ndiv * npts / nsps + dtstep = 1.0 / (ndiv * baud) + + !==== Allocate buffers ===================================================== + allocate(csx(0:npts), csy(0:npts)) + call timer('fchisq ', 0) + + !=========================================================================== + ! MIX AND INTEGRATE (always recompute) + !=========================================================================== + csx(0) = (0.0, 0.0) + csy(0) = (0.0, 0.0) + + wstep = (1.0, 0.0) + w = (1.0, 0.0) + x0 = 0.5*(npts + 1) + s = 2.0 / npts + + do i = 1, npts + x = s*(i - x0) + + if (mod(i,100) == 1) then + p2 = 1.5*x*x - 0.5 + dphi = (a(1) + x*a(2) + p2*a(3)) * (twopi/fsample) + wstep = cmplx(cos(dphi), sin(dphi)) + end if + + w = w * wstep + csx(i) = csx(i-1) + w*cx(i) + csy(i) = csy(i-1) + w*cy(i) + end do + + !=========================================================================== + ! COMPUTE HALF-SYMBOL POWERS + !=========================================================================== + fac = 1.0e-4 + pol = a(4) / 57.2957795 + allocate(ss(nout)) + ss = 0.0 + + do i = 1, nout + j = i*nsps/ndiv + k = j - nsph + + if (k >= 1) then + za = csx(j) - csx(k) + zb = csy(j) - csy(k) + z = cos(pol)*za + sin(pol)*zb + ss(i) = fac * (real(z)**2 + aimag(z)**2) + end if + end do + + !=========================================================================== + ! CORRELATE WITH SYNC PATTERN + !=========================================================================== + call timer('ccf2 ', 0) + call ccf2(ss, nout, nflip, ccfmax, lagpk) + call timer('ccf2 ', 1) + + dtmax = lagpk * dtstep + fchisq = -ccfmax + + !==== Cleanup ============================================================== + deallocate(ss) + deallocate(csx, csy) + + call timer('fchisq ', 1) end function fchisq + +end module fchisq_mod + diff --git a/map65/libm65/fchisq0.f90 b/map65/libm65/fchisq0.f90 index 2c62f275..7cb9cb8a 100644 --- a/map65/libm65/fchisq0.f90 +++ b/map65/libm65/fchisq0.f90 @@ -1,23 +1,44 @@ -real function fchisq0(y,npts,a) - - real y(npts),a(4) - -! rewind 51 - chisq = 0. - do i=1,npts - x=i - z=(x-a(3))/(0.5*a(4)) - yfit=a(1) - if(abs(z).lt.3.0) then - d=1.0 + z*z - yfit=a(1) + a(2) * (1.0/d - 0.1) - endif - chisq=chisq + (y(i) - yfit)**2 -! write(51,3001) i,y(i),yfit,y(i)-yfit -!3001 format(i5,3f10.4) - enddo - fchisq0=chisq - - return +module fchisq0_mod + implicit none +contains + +real function fchisq0(y, npts, a) result(r) + implicit none + + !-------------------------------------------------------------------- + ! Arguments + !-------------------------------------------------------------------- + integer, intent(in) :: npts + real, intent(in) :: y(npts) + real, intent(in) :: a(4) + + !-------------------------------------------------------------------- + ! Locals + !-------------------------------------------------------------------- + integer :: i + real :: x, z, yfit, d + real :: chisq + + !-------------------------------------------------------------------- + ! Compute chi-square + !-------------------------------------------------------------------- + chisq = 0.0 + do i = 1, npts + x = real(i) + z = (x - a(3)) / (0.5 * a(4)) + yfit = a(1) + + if (abs(z) < 3.0) then + d = 1.0 + z*z + yfit = a(1) + a(2) * (1.0/d - 0.1) + end if + + chisq = chisq + (y(i) - yfit)**2 + end do + + r = chisq + end function fchisq0 +end module fchisq0_mod + diff --git a/map65/libm65/fftw3.f b/map65/libm65/fftw3.f deleted file mode 100644 index 3410184c..00000000 --- a/map65/libm65/fftw3.f +++ /dev/null @@ -1,64 +0,0 @@ - INTEGER FFTW_R2HC - PARAMETER (FFTW_R2HC=0) - INTEGER FFTW_HC2R - PARAMETER (FFTW_HC2R=1) - INTEGER FFTW_DHT - PARAMETER (FFTW_DHT=2) - INTEGER FFTW_REDFT00 - PARAMETER (FFTW_REDFT00=3) - INTEGER FFTW_REDFT01 - PARAMETER (FFTW_REDFT01=4) - INTEGER FFTW_REDFT10 - PARAMETER (FFTW_REDFT10=5) - INTEGER FFTW_REDFT11 - PARAMETER (FFTW_REDFT11=6) - INTEGER FFTW_RODFT00 - PARAMETER (FFTW_RODFT00=7) - INTEGER FFTW_RODFT01 - PARAMETER (FFTW_RODFT01=8) - INTEGER FFTW_RODFT10 - PARAMETER (FFTW_RODFT10=9) - INTEGER FFTW_RODFT11 - PARAMETER (FFTW_RODFT11=10) - INTEGER FFTW_FORWARD - PARAMETER (FFTW_FORWARD=-1) - INTEGER FFTW_BACKWARD - PARAMETER (FFTW_BACKWARD=+1) - INTEGER FFTW_MEASURE - PARAMETER (FFTW_MEASURE=0) - INTEGER FFTW_DESTROY_INPUT - PARAMETER (FFTW_DESTROY_INPUT=1) - INTEGER FFTW_UNALIGNED - PARAMETER (FFTW_UNALIGNED=2) - INTEGER FFTW_CONSERVE_MEMORY - PARAMETER (FFTW_CONSERVE_MEMORY=4) - INTEGER FFTW_EXHAUSTIVE - PARAMETER (FFTW_EXHAUSTIVE=8) - INTEGER FFTW_PRESERVE_INPUT - PARAMETER (FFTW_PRESERVE_INPUT=16) - INTEGER FFTW_PATIENT - PARAMETER (FFTW_PATIENT=32) - INTEGER FFTW_ESTIMATE - PARAMETER (FFTW_ESTIMATE=64) - INTEGER FFTW_ESTIMATE_PATIENT - PARAMETER (FFTW_ESTIMATE_PATIENT=128) - INTEGER FFTW_BELIEVE_PCOST - PARAMETER (FFTW_BELIEVE_PCOST=256) - INTEGER FFTW_DFT_R2HC_ICKY - PARAMETER (FFTW_DFT_R2HC_ICKY=512) - INTEGER FFTW_NONTHREADED_ICKY - PARAMETER (FFTW_NONTHREADED_ICKY=1024) - INTEGER FFTW_NO_BUFFERING - PARAMETER (FFTW_NO_BUFFERING=2048) - INTEGER FFTW_NO_INDIRECT_OP - PARAMETER (FFTW_NO_INDIRECT_OP=4096) - INTEGER FFTW_ALLOW_LARGE_GENERIC - PARAMETER (FFTW_ALLOW_LARGE_GENERIC=8192) - INTEGER FFTW_NO_RANK_SPLITS - PARAMETER (FFTW_NO_RANK_SPLITS=16384) - INTEGER FFTW_NO_VRANK_SPLITS - PARAMETER (FFTW_NO_VRANK_SPLITS=32768) - INTEGER FFTW_NO_VRECURSE - PARAMETER (FFTW_NO_VRECURSE=65536) - INTEGER FFTW_NO_SIMD - PARAMETER (FFTW_NO_SIMD=131072) diff --git a/map65/libm65/fftw3.f90 b/map65/libm65/fftw3.f90 index 440ccc28..f5674736 100644 --- a/map65/libm65/fftw3.f90 +++ b/map65/libm65/fftw3.f90 @@ -1,64 +1,39 @@ - INTEGER FFTW_R2HC - PARAMETER (FFTW_R2HC=0) - INTEGER FFTW_HC2R - PARAMETER (FFTW_HC2R=1) - INTEGER FFTW_DHT - PARAMETER (FFTW_DHT=2) - INTEGER FFTW_REDFT00 - PARAMETER (FFTW_REDFT00=3) - INTEGER FFTW_REDFT01 - PARAMETER (FFTW_REDFT01=4) - INTEGER FFTW_REDFT10 - PARAMETER (FFTW_REDFT10=5) - INTEGER FFTW_REDFT11 - PARAMETER (FFTW_REDFT11=6) - INTEGER FFTW_RODFT00 - PARAMETER (FFTW_RODFT00=7) - INTEGER FFTW_RODFT01 - PARAMETER (FFTW_RODFT01=8) - INTEGER FFTW_RODFT10 - PARAMETER (FFTW_RODFT10=9) - INTEGER FFTW_RODFT11 - PARAMETER (FFTW_RODFT11=10) - INTEGER FFTW_FORWARD - PARAMETER (FFTW_FORWARD=-1) - INTEGER FFTW_BACKWARD - PARAMETER (FFTW_BACKWARD=+1) - INTEGER FFTW_MEASURE - PARAMETER (FFTW_MEASURE=0) - INTEGER FFTW_DESTROY_INPUT - PARAMETER (FFTW_DESTROY_INPUT=1) - INTEGER FFTW_UNALIGNED - PARAMETER (FFTW_UNALIGNED=2) - INTEGER FFTW_CONSERVE_MEMORY - PARAMETER (FFTW_CONSERVE_MEMORY=4) - INTEGER FFTW_EXHAUSTIVE - PARAMETER (FFTW_EXHAUSTIVE=8) - INTEGER FFTW_PRESERVE_INPUT - PARAMETER (FFTW_PRESERVE_INPUT=16) - INTEGER FFTW_PATIENT - PARAMETER (FFTW_PATIENT=32) - INTEGER FFTW_ESTIMATE - PARAMETER (FFTW_ESTIMATE=64) - INTEGER FFTW_ESTIMATE_PATIENT - PARAMETER (FFTW_ESTIMATE_PATIENT=128) - INTEGER FFTW_BELIEVE_PCOST - PARAMETER (FFTW_BELIEVE_PCOST=256) - INTEGER FFTW_DFT_R2HC_ICKY - PARAMETER (FFTW_DFT_R2HC_ICKY=512) - INTEGER FFTW_NONTHREADED_ICKY - PARAMETER (FFTW_NONTHREADED_ICKY=1024) - INTEGER FFTW_NO_BUFFERING - PARAMETER (FFTW_NO_BUFFERING=2048) - INTEGER FFTW_NO_INDIRECT_OP - PARAMETER (FFTW_NO_INDIRECT_OP=4096) - INTEGER FFTW_ALLOW_LARGE_GENERIC - PARAMETER (FFTW_ALLOW_LARGE_GENERIC=8192) - INTEGER FFTW_NO_RANK_SPLITS - PARAMETER (FFTW_NO_RANK_SPLITS=16384) - INTEGER FFTW_NO_VRANK_SPLITS - PARAMETER (FFTW_NO_VRANK_SPLITS=32768) - INTEGER FFTW_NO_VRECURSE - PARAMETER (FFTW_NO_VRECURSE=65536) - INTEGER FFTW_NO_SIMD - PARAMETER (FFTW_NO_SIMD=131072) +module fftw3_constants + implicit none + + integer, parameter :: FFTW_R2HC = 0 + integer, parameter :: FFTW_HC2R = 1 + integer, parameter :: FFTW_DHT = 2 + integer, parameter :: FFTW_REDFT00 = 3 + integer, parameter :: FFTW_REDFT01 = 4 + integer, parameter :: FFTW_REDFT10 = 5 + integer, parameter :: FFTW_REDFT11 = 6 + integer, parameter :: FFTW_RODFT00 = 7 + integer, parameter :: FFTW_RODFT01 = 8 + integer, parameter :: FFTW_RODFT10 = 9 + integer, parameter :: FFTW_RODFT11 = 10 + + integer, parameter :: FFTW_FORWARD = -1 + integer, parameter :: FFTW_BACKWARD = +1 + + integer, parameter :: FFTW_MEASURE = 0 + integer, parameter :: FFTW_DESTROY_INPUT = 1 + integer, parameter :: FFTW_UNALIGNED = 2 + integer, parameter :: FFTW_CONSERVE_MEMORY = 4 + integer, parameter :: FFTW_EXHAUSTIVE = 8 + integer, parameter :: FFTW_PRESERVE_INPUT = 16 + integer, parameter :: FFTW_PATIENT = 32 + integer, parameter :: FFTW_ESTIMATE = 64 + integer, parameter :: FFTW_ESTIMATE_PATIENT = 128 + integer, parameter :: FFTW_BELIEVE_PCOST = 256 + integer, parameter :: FFTW_DFT_R2HC_ICKY = 512 + integer, parameter :: FFTW_NONTHREADED_ICKY = 1024 + integer, parameter :: FFTW_NO_BUFFERING = 2048 + integer, parameter :: FFTW_NO_INDIRECT_OP = 4096 + integer, parameter :: FFTW_ALLOW_LARGE_GENERIC = 8192 + integer, parameter :: FFTW_NO_RANK_SPLITS = 16384 + integer, parameter :: FFTW_NO_VRANK_SPLITS = 32768 + integer, parameter :: FFTW_NO_VRECURSE = 65536 + integer, parameter :: FFTW_NO_SIMD = 131072 + +end module fftw3_constants diff --git a/map65/libm65/fftw3_f77_interfaces.f90 b/map65/libm65/fftw3_f77_interfaces.f90 new file mode 100644 index 00000000..1b5af220 --- /dev/null +++ b/map65/libm65/fftw3_f77_interfaces.f90 @@ -0,0 +1,44 @@ +module fftw3_f77_interfaces + use iso_c_binding, only: c_int, c_intptr_t, c_float_complex, c_float + implicit none + + interface + subroutine sfftw_destroy_plan(plan) + import :: c_intptr_t + implicit none + integer(c_intptr_t) :: plan + end subroutine sfftw_destroy_plan + + subroutine sfftw_plan_dft_1d(plan, n, in, out, sign, flags) + import :: c_int, c_intptr_t, c_float_complex + implicit none + integer(c_intptr_t) :: plan + integer(c_int) :: n, sign, flags + complex(c_float_complex) :: in(*), out(*) + end subroutine sfftw_plan_dft_1d + + subroutine sfftw_plan_dft_r2c_1d(plan, n, in, out, flags) + import :: c_int, c_intptr_t, c_float_complex + implicit none + integer(c_intptr_t) :: plan + integer(c_int) :: n, flags + complex(c_float_complex) :: in(*), out(*) + end subroutine sfftw_plan_dft_r2c_1d + + subroutine sfftw_plan_dft_c2r_1d(plan, n, in, out, flags) + import :: c_int, c_intptr_t, c_float_complex + implicit none + integer(c_intptr_t) :: plan + integer(c_int) :: n, flags + complex(c_float_complex) :: in(*), out(*) + end subroutine sfftw_plan_dft_c2r_1d + + subroutine sfftw_execute(plan) + import :: c_intptr_t + implicit none + integer(c_intptr_t) :: plan + end subroutine sfftw_execute + end interface + +end module fftw3_f77_interfaces + diff --git a/map65/libm65/fil6521.f90 b/map65/libm65/fil6521.f90 index f588d0c1..3764ed33 100644 --- a/map65/libm65/fil6521.f90 +++ b/map65/libm65/fil6521.f90 @@ -1,44 +1,60 @@ -subroutine fil6521(c1,n1,c2,n2) - -! FIR lowpass filter designed using ScopeFIR - -! Pass #1 Pass #2 -!----------------------------------------------- -! fsample (Hz) 1378.125 Input sample rate -! Ntaps 21 Number of filter taps -! fc (Hz) 40 Cutoff frequency -! fstop (Hz) 172.266 Lower limit of stopband -! Ripple (dB) 0.1 Ripple in passband -! Stop Atten (dB) 38 Stopband attenuation -! fout (Hz) 344.531 Output sample rate - - parameter (NTAPS=21) - parameter (NH=(NTAPS-1)/2) - parameter (NDOWN=4) !Downsample ratio = 1/4 - complex c1(n1) - complex c2(n1/NDOWN) - -! Filter coefficients: - real a(-NH:NH) - data a/ & - -0.011958606980,-0.013888627387,-0.015601306443,-0.010602249570, & - 0.003804023436, 0.028320058273, 0.060903935217, 0.096841904411, & - 0.129639871228, 0.152644580853, 0.160917511283, 0.152644580853, & - 0.129639871228, 0.096841904411, 0.060903935217, 0.028320058273, & - 0.003804023436,-0.010602249570,-0.015601306443,-0.013888627387, & - -0.011958606980/ - - n2=(n1-NTAPS+NDOWN)/NDOWN - k0=NH-NDOWN+1 - -! Loop over all output samples - do i=1,n2 - c2(i)=0. - k=k0 + NDOWN*i - do j=-NH,NH - c2(i)=c2(i) + c1(j+k)*a(j) - enddo - enddo - - return +module fil6521_mod + implicit none +contains + +subroutine fil6521(c1, n1, c2, n2) + implicit none + + !-------------------------------------------------------------------- + ! Arguments + !-------------------------------------------------------------------- + integer, intent(in) :: n1 + integer, intent(out) :: n2 + complex, intent(in) :: c1(n1) + complex, intent(out) :: c2(n1/4) ! NDOWN = 4 + + !-------------------------------------------------------------------- + ! Parameters + !-------------------------------------------------------------------- + integer, parameter :: NTAPS = 21 + integer, parameter :: NH = (NTAPS - 1)/2 + integer, parameter :: NDOWN = 4 + + !-------------------------------------------------------------------- + ! Locals + !-------------------------------------------------------------------- + integer :: i, j, k, k0 + real :: a(-NH:NH) + + !-------------------------------------------------------------------- + ! Filter coefficients (ScopeFIR) + !-------------------------------------------------------------------- + data a / & + -0.011958606980, -0.013888627387, -0.015601306443, -0.010602249570, & + 0.003804023436, 0.028320058273, 0.060903935217, 0.096841904411, & + 0.129639871228, 0.152644580853, 0.160917511283, 0.152644580853, & + 0.129639871228, 0.096841904411, 0.060903935217, 0.028320058273, & + 0.003804023436, -0.010602249570, -0.015601306443, -0.013888627387, & + -0.011958606980 / + + !-------------------------------------------------------------------- + ! Compute output length and starting offset + !-------------------------------------------------------------------- + n2 = (n1 - NTAPS + NDOWN) / NDOWN + k0 = NH - NDOWN + 1 + + !-------------------------------------------------------------------- + ! FIR filtering + decimation by 4 + !-------------------------------------------------------------------- + do i = 1, n2 + c2(i) = (0.0, 0.0) + k = k0 + NDOWN * i + + do j = -NH, NH + c2(i) = c2(i) + c1(j + k) * a(j) + end do + end do + end subroutine fil6521 + +end module fil6521_mod diff --git a/map65/libm65/filbig.f90 b/map65/libm65/filbig.f90 index ada8ccc0..bfbaf7a5 100644 --- a/map65/libm65/filbig.f90 +++ b/map65/libm65/filbig.f90 @@ -1,132 +1,221 @@ -subroutine filbig(dd,nmax,f0,newdat,nfsample,xpol,c4a,c4b,n4) - -! Filter and downsample complex data stored in array dd(4,nmax). -! Output is downsampled from 96000 Hz to 1375.125 Hz. - - use timer_module, only: timer - parameter (MAXFFT1=5376000,MAXFFT2=77175) - real*4 dd(4,nmax) !Input data - complex ca(MAXFFT1),cb(MAXFFT1) !FFTs of input - complex c4a(MAXFFT2),c4b(MAXFFT2) !Output data - real*8 df - real halfpulse(8) !Impulse response of filter (one sided) - complex cfilt(MAXFFT2) !Filter (complex; imag = 0) - real rfilt(MAXFFT2) !Filter (real) - integer*8 plan1,plan2,plan3,plan4,plan5 - logical first,xpol - include 'fftw3.f' - common/cacb/ca,cb - equivalence (rfilt,cfilt) - data first/.true./,npatience/1/ - data halfpulse/114.97547150,36.57879257,-20.93789101, & - 5.89886379,1.59355187,-2.49138308,0.60910773,-0.04248129/ - save - - if(nmax.lt.0) go to 900 - - nfft1=MAXFFT1 - nfft2=MAXFFT2 - if(nfsample.eq.95238) then - nfft1=5120000 - nfft2=74088 - endif - - if(first) then - nflags=FFTW_ESTIMATE - if(npatience.eq.1) nflags=FFTW_ESTIMATE_PATIENT - if(npatience.eq.2) nflags=FFTW_MEASURE - if(npatience.eq.3) nflags=FFTW_PATIENT - if(npatience.eq.4) nflags=FFTW_EXHAUSTIVE +module filbig_mod + use iso_fortran_env, only: real32, real64 + use iso_c_binding, only:c_intptr_t + use timer_module, only: timer + use debug_log + use cacb_mod + use npar_ptrs_mod, only: nrate_active, nfft_big_active + use fftw3_constants + use fftw3_f77_interfaces + use sec_midn_mod, only: sec_midn + implicit none + + integer, parameter :: MAXFFT1 = 56*192000 + integer, parameter :: MAXFFT2 = 2*77175 + + complex, save :: c4a_buf(MAXFFT2), c4b_buf(MAXFFT2), cfilt_buf(MAXFFT2) + integer(c_intptr_t), save :: plan1, plan2, plan3, plan4, plan5 + logical, save :: filbig_first = .true. + +contains + + subroutine filbig(dd, nmax, f0, newdat, nfsample, xpol, c4a, c4b, n4) + + ! Filter and downsample complex data stored in array dd(4,nmax). + ! Output is downsampled from nrate_active Hz to 1378.125 Hz (same decimation ratio as 96 kHz). + + integer, intent(in) :: nmax + real(real32), intent(in) :: dd(4, nmax) + real(real64), intent(in) :: f0 + integer, intent(inout) :: newdat + integer, intent(in) :: nfsample + logical, intent(in) :: xpol + complex, intent(out) :: c4a(MAXFFT2), c4b(MAXFFT2) + integer, intent(out) :: n4 + + real(real64) :: df + real halfpulse(8) !Impulse response (one sided) + real base, fac, filtval + integer i, i0, j, nfft1, nfft2, nflags, nh, npatience, nz + real(real64) :: decim + ! Filter in frequency domain; sized at max short-FFT length + data npatience/1/ + data halfpulse/114.97547150, 36.57879257, -20.93789101, & + 5.89886379, 1.59355187, -2.49138308, 0.60910773, -0.04248129/ + + save + + ! ca/cb storage is sized at MAXFFT1 in cacb_mod; the *active* big FFT + ! length is nfft_big_active, set from C++ via set_runtime_params_(). + call init_cacb(MAXFFT1) + + if (nmax .lt. 0) go to 900 + + ! Runtime big-FFT length: nfft_big_active is 56 * nrate_active, set + ! from C++ at startup. Clamp to MAXFFT1 for safety. + nfft1 = min(56*nrate_active, MAXFFT1) + decim = real(nrate_active, kind=real64) / 1378.125_real64 + ! Preserve the original decimation ratio between nfft1 and nfft2. + ! At 96 kHz: nfft1 = 5376000, nfft2 = 77175 ? ratio � 69.64 + ! At 192 kHz: nfft1 doubles, so nfft2 should double to keep the + ! same time span / bandwidth in the downsampled stream. + ! + ! Use the 96 kHz baseline ratio to derive nfft2 for any rate: + ! nfft2 � nfft1 * (77175 / 5376000) + + ! Choose nfft2 so that the time span in c4a is the same as in the 96 kHz case + ! Baseline: at 96 kHz, nfft1=5,376,000, nfft2=77,175 + ! nfft2 = int( real(nfft1, kind=real64) * 77175.0_real64 / 5376000.0_real64 ) + nfft2 = int(MAXFFT2/2) + nfft2 = min(nfft2, MAXFFT2) + if (nfft2 .gt. MAXFFT2) nfft2 = MAXFFT2 + + ! Preserve the legacy 95238 special case (Linrad odd rate); if you + ! still use it, override the derived sizes with the historical ones. + if (nfsample .eq. 95238) then + nfft1 = min(5120000, MAXFFT1) + nfft2 = min(74088, MAXFFT2) + endif + + if (filbig_first) then + ! TEMP diagnostic 2026-09-10 for the "first decode cycle after + ! startup is degraded/missing" investigation. filbig_first is a + ! module-SAVEd flag -- true exactly once, for the life of the + ! process -- so this whole block runs on the very first filbig() + ! call and never again. That happens to line up exactly with when + ! the anomaly has been observed. FFTW plan creation (even the cheap + ! ESTIMATE_PATIENT mode used below) still does real work for a + ! multi-million-point transform; if it takes long enough to run + ! synchronously on this thread, it could delay real-time audio + ! capture on the GUI/audio thread for that whole span. Time it + ! directly rather than assuming either way. + call dbg('filbig: FIRST-EVER CALL, starting FFTW plan creation at t=' // rtoa(sec_midn()) // & + ' nfft1=' // itoa(nfft1) // ' nfft2=' // itoa(nfft2)) + + nflags = FFTW_ESTIMATE + if (npatience .eq. 1) nflags = FFTW_ESTIMATE_PATIENT + if (npatience .eq. 2) nflags = FFTW_MEASURE + if (npatience .eq. 3) nflags = FFTW_PATIENT + if (npatience .eq. 4) nflags = FFTW_EXHAUSTIVE + + ! Plan the FFTs just once + call timer('FFTplans', 0) + call sfftw_plan_dft_1d(plan1, nfft1, ca, ca, FFTW_BACKWARD, nflags) + call sfftw_plan_dft_1d(plan2, nfft1, cb, cb, FFTW_BACKWARD, nflags) + call sfftw_plan_dft_1d(plan3, nfft2, c4a_buf, c4a_buf, FFTW_FORWARD, nflags) + call sfftw_plan_dft_1d(plan4, nfft2, c4b_buf, c4b_buf, FFTW_FORWARD, nflags) + call sfftw_plan_dft_1d(plan5, nfft2, cfilt_buf,cfilt_buf,FFTW_BACKWARD, nflags) + call timer('FFTplans', 1) + call dbg('filbig: FFTW plan creation DONE at t=' // rtoa(sec_midn())) + + ! Convert impulse response to filter function + do i = 1, nfft2 + cfilt_buf(i) = 0.0 + enddo + fac = 0.00625/nfft1 + cfilt_buf(1) = fac*halfpulse(1) + do i = 2, 8 + cfilt_buf(i) = fac*halfpulse(i) + cfilt_buf(nfft2 + 2 - i) = fac*halfpulse(i) + enddo + call sfftw_execute(plan5) + + base = real(cfilt_buf(nfft2/2 + 1)) + + ! Bin width of the big FFT: use the active runtime rate instead + ! of a hardcoded 96000. The 95238 special case is preserved. + df = dble(nrate_active)/dble(nfft1) + if (nfsample .eq. 95238) df = 95238.1d0/dble(nfft1) + filbig_first = .false. + call dbg('filbig: entire one-time init (plans + filter) DONE at t=' // rtoa(sec_midn())) + endif + + ! When new data comes along, we need to compute a new "big FFT" + ! If we just have a new f0, continue with the existing ca and cb. + + if (newdat .ne. 0 .or. sum(abs(ca)) .eq. 0.0) then !### Test on ca should be unnecessary? + nz = min(nmax, nfft1) + do i = 1, nz + ca(i) = cmplx(dd(1, i), dd(2, i)) + if (xpol) cb(i) = cmplx(dd(3, i), dd(4, i)) + enddo + + if (nmax .lt. nfft1) then + do i = nmax + 1, nfft1 + ca(i) = 0.0 + if (xpol) cb(i) = 0.0 + enddo + endif + call timer('FFTbig ', 0) + call sfftw_execute(plan1) + if (xpol) call sfftw_execute(plan2) + call timer('FFTbig ', 1) + newdat = 0 + endif + + ! NB: f0 is the frequency at which we want our filter centered. + ! i0 is the bin number in ca and cb closest to f0. + + i0 = nint(f0/df) + 1 + nh = nfft2/2 + + ! Lower half of filter + do i = 1, nh + j = i0 + i - 1 + if (j .ge. 1 .and. j .le. nfft1) then + filtval = real(cfilt_buf(i)) - base + c4a_buf(i) = filtval*ca(j) + if (xpol) c4b_buf(i) = filtval*cb(j) + else + c4a_buf(i) = 0.0 + if (xpol) c4b_buf(i) = 0.0 + endif + enddo + + ! Upper half of filter, with wrap-around and bounds check + do i = nh + 1, nfft2 + j = i0 + i - 1 - nfft2 + if (j .lt. 1) j = j + nfft1 + + if (j < 1 .or. j > size(ca)) then + write (dbg_unit, *) 'FILBIG OOB: i=', i, ' j=', j, ' nh=', nh, & + ' nfft1=', nfft1, ' nfft2=', nfft2, ' i0=', i0 + flush(dbg_unit) + stop 'FILBIG index OOB' + end if + + filtval = real(cfilt_buf(i)) - base + c4a_buf(i) = filtval*ca(j) + if (xpol) c4b_buf(i) = filtval*cb(j) + enddo + + ! Do the short reverse transform, to go back to time domain. + call timer('FFTsmall', 0) + call sfftw_execute(plan3) + if (xpol) call sfftw_execute(plan4) + call timer('FFTsmall', 1) + + c4a(1:nfft2) = c4a_buf(1:nfft2) + if (xpol) then + c4b(1:nfft2) = c4b_buf(1:nfft2) + else + c4b(1:nfft2) = 0.0 + endif + + ! Number of valid output samples at ~1375 Hz + n4 = min( int( real(nmax, kind=real64) / decim ), nfft2 ) + n4 = min( int( real(nmax, kind=real64) / decim ), nfft2 ) -! Plan the FFTs just once - call timer('FFTplans ',0) - call sfftw_plan_dft_1d(plan1,nfft1,ca,ca,FFTW_BACKWARD,nflags) - call sfftw_plan_dft_1d(plan2,nfft1,cb,cb,FFTW_BACKWARD,nflags) - call sfftw_plan_dft_1d(plan3,nfft2,c4a,c4a,FFTW_FORWARD,nflags) - call sfftw_plan_dft_1d(plan4,nfft2,c4b,c4b,FFTW_FORWARD,nflags) - call sfftw_plan_dft_1d(plan5,nfft2,cfilt,cfilt,FFTW_BACKWARD,nflags) - call timer('FFTplans ',1) - -! Convert impulse response to filter function - do i=1,nfft2 - cfilt(i)=0. - enddo - fac=0.00625/nfft1 - cfilt(1)=fac*halfpulse(1) - do i=2,8 - cfilt(i)=fac*halfpulse(i) - cfilt(nfft2+2-i)=fac*halfpulse(i) - enddo - call sfftw_execute(plan5) - - base=cfilt(nfft2/2+1) - do i=1,nfft2 - rfilt(i)=real(cfilt(i))-base - enddo - - df=96000.d0/nfft1 - if(nfsample.eq.95238) df=95238.1d0/nfft1 - first=.false. - endif - -! When new data comes along, we need to compute a new "big FFT" -! If we just have a new f0, continue with the existing ca and cb. - - if(newdat.ne.0 .or. sum(abs(ca)).eq.0.0) then !### Test on ca should be unnecessary? - nz=min(nmax,nfft1) - do i=1,nz - ca(i)=cmplx(dd(1,i),dd(2,i)) - if(xpol) cb(i)=cmplx(dd(3,i),dd(4,i)) - enddo - - if(nmax.lt.nfft1) then - do i=nmax+1,nfft1 - ca(i)=0. - if(xpol) cb(i)=0. - enddo - endif - call timer('FFTbig ',0) - call sfftw_execute(plan1) - if(xpol) call sfftw_execute(plan2) - call timer('FFTbig ',1) - newdat=0 - endif - -! NB: f0 is the frequency at which we want our filter centered. -! i0 is the bin number in ca and cb closest to f0. - - i0=nint(f0/df) + 1 - nh=nfft2/2 - do i=1,nh !Copy data into c4a and c4b, - j=i0+i-1 !and apply the filter function - if(j.ge.1 .and. j.le.nfft1) then - c4a(i)=rfilt(i)*ca(j) - if(xpol) c4b(i)=rfilt(i)*cb(j) - else - c4a(i)=0. - if(xpol) c4b(i)=0. - endif - enddo - do i=nh+1,nfft2 - j=i0+i-1-nfft2 - if(j.lt.1) j=j+nfft1 !nfft1 was nfft2 - c4a(i)=rfilt(i)*ca(j) - if(xpol) c4b(i)=rfilt(i)*cb(j) - enddo - -! Do the short reverse transform, to go back to time domain. - call timer('FFTsmall',0) - call sfftw_execute(plan3) - if(xpol) call sfftw_execute(plan4) - call timer('FFTsmall',1) - n4=min(nmax/64,nfft2) - go to 999 - -900 call sfftw_destroy_plan(plan1) - call sfftw_destroy_plan(plan2) - call sfftw_destroy_plan(plan3) - call sfftw_destroy_plan(plan4) - call sfftw_destroy_plan(plan5) - -999 return -end subroutine filbig + go to 999 + + 900 call sfftw_destroy_plan(plan1) + call sfftw_destroy_plan(plan2) + call sfftw_destroy_plan(plan3) + call sfftw_destroy_plan(plan4) + call sfftw_destroy_plan(plan5) + + 999 return + end subroutine filbig + +end module filbig_mod + diff --git a/map65/libm65/fmtmsg.f90 b/map65/libm65/fmtmsg.f90 index 2ceb8155..8e583f55 100644 --- a/map65/libm65/fmtmsg.f90 +++ b/map65/libm65/fmtmsg.f90 @@ -1,21 +1,42 @@ -subroutine fmtmsg(msg,iz) +module fmtmsg_mod + implicit none +contains - character*22 msg +subroutine fmtmsg(msg, iz) + implicit none -! Convert all letters to upper case - iz=22 - do i=1,22 - if(msg(i:i).ge.'a' .and. msg(i:i).le.'z') & - msg(i:i)= char(ichar(msg(i:i))+ichar('A')-ichar('a')) - if(msg(i:i).ne.' ') iz=i - enddo + !-------------------------------------------------------------------- + ! Arguments + !-------------------------------------------------------------------- + character(len=22), intent(inout) :: msg + integer, intent(out) :: iz - do iter=1,5 !Collapse multiple blanks into one - ib2=index(msg(1:iz),' ') - if(ib2.lt.1) go to 100 - msg=msg(1:ib2)//msg(ib2+2:) - iz=iz-1 - enddo + !-------------------------------------------------------------------- + ! Locals + !-------------------------------------------------------------------- + integer :: i, iter, ib2 + + !-------------------------------------------------------------------- + ! Convert all letters to upper case and track last nonblank + !-------------------------------------------------------------------- + iz = 22 + do i = 1, 22 + if (msg(i:i) >= 'a' .and. msg(i:i) <= 'z') then + msg(i:i) = char(ichar(msg(i:i)) + ichar('A') - ichar('a')) + end if + if (msg(i:i) /= ' ') iz = i + end do + + !-------------------------------------------------------------------- + ! Collapse multiple blanks into one (up to 5 passes) + !-------------------------------------------------------------------- + do iter = 1, 5 + ib2 = index(msg(1:iz), ' ') + if (ib2 < 1) exit + msg = msg(1:ib2) // msg(ib2+2:) + iz = iz - 1 + end do -100 return end subroutine fmtmsg + +end module fmtmsg_mod diff --git a/map65/libm65/four2a.f90 b/map65/libm65/four2a.f90 index fc46109e..91be0f48 100644 --- a/map65/libm65/four2a.f90 +++ b/map65/libm65/four2a.f90 @@ -1,115 +1,116 @@ -subroutine four2a(a,nfft,ndim,isign,iform) - -! IFORM = 1, 0 or -1, as data is -! complex, real, or the first half of a complex array. Transform -! values are returned in array DATA. They are complex, real, or -! the first half of a complex array, as IFORM = 1, -1 or 0. - -! The transform of a real array (IFORM = 0) dimensioned N(1) by N(2) -! by ... will be returned in the same array, now considered to -! be complex of dimensions N(1)/2+1 by N(2) by .... Note that if -! IFORM = 0 or -1, N(1) must be even, and enough room must be -! reserved. The missing values may be obtained by complex conjugation. - -! The reverse transformation of a half complex array dimensioned -! N(1)/2+1 by N(2) by ..., is accomplished by setting IFORM -! to -1. In the N array, N(1) must be the true N(1), not N(1)/2+1. -! The transform will be real and returned to the input array. - -! This version of four2a makes calls to the FFTW library to do the -! actual computations. - +module four2a_mod use fftw3 - parameter (NPMAX=2100) !Max numberf of stored plans - parameter (NSMALL=16384) !Max size of "small" FFTs - complex a(nfft+1) !Array to be transformed - complex aa(NSMALL) !Local copy of "small" a() - integer nn(NPMAX),ns(NPMAX),nf(NPMAX) !Params of stored plans - integer*8 nl(NPMAX),nloc !More params of plans - integer*8 plan(NPMAX) !Pointers to stored plans - logical found_plan - data nplan/0/ !Number of stored plans - common/patience/npatience,nthreads !Patience and threads for FFTW plans - save plan,nplan,nn,ns,nf,nl - - if(nfft.lt.0) go to 999 - - nloc=loc(a) - - found_plan = .false. - !$omp critical(four2a_setup) - do i=1,nplan - if(nfft.eq.nn(i) .and. isign.eq.ns(i) .and. & - iform.eq.nf(i) .and. nloc.eq.nl(i)) then - found_plan = .true. - exit - end if - enddo - - if(i.ge.NPMAX) stop 'Too many FFTW plans requested.' - - if (.not. found_plan) then - nplan=nplan+1 - i=nplan - - nn(i)=nfft - ns(i)=isign - nf(i)=iform - nl(i)=nloc - -! Planning: FFTW_ESTIMATE, FFTW_ESTIMATE_PATIENT, FFTW_MEASURE, -! FFTW_PATIENT, FFTW_EXHAUSTIVE - nflags=FFTW_ESTIMATE - if(npatience.eq.1) nflags=FFTW_ESTIMATE_PATIENT - if(npatience.eq.2) nflags=FFTW_MEASURE - if(npatience.eq.3) nflags=FFTW_PATIENT - if(npatience.eq.4) nflags=FFTW_EXHAUSTIVE - - if(nfft.le.NSMALL) then - jz=nfft - if(iform.eq.0) jz=nfft/2 - aa(1:jz)=a(1:jz) - endif - - !$omp critical(fftw) ! serialize non thread-safe FFTW3 calls - if(isign.eq.-1 .and. iform.eq.1) then - call sfftw_plan_dft_1d(plan(i),nfft,a,a,FFTW_FORWARD,nflags) - else if(isign.eq.1 .and. iform.eq.1) then - call sfftw_plan_dft_1d(plan(i),nfft,a,a,FFTW_BACKWARD,nflags) - else if(isign.eq.-1 .and. iform.eq.0) then - call sfftw_plan_dft_r2c_1d(plan(i),nfft,a,a,nflags) - else if(isign.eq.1 .and. iform.eq.-1) then - call sfftw_plan_dft_c2r_1d(plan(i),nfft,a,a,nflags) - else - stop 'Unsupported request in four2a' - endif - !$omp end critical(fftw) - - if(nfft.le.NSMALL) then - jz=nfft - if(iform.eq.0) jz=nfft/2 - a(1:jz)=aa(1:jz) - endif - end if - !$omp end critical(four2a_setup) - - call sfftw_execute(plan(i)) - return - -999 continue - - !$omp critical(four2a) - do i=1,nplan -! The test is only to silence a compiler warning: - if(ndim.ne.-999) then - !$omp critical(fftw) ! serialize non thread-safe FFTW3 calls - call sfftw_destroy_plan(plan(i)) - !$omp end critical(fftw) - end if - enddo - - nplan=0 - !$omp end critical(four2a) - - return -end subroutine four2a + use iso_c_binding + use fftw3_f77_interfaces + + implicit none + +contains + + function loc_cplx(x) result(addr) + use iso_c_binding, only: c_float_complex, c_intptr_t, c_loc + implicit none + complex(c_float_complex), intent(in), target :: x(*) + integer(c_intptr_t) :: addr + addr = transfer(c_loc(x), addr) + end function loc_cplx + + recursive subroutine four2a(a, nfft, ndim, isign, iform) bind(C, name='four2a_') + + implicit none + + !==== Arguments ============================================================ + complex(c_float_complex), dimension(*), intent(inout) :: a + integer(c_int), intent(in) :: nfft, ndim, isign, iform + + !==== Parameters =========================================================== + integer, parameter :: NPMAX = 2100 + integer, parameter :: NSMALL = 16384 + + !==== Local variables ====================================================== + complex(c_float_complex) :: aa(NSMALL) + integer :: nn(NPMAX), ns(NPMAX), nf(NPMAX) + integer(c_intptr_t) :: nl(NPMAX), nloc + integer(c_intptr_t) :: plan(NPMAX) + logical :: found_plan + integer :: i, jz = 0, nflags + integer :: nplan + + !==== Saved state ========================================================== + save plan, nplan, nn, ns, nf, nl + data nplan / 0 / + + integer :: dummy_unused + dummy_unused = ndim + + + !==== Early exit: destroy all plans ======================================= + if (nfft < 0) then + !$omp critical(four2a) + do i = 1, nplan + !$omp critical(fftw) + call sfftw_destroy_plan(plan(i)) + !$omp end critical(fftw) + enddo + nplan = 0 + !$omp end critical(four2a) + return + endif + + !==== Locate or create plan =============================================== + nloc = loc_cplx(a) + found_plan = .false. + + !$omp critical(four2a_setup) + do i = 1, nplan + if (nfft == nn(i) .and. isign == ns(i) .and. iform == nf(i) .and. nloc == nl(i)) then + found_plan = .true. + exit + endif + enddo + + if (.not. found_plan) then + nplan = nplan + 1 + i = nplan + + nn(i) = nfft + ns(i) = isign + nf(i) = iform + nl(i) = nloc + + nflags = FFTW_ESTIMATE + + if (nfft <= NSMALL) then + jz = nfft + if (iform <= 0) jz = nfft/2 + 1 + aa(1:jz) = a(1:jz) + endif + + !$omp critical(fftw) + select case (iform) + case (1) + if (isign == -1) then + call sfftw_plan_dft_1d(plan(i), nfft, a, a, FFTW_FORWARD, nflags) + else + call sfftw_plan_dft_1d(plan(i), nfft, a, a, FFTW_BACKWARD, nflags) + endif + case (0) + call sfftw_plan_dft_r2c_1d(plan(i), nfft, a, a, nflags) + case (-1) + call sfftw_plan_dft_c2r_1d(plan(i), nfft, a, a, nflags) + case default + stop 'Unsupported request in four2a' + end select + !$omp end critical(fftw) + + if (nfft <= NSMALL) then + a(1:jz) = aa(1:jz) + endif + endif + !$omp end critical(four2a_setup) + + call sfftw_execute(plan(i)) + + end subroutine four2a + +end module four2a_mod diff --git a/map65/libm65/four2a_legacy_wrap.f90 b/map65/libm65/four2a_legacy_wrap.f90 new file mode 100644 index 00000000..d2c0028b --- /dev/null +++ b/map65/libm65/four2a_legacy_wrap.f90 @@ -0,0 +1,77 @@ +module four2a_legacy_wrap_mod + use iso_c_binding + use four2a_mod, only: four2a + implicit none + + integer, parameter :: JT65_NFFT = 512 + integer, parameter :: JT65_NH = JT65_NFFT/2 +contains + +subroutine r2c_legacy(s_real, cs_half) + use iso_c_binding + use four2a_mod, only: four2a + implicit none + + real, intent(in) :: s_real(JT65_NFFT) + complex, intent(out) :: cs_half(0:JT65_NH) + + integer :: k + integer(c_int) :: nfft_c, ndim_c, isign_c, iform_c + + block + real(c_float), save, target :: work(2*(JT65_NH+1)) + complex(c_float_complex), pointer :: work_c(:) + + call c_f_pointer(c_loc(work), work_c, [JT65_NH+1]) + + work(1:JT65_NFFT) = real(s_real, kind=c_float) + + nfft_c = JT65_NFFT + ndim_c = 1 + isign_c = 1 + iform_c = 0 + call four2a(work_c, nfft_c, ndim_c, isign_c, iform_c) + + do k = 0, JT65_NH + cs_half(k) = cmplx(real(work_c(k+1)), aimag(work_c(k+1))) + enddo + end block +end subroutine r2c_legacy + +subroutine c2r_legacy(cs_half, s_real) + use iso_c_binding + use four2a_mod, only: four2a + implicit none + + complex, intent(in) :: cs_half(0:JT65_NH) + real, intent(out) :: s_real(JT65_NFFT) + + integer :: k + integer(c_int) :: nfft_c, ndim_c, isign_c, iform_c + + block + real(c_float), target :: work(2*(JT65_NH+1)) + complex(c_float_complex), pointer :: work_c(:) + + call c_f_pointer(c_loc(work), work_c, [JT65_NH+1]) + + ! load packed half-spectrum: cs_half(0..nh) → work_c(1..nh+1) + do k = 0, JT65_NH + work_c(k+1) = cmplx(real(cs_half(k), kind=c_float), & + aimag(cs_half(k)), kind=c_float) + enddo + + ! c2r: iform = -1 + nfft_c = JT65_NFFT + ndim_c = 1 + isign_c = 1 + iform_c = -1 + call four2a(work_c, nfft_c, ndim_c, isign_c, iform_c) + + ! real output in first nfft reals + s_real = real(work(1:JT65_NFFT)) + end block + +end subroutine c2r_legacy + +end module four2a_legacy_wrap_mod diff --git a/map65/libm65/ftninit.f90 b/map65/libm65/ftninit.f90 index 26911a19..28f95fd4 100644 --- a/map65/libm65/ftninit.f90 +++ b/map65/libm65/ftninit.f90 @@ -1,19 +1,24 @@ -subroutine ftninit(appd) +module ftninit_mod + implicit none +contains +subroutine ftninit(appd) use timer_module, only: timer use, intrinsic :: iso_c_binding, only: C_NULL_CHAR + use pfx_data_mod + use pfx_mod + use pfxdump_mod use FFTW3 - character*(*) appd - character addpfx*8 + character(*), intent(in) :: appd character wisfile*256 - common/pfxcom/addpfx + integer :: iret addpfx=' ' call pfxdump(appd//'/prefixes.txt') open(12,file=appd//'/wb_q65.txt',status='unknown') open(13,file=appd//'/map65.log',status='unknown') ! open(19,file=appd//'/livecq.txt',status='unknown') ! not written with new livecq code - open(21,file=appd//'/map65_rx.log',status='unknown',access='append',err=950) + open(21, file=appd//'/map65_rx.log', status='unknown', position='append', err=950) open(26,file=appd//'/tmp26.txt',status='unknown') ! Import FFTW wisdom, if available: @@ -29,3 +34,4 @@ subroutine ftninit(appd) stop end subroutine ftninit +end module ftninit_mod diff --git a/map65/libm65/ftnquit.f90 b/map65/libm65/ftnquit.f90 index b74e2b9e..7543c19e 100644 --- a/map65/libm65/ftnquit.f90 +++ b/map65/libm65/ftnquit.f90 @@ -1,8 +1,33 @@ +module ftnquit_mod + use filbig_mod + use four2a_mod + use iso_fortran_env, only: real64, real32 + use filbig_mod, only: MAXFFT2 + + implicit none +contains + subroutine ftnquit + implicit none + + real(real32) :: dd_dummy(1,1) + integer :: nmax_dummy = -1 + real(real64) :: f0_dummy = 0.0d0 + integer :: newdat_dummy = 0 + integer :: nfsample_dummy = 0 + logical :: xpol_dummy = .false. + complex :: c4a_dummy(MAXFFT2), c4b_dummy(MAXFFT2) + integer :: n4_dummy = 0 + + complex :: a_dummy(1) -! Destroy the FFTW plans - call four2a(a,-1,1,1,1) - call filbig(id,-1,1,f0,newdat,nfsample,c4a,c4b,n4) + call four2a(a_dummy, -1, 1, 1, 1) + + call filbig(dd_dummy, nmax_dummy, f0_dummy, newdat_dummy, & + nfsample_dummy, xpol_dummy, c4a_dummy, c4b_dummy, n4_dummy) - return end subroutine ftnquit + +end module ftnquit_mod + + diff --git a/map65/libm65/ftrsd2.c b/map65/libm65/ftrsd2.c index 7d8dd366..f281e72d 100644 --- a/map65/libm65/ftrsd2.c +++ b/map65/libm65/ftrsd2.c @@ -132,15 +132,14 @@ codeword is "best". jj = (62-i)/8; thresh0[i] = 1.3*perr[ii][jj]; } - if(nsum<=0) return; - pp1=0.0; pp2=0.0; + if (nsum>0) { for (k=1; k<=ntrials; k++) { memset(era_pos,0,51*sizeof(int)); memcpy(workdat,rxdat,sizeof(rxdat)); -/* +/* Mark a subset of the symbols as erasures. Run through the ranked symbols, starting with the worst, i=0. NB: j is the symbol-vector index of the symbol with rank i. @@ -162,10 +161,10 @@ NB: j is the symbol-vector index of the symbol with rank i. } } - nerr=decode_rs_int(rs,workdat,era_pos,numera,0); + nerr=decode_rs_int(rs,workdat,era_pos,numera,0); if( nerr >= 0 ) { // We have a candidate codeword. Find its hard and soft distance from - // the received word. Also find pp1 and pp2 from the full array + // the received word. Also find pp1 and pp2 from the full array // s3(64,63) of synchronized symbol spectra. ncandidates=ncandidates+1; nhard=0; @@ -198,7 +197,15 @@ NB: j is the symbol-vector index of the symbol with rank i. } if(k == ntrials) ntry[0]=k; } - + } + // nsum<=0 (or no erasure trial found a valid codeword) falls through to + // here with ncandidates==0 and the *_min sentinels left at their "nothing + // found" initial values (32768) -- previously this case (nsum<=0) hit an + // early "return;" that skipped writing param[]/correct[]/ntry[] entirely, + // leaving the caller's pre-call param=0 in place, which incorrectly read + // as an accepted decode (ntotal=0 trivially clears the accept threshold) + // and unpacked whatever garbage was sitting in the uninitialized + // "correct" array as if it were a real message. param[0]=ncandidates; param[1]=nhard_min; param[2]=nsoft_min; diff --git a/map65/libm65/ftrsd2_mod.f90 b/map65/libm65/ftrsd2_mod.f90 new file mode 100644 index 00000000..0737e9c0 --- /dev/null +++ b/map65/libm65/ftrsd2_mod.f90 @@ -0,0 +1,12 @@ +module ftrsd2_mod + use iso_c_binding + implicit none + interface + subroutine ftrsd2_(mrsym, mrprob, mr2sym, mr2prob, ntrials0, correct, param, ntry) bind(C, name="ftrsd2_") + use iso_c_binding + integer(c_int), intent(in) :: mrsym(*), mrprob(*), mr2sym(*), mr2prob(*) + integer(c_int), intent(in) :: ntrials0 + integer(c_int), intent(out) :: correct(*), param(*), ntry(*) + end subroutine ftrsd2_ + end interface +end module ftrsd2_mod diff --git a/map65/libm65/gen65.f90 b/map65/libm65/gen65.f90 index f09d0868..0be99fc4 100644 --- a/map65/libm65/gen65.f90 +++ b/map65/libm65/gen65.f90 @@ -1,99 +1,208 @@ -subroutine gen65(message,mode65,samfac,nsendingsh,msgsent,iwave,nwave) - -! Encodes a JT65 message into a wavefile. -! Executes in 17 ms on opti-745. +! NOTE: This routine must remain a top-level Fortran subroutine. +! It has CHARACTER arguments, which require hidden length parameters +! that are passed automatically by the Fortran ABI. +! Keeping it outside any module preserves the legacy Fortran/C++ ABI +! and ensures the caller can continue to use the symbol name gen65_. +subroutine gen65_core(message, mode65, samfac, nsendingsh, msgsent, iwave, nwave) + use iso_c_binding use packjt + use chkmsg_mod + use graycode_mod + use rs_mod, only: rs_encode_ + use interleave63_mod + implicit none + + !-------------------------------------------------------------------- + ! Parameters + !-------------------------------------------------------------------- + integer, parameter :: NMAX = 2*60*11025 + + !-------------------------------------------------------------------- + ! Arguments + !-------------------------------------------------------------------- + character(len=22), intent(inout) :: message + integer, intent(in) :: mode65 + real(8), intent(in) :: samfac + integer, intent(out) :: nsendingsh + character(len=22), intent(out) :: msgsent + integer(2), intent(out) :: iwave(NMAX) + integer, intent(out) :: nwave + + !-------------------------------------------------------------------- + ! Locals + !-------------------------------------------------------------------- + character(len=3) :: cok + real(8) :: dt, phi, f, f0, dfgen, dphi, twopi + integer :: dgen(12) + integer :: sent(63) + logical :: first + integer :: nprc(126) + real :: pr(126), flip + integer :: nspecial + integer :: nsym, nsps + integer :: i, j, ii, k, itype + real(8) :: xphi + + !-------------------------------------------------------------------- + ! Initialization + !-------------------------------------------------------------------- + data nprc / & + 1,0,0,1,1,0,0,0,1,1,1,1,1,1,0,1,0,1,0,0, & + 0,1,0,1,1,0,0,1,0,0,0,1,1,1,0,0,1,1,1,1, & + 0,1,1,0,1,1,1,1,0,0,0,1,1,0,1,0,1,0,1,1, & + 0,0,1,1,0,1,0,1,0,1,0,0,1,0,0,0,0,0,0,1, & + 1,0,0,0,0,0,0,0,1,1,0,1,0,0,1,0,1,1,0,1, & + 0,1,0,1,0,0,1,1,0,0,1,0,0,1,0,0,0,0,1,1, & + 1,1,1,1,1,1 / + data twopi / 6.283185307179586476d0 / + data first /.true./ + save first, pr + + !-------------------------------------------------------------------- + ! Precompute PR sequence once + !-------------------------------------------------------------------- + if (first) then + do i = 1, 126 + pr(i) = 2*nprc(i) - 1 + end do + first = .false. + end if + + !-------------------------------------------------------------------- + ! Message classification + !-------------------------------------------------------------------- + !write(*,*) 'GEN65 received message', message + call chkmsg(message, cok, nspecial, flip) + + if (nspecial == 0) then - parameter (NMAX=2*60*11025) !Max length of wave file - character*22 message !Message to be generated - character*22 msgsent !Message as it will be received - character*3 cok !' ' or 'OOO' - real*8 dt,phi,f,f0,dfgen,dphi,twopi,samfac - integer*2 iwave(NMAX) !Generated wave file - integer dgen(12) - integer sent(63) - logical first - integer nprc(126) - real pr(126) - data nprc/1,0,0,1,1,0,0,0,1,1,1,1,1,1,0,1,0,1,0,0, & - 0,1,0,1,1,0,0,1,0,0,0,1,1,1,0,0,1,1,1,1, & - 0,1,1,0,1,1,1,1,0,0,0,1,1,0,1,0,1,0,1,1, & - 0,0,1,1,0,1,0,1,0,1,0,0,1,0,0,0,0,0,0,1, & - 1,0,0,0,0,0,0,0,1,1,0,1,0,0,1,0,1,1,0,1, & - 0,1,0,1,0,0,1,1,0,0,1,0,0,1,0,0,0,0,1,1, & - 1,1,1,1,1,1/ - data twopi/6.283185307179586476d0/,first/.true./ - save - - if(first) then - do i=1,126 - pr(i)=2*nprc(i)-1 - enddo - first=.false. - endif - - call chkmsg(message,cok,nspecial,flip) - if(nspecial.eq.0) then - call packmsg(message,dgen,itype) !Pack message into 72 bits - nsendingsh=0 - if(iand(dgen(10),8).ne.0) nsendingsh=-1 !Plain text flag - - call rs_encode(dgen,sent) - call interleave63(sent,1) !Apply interleaving - call graycode(sent,63,1) !Apply Gray code - nsym=126 !Symbols per transmission - nsps=4096 + call packmsg(message, dgen, itype) + + nsendingsh = 0 + if (iand(dgen(10), 8) /= 0) nsendingsh = -1 + + call rs_encode_(dgen, sent) + call interleave63(sent, 1) + call graycode(sent, 63, 1) + + nsym = 126 + nsps = 4096 else - nsym=32 - nsps=16384 - nsendingsh=1 !Flag for shorthand message - endif - if(mode65.eq.0) go to 900 - -! Set up necessary constants - dt=1.d0/(samfac*11025.d0) - f0=118*11025.d0/1024 - dfgen=mode65*11025.d0/4096.d0 - phi=0.d0 - dphi=twopi*dt*f0 - i=0 - k=0 - do j=1,nsym - if(message(1:5).ne.'@TUNE') then - f=f0 - if(nspecial.ne.0 .and. mod(j,2).eq.0) f=f0+10*nspecial*dfgen - if(nspecial.eq.0 .and. flip*pr(j).lt.0.0) then - k=k+1 - f=f0+(sent(k)+2)*dfgen - endif - dphi=twopi*dt*f - endif - do ii=1,nsps - phi=phi+dphi - if(phi.gt.twopi) phi=phi-twopi - xphi=phi - i=i+1 - iwave(2*i-1)=32767.0*cos(xphi) - iwave(2*i)=32767.0*sin(xphi) - enddo - enddo - - iwave(2*nsym*nsps+1:)=0 - nwave=2*nsym*nsps + 5512 - call unpackmsg(dgen,msgsent) - if(flip.lt.0.0) then - do i=22,1,-1 - if(msgsent(i:i).ne.' ') goto 10 - enddo -10 msgsent=msgsent(1:i)//' OOO' - endif - - if(nsendingsh.eq.1) then - if(nspecial.eq.2) msgsent='RO' - if(nspecial.eq.3) msgsent='RRR' - if(nspecial.eq.4) msgsent='73' - endif - -900 return -end subroutine gen65 + nsym = 32 + nsps = 16384 + nsendingsh = 1 + end if + + if (mode65 == 0) then + nwave = 0 + return + end if + + !-------------------------------------------------------------------- + ! Waveform generation + !-------------------------------------------------------------------- + dt = 1.d0 / (samfac * 11025.d0) + f0 = 118 * 11025.d0 / 1024.d0 + dfgen = mode65 * 11025.d0 / 4096.d0 + phi = 0.d0 + dphi = twopi * dt * f0 + + i = 0 + k = 0 + + do j = 1, nsym + if (message(1:5) /= '@TUNE') then + f = f0 + if (nspecial /= 0 .and. mod(j,2) == 0) f = f0 + 10*nspecial*dfgen + if (nspecial == 0 .and. flip*pr(j) < 0.0) then + k = k + 1 + f = f0 + (sent(k) + 2)*dfgen + end if + dphi = twopi * dt * f + end if + + do ii = 1, nsps + phi = phi + dphi + if (phi > twopi) phi = phi - twopi + xphi = phi + i = i + 1 + iwave(2*i-1) = 32767.0 * cos(xphi) + iwave(2*i) = 32767.0 * sin(xphi) + end do + end do + + !-------------------------------------------------------------------- + ! Finalize waveform + !-------------------------------------------------------------------- + iwave(2*nsym*nsps+1:) = 0 + nwave = 2*nsym*nsps + 5512 + + !-------------------------------------------------------------------- + ! Decode message for display + !-------------------------------------------------------------------- + if (nspecial == 0) then + call unpackmsg(dgen, msgsent) + write(*,*) 'GEN65 msgsent is: ',msgsent + if (flip < 0.0) then + do i = 22, 1, -1 + if (msgsent(i:i) /= ' ') exit + end do + msgsent = msgsent(1:i) // ' OOO' + end if + else + msgsent = ' ' ! or leave as-is; will be overwritten below + end if + + if (nsendingsh == 1) then + if (nspecial == 2) msgsent = 'RO' + if (nspecial == 3) msgsent = 'RRR' + if (nspecial == 4) msgsent = '73' + end if + +end subroutine gen65_core + +subroutine gen65_c(msg, mode65, samfac, nsendingsh, msgsent_c, iwave_c, nwave) & + bind(C, name="gen65_") + use iso_c_binding + implicit none + + ! C-side arguments + character(kind=c_char), dimension(*), intent(inout) :: msg + integer(c_int), intent(in) :: mode65 + real(c_double), intent(in) :: samfac + integer(c_int), intent(out) :: nsendingsh + character(kind=c_char), dimension(*),intent(out) :: msgsent_c + integer(c_short), dimension(*), intent(out) :: iwave_c + integer(c_int), intent(out) :: nwave + + ! Fortran locals + character(len=22) :: fmsg, fmsgsent + integer(2), save :: fiwave(2*60*11025) + integer :: i + + ! Copy C msg ? Fortran CHARACTER(22) + fmsg = ' ' + do i = 1, 22 + if (msg(i) == c_null_char) exit + fmsg(i:i) = achar(iachar(msg(i))) + end do + + ! Call the real Fortran routine + call gen65_core(fmsg, mode65, samfac, nsendingsh, fmsgsent, fiwave, nwave) + + ! Copy Fortran msgsent ? C buffer + do i = 1, 22 + msgsent_c(i) = fmsgsent(i:i) + end do + msgsent_c(23) = c_null_char ! null terminate + + ! Copy waveform + do i = 1, nwave + iwave_c(i) = fiwave(i) + end do + +end subroutine gen65_c + + +!does not require end module
\ No newline at end of file diff --git a/map65/libm65/gen_q65_cwave.f90 b/map65/libm65/gen_q65_cwave.f90 index 115d1fc4..2f5c1262 100644 --- a/map65/libm65/gen_q65_cwave.f90 +++ b/map65/libm65/gen_q65_cwave.f90 @@ -1,52 +1,95 @@ -subroutine gen_q65_cwave(msg,ntxfreq,ntone_spacing,msgsent,cwave,nwave) +module gen_q65_cwave_mod + implicit none +contains -! Encodes a Q65 message to yield complex cwave() at fsample = 96000 Hz +subroutine gen_q65_cwave(msg,ntxfreq,ntone_spacing,fsample,msgsent,cwave,nwave) use packjt use q65_encoding - parameter (NMAX=60*96000) - character*24 msg !w3sz was *22 - character*24 msgsent !w3sz was *22 !Message as it will be received - character*37 msg37 - real*8 t,dt,phi,f,f0,dfgen,dphi,twopi,tsym - complex cwave(NMAX) - integer codeword(65),itone(85) - integer icos7(0:6) - data icos7/2,5,6,0,4,1,3/ !Defines a 7x7 Costas array - data twopi/6.283185307179586476d0/ + use iso_fortran_env, only: real64 + + !-------------------------------------------------------------------- + ! Arguments (with correct intent and explicit types) + !-------------------------------------------------------------------- + ! fsample is the actual sample rate in Hz + real(real64), intent(in) :: fsample + character*24, intent(in) :: msg + integer, intent(in) :: ntxfreq + integer, intent(in) :: ntone_spacing + character*24, intent(out) :: msgsent + complex, intent(out) :: cwave(:) + integer, intent(out) :: nwave + + !-------------------------------------------------------------------- + ! Local character variables + !-------------------------------------------------------------------- + character*37 :: msg37,msgsent37 + + !-------------------------------------------------------------------- + ! Explicit declarations for all formerly implicit variables + !-------------------------------------------------------------------- + ! Implicit REAL(4) variables (A–H, O–Z) + real(real64) :: t, dt, phi, f, f0, dfgen, dphi, twopi, tsym, xphi + + ! Implicit INTEGER variables (I–N) + integer :: i, j, j0, nsym + + ! Explicit locals + integer :: codeword(65), itone(85) + integer :: icos7(0:6) + logical :: success + + data icos7 /2,5,6,0,4,1,3/ + data twopi /6.283185307179586476d0/ save - msgsent=msg - msg37='' - msg37(1:24)=msg !w3sz was 1:22 - call get_q65_tones(msg37,codeword,itone) - -! Set up necessary constants - nsym=85 - tsym=7200.d0/12000.d0 - dt=1.d0/96000.d0 - f0=ntxfreq - dfgen=ntone_spacing*12000.d0/7200.d0 - phi=0.d0 - dphi=twopi*dt*f0 - i=0 - nwave=85*7200*96000.d0/12000.d0 - t=0.d0 - j0=0 - do i=1,nwave - t=t+dt - j=t/tsym + 1 - if(j.gt.85) exit - if(j.ne.j0) then - f=f0 + itone(j)*dfgen - dphi=twopi*dt*f - j0=j + !-------------------------------------------------------------------- + ! Begin logic (unchanged from legacy) + !-------------------------------------------------------------------- + msg37 = '' + msg37(1:24) = msg + + call get_q65_tones(msg37, codeword, itone, msgsent37, success) + msgsent = msgsent37(1:len(msgsent)) + if(.not.success) then + cwave=0 + nwave=0 + return + endif + + ! Constants + nsym = 85 + tsym = 7200.d0 / 12000.d0 ! symbol duration (unchanged) + dt = 1.d0 / fsample ! sample interval + f0 = ntxfreq + dfgen = ntone_spacing * 12000.d0 / 7200.d0 ! tone spacing in Hz (unchanged) + + phi = 0.d0 + dphi = twopi * dt * f0 + + ! total samples for the 85-symbol Q65-60A waveform + nwave = int( nsym * tsym * fsample + 0.5d0 ) + + t = 0.d0 + j0 = 0 + + do i = 1, nwave + t = t + dt + j = min(nsym, int(t/tsym) + 1) + + if (j /= j0) then + f = f0 + itone(j) * dfgen + dphi = twopi * dt * f + j0 = j endif - phi=phi+dphi - if(phi.gt.twopi) phi=phi-twopi - xphi=phi - cwave(i)=cmplx(cos(xphi),-sin(xphi)) + + phi = phi + dphi + if (phi > twopi) phi = phi - twopi + + xphi = phi + cwave(i) = cmplx(cos(xphi), -sin(xphi)) enddo -999 return end subroutine gen_q65_cwave + +end module gen_q65_cwave_mod diff --git a/map65/libm65/gen_q65_wave.f90 b/map65/libm65/gen_q65_wave.f90 index bd91c8dd..cfdd04da 100644 --- a/map65/libm65/gen_q65_wave.f90 +++ b/map65/libm65/gen_q65_wave.f90 @@ -1,54 +1,102 @@ -subroutine gen_q65_wave(msg,ntxfreq,mode65,msgsent,iwave,nwave) +! NOTE: This routine must remain a top-level Fortran subroutine. +! It has CHARACTER arguments, which require hidden length parameters +! that are passed automatically by the Fortran ABI. +! Keeping it outside any module preserves the legacy Fortran/C++ ABI +! and ensures the caller can continue to use the symbol name gen_q65_wave_. -! Encodes a Q65 message to yield complex iwave() at fsample = 11025 Hz +subroutine gen_q65_wave(msg,ntxfreq,mode65,msgsent,iwave,nwave) use packjt use q65_encoding - parameter (NMAX=2*60*11025) - character*22 msg - character*22 msgsent !Message as it will be received - character*37 msg37 - real*8 t,dt,phi,f,f0,dfgen,dphi,twopi,tsym - integer codeword(65),itone(85) - integer*2 iwave(NMAX) - integer icos7(0:6) - data icos7/2,5,6,0,4,1,3/ !Defines a 7x7 Costas array - data twopi/6.283185307179586476d0/ + implicit none + + integer, parameter :: NMAX = 2*60*11025 + + !-------------------------------------------------------------------- + ! Arguments (must NOT use bind(C) because of CHARACTER arguments) + !-------------------------------------------------------------------- + character*22, intent(in) :: msg + integer, intent(in) :: ntxfreq + integer, intent(in) :: mode65 + character*22, intent(out) :: msgsent + integer*2, intent(out) :: iwave(NMAX) + integer, intent(out) :: nwave + + !-------------------------------------------------------------------- + ! Local character + !-------------------------------------------------------------------- + character*37 :: msg37,msgsent37 + + !-------------------------------------------------------------------- + ! Explicit REAL*8 variables (as in original) + !-------------------------------------------------------------------- + real*8 :: t, dt, phi, f, f0, dfgen, dphi, twopi, tsym + + !-------------------------------------------------------------------- + ! Formerly implicit variables + !-------------------------------------------------------------------- + integer :: i, j, j0, nsym, ndf, iz + real :: xphi + + integer :: codeword(65), itone(85) + integer :: icos7(0:6) + logical :: success + + data icos7 /2,5,6,0,4,1,3/ + data twopi /6.283185307179586476d0/ save - msgsent=msg - msg37='' - msg37(1:22)=msg - call get_q65_tones(msg37,codeword,itone) - -! Set up necessary constants - nsym=85 - tsym=7200.d0/12000.d0 - dt=1.d0/11025.d0 - f0=ntxfreq - ndf=2**(mode65-1) - dfgen=ndf*12000.d0/7200.d0 - phi=0.d0 - dphi=twopi*dt*f0 - i=0 - iz=85*7200*11025.d0/12000.d0 - t=0.d0 - j0=0 - do i=1,iz - t=t+dt - j=t/tsym + 1.0 - if(j.ne.j0) then - f=f0 + itone(j)*dfgen - dphi=twopi*dt*f - j0=j + !-------------------------------------------------------------------- + ! Logic (unchanged) + !-------------------------------------------------------------------- + msg37 = '' + msg37(1:22) = msg + + ! Strip JT65-style OOO suffix if present + if (len_trim(msg37) >= 4) then + if (msg37(len_trim(msg37)-3:len_trim(msg37)) == ' OOO') then + msg37(len_trim(msg37)-3:) = ' ' + end if + end if + + call get_q65_tones(msg37, codeword, itone, msgsent37, success) + msgsent = msgsent37(1:len(msgsent)) + if(.not.success) then + iwave=0 + nwave=0 + return + endif + + nsym = 85 + tsym = 7200.d0/12000.d0 + dt = 1.d0/11025.d0 + f0 = ntxfreq + ndf = 2**(mode65-1) + dfgen = ndf*12000.d0/7200.d0 + phi = 0.d0 + dphi = twopi*dt*f0 + i = 0 + iz = 85*7200*11025.d0/12000.d0 + t = 0.d0 + j0 = 0 + + do i = 1, iz + t = t + dt + j = min(nsym, int(t/tsym) + 1) + if (j /= j0) then + f = f0 + itone(j)*dfgen + dphi = twopi*dt*f + j0 = j endif - phi=phi+dphi - if(phi.gt.twopi) phi=phi-twopi - xphi=phi - iwave(2*i-1)=32767.0*cos(xphi) - iwave(2*i)=32767.0*sin(xphi) + phi = phi + dphi + if (phi > twopi) phi = phi - twopi + xphi = real(phi) + iwave(2*i-1) = 32767.0*cos(xphi) + iwave(2*i) = 32767.0*sin(xphi) enddo - nwave=2*iz -999 return + nwave = 2*iz + end subroutine gen_q65_wave + +! does not require end module diff --git a/map65/libm65/geocentric.f90 b/map65/libm65/geocentric.f90 index 59ed90b5..3c79ab68 100644 --- a/map65/libm65/geocentric.f90 +++ b/map65/libm65/geocentric.f90 @@ -1,17 +1,23 @@ -subroutine geocentric(alat,elev,hlt,erad) - - implicit real*8 (a-h,o-z) - -! IAU 1976 flattening f, equatorial radius a - f = 1.d0/298.257d0 - a = 6378140.d0 - c = 1.d0/sqrt(1.d0 + (-2.d0 + f)*f*sin(alat)*sin(alat)) - arcf = (a*c + elev)*cos(alat) - arsf = (a*(1.d0 - f)*(1.d0 - f)*c + elev)*sin(alat) - hlt = datan2(arsf,arcf) - erad = sqrt(arcf*arcf + arsf*arsf) - erad = 0.001d0*erad - - return -end subroutine geocentric +module geocentric_mod + use iso_fortran_env, only: real64 + implicit none +contains + subroutine geocentric(alat,elev,hlt,erad) + implicit none + real(real64), intent(in) :: alat, elev + real(real64), intent(out) :: hlt, erad + real(real64) :: f, a_radius, c, arcf, arsf + + ! IAU 1976 flattening f, equatorial radius a + f = 1.d0/298.257d0 + a_radius = 6378140.d0 + c = 1.d0/sqrt(1.d0 + (-2.d0 + f)*f*sin(alat)*sin(alat)) + arcf = (a_radius*c + elev)*cos(alat) + arsf = (a_radius*(1.d0 - f)*(1.d0 - f)*c + elev)*sin(alat) + hlt = atan2(arsf,arcf) + erad = sqrt(arcf*arcf + arsf*arsf) + erad = 0.001d0*erad + + end subroutine geocentric +end module geocentric_mod diff --git a/map65/libm65/getdphi.f90 b/map65/libm65/getdphi.f90 index e55d7120..24cf0ab4 100644 --- a/map65/libm65/getdphi.f90 +++ b/map65/libm65/getdphi.f90 @@ -1,18 +1,36 @@ +module getdphi_mod + implicit none +contains + subroutine getdphi(qphi) + use stdout_channel_mod, only: write_stdout + implicit none + + ! Arguments + real, intent(in) :: qphi(12) + + ! Locals + real :: c, dphi, s, th + integer :: i + character(len=32) :: line + + s = 0.0 + c = 0.0 - real qphi(12) + do i = 1, 12 + th = i * 30.0 / 57.2957795 ! convert degrees to radians + s = s + qphi(i) * sin(th) + c = c + qphi(i) * cos(th) + end do - s=0. - c=0. - do i=1,12 - th=i*30/57.2957795 - s=s+qphi(i)*sin(th) - c=c+qphi(i)*cos(th) - enddo + dphi = 57.2957795 * atan2(s, c) + write(line,1010) nint(dphi) +1010 format('!Best-fit Dphi =', i4, ' deg') + ! Plain write(*,...) went to real process stdout, which nothing reads any + ! more -- the GUI now gets decoder output through the write_stdout shared- + ! memory channel instead, so this line never reached the Messages window. + call write_stdout(trim(line)//new_line('a')) - dphi=57.2957795*atan2(s,c) - write(*,1010) nint(dphi) -1010 format('!Best-fit Dphi =',i4,' deg') +end subroutine getdphi - return - end +end module getdphi_mod diff --git a/map65/libm65/getpfx1.f90 b/map65/libm65/getpfx1.f90 index 40fcc369..ba7faa37 100644 --- a/map65/libm65/getpfx1.f90 +++ b/map65/libm65/getpfx1.f90 @@ -1,19 +1,34 @@ -subroutine getpfx1(callsign,k,nv2) +module getpfx1_mod + implicit none +contains - character*12 callsign0,callsign,lof,rof - character*8 c - character addpfx*8,tpfx*4,tsfx*3 - logical ispfx,issfx,invalid - common/pfxcom/addpfx - include 'pfx.f90' +subroutine getpfx1(callsign, k, nv2) - callsign0=callsign - nv2=0 - iz=index(callsign,' ') - 1 - if(iz.lt.0) iz=12 - islash=index(callsign(1:iz),'/') - k=0 - c=' ' + use pfx_data_mod + use pfx_mod + use nchar_mod + use k2grid_mod + + implicit none + + character(len=12), intent(inout) :: callsign + integer, intent(out) :: k, nv2 + + character(len=12) :: callsign0, lof, rof + character(len=8) :: c + character(len=4) :: tpfx + character(len=3) :: tsfx + logical :: ispfx, issfx, invalid + integer :: i, islash, iz, llof, lrof + + callsign0 = callsign + nv2 = 1 + iz = index(callsign,' ') - 1 + if (iz < 0) iz = 12 + islash = index(callsign(1:iz),'/') + k = 0 + c = ' ' + if(islash.gt.0 .and. islash.le.(iz-4)) then ! Add-on prefix c=callsign(1:islash-1) @@ -21,11 +36,13 @@ subroutine getpfx1(callsign,k,nv2) do i=1,NZ if(pfx(i)(1:4).eq.c) then k=i + nv2=2 go to 10 endif enddo if(addpfx.eq.c) then k=449 + nv2=2 go to 10 endif @@ -36,6 +53,7 @@ subroutine getpfx1(callsign,k,nv2) do i=1,NZ2 if(sfx(i).eq.c(1:1)) then k=400+i + nv2=3 go to 10 endif enddo @@ -45,6 +63,7 @@ subroutine getpfx1(callsign,k,nv2) ! Original JT65 would force this compound callsign to be treated as ! plain text. In JT65v2, we will encode the prefix or suffix into nc1. ! The task here is to compute the proper value of k. +! TODO: Reject invalid compound characters before nchar can stop MAP65. lof=callsign0(:islash-1) rof=callsign0(islash+1:) llof=len_trim(lof) @@ -74,7 +93,7 @@ subroutine getpfx1(callsign,k,nv2) k=37*k + nchar(tpfx(2:2)) k=37*k + nchar(tpfx(3:3)) k=37*k + nchar(tpfx(4:4)) - nv2=1 + nv2=4 i=index(callsign0,'/') callsign=callsign0(:i-1) callsign=callsign0(i+1:) @@ -84,7 +103,7 @@ subroutine getpfx1(callsign,k,nv2) k=nchar(tsfx(1:1)) k=37*k + nchar(tsfx(2:2)) k=37*k + nchar(tsfx(3:3)) - nv2=2 + nv2=5 i=index(callsign0,'/') callsign=callsign0(:i-1) endif @@ -93,4 +112,5 @@ subroutine getpfx1(callsign,k,nv2) return end subroutine getpfx1 +end module getpfx1_mod diff --git a/map65/libm65/getpfx2.f90 b/map65/libm65/getpfx2.f90 index d747e7f2..82b9ca0b 100644 --- a/map65/libm65/getpfx2.f90 +++ b/map65/libm65/getpfx2.f90 @@ -1,9 +1,15 @@ +module getpfx2_mod + implicit none +contains + subroutine getpfx2(k0,callsign) - character callsign*12 - include 'pfx.f90' - character addpfx*8 - common/pfxcom/addpfx + use pfx_data_mod + use pfx_mod + + integer, intent(in) :: k0 + character(len=12), intent(inout) :: callsign + integer :: iz,k k=k0 if(k.gt.450) k=k-450 @@ -21,4 +27,5 @@ subroutine getpfx2(k0,callsign) return end subroutine getpfx2 +end module getpfx2_mod diff --git a/map65/libm65/gran_interface.f90 b/map65/libm65/gran_interface.f90 new file mode 100644 index 00000000..8635c0ea --- /dev/null +++ b/map65/libm65/gran_interface.f90 @@ -0,0 +1,17 @@ +module gran_interface + use iso_c_binding + implicit none + + interface + function gran() bind(C, name='gran_') + import :: c_float + real(c_float) :: gran + end function gran + + function rran() bind(C, name='rran_') + import :: c_float + real(c_float) :: rran + end function rran + end interface + +end module gran_interface diff --git a/map65/libm65/graycode.f90 b/map65/libm65/graycode.f90 index 2074241a..ea818c0f 100644 --- a/map65/libm65/graycode.f90 +++ b/map65/libm65/graycode.f90 @@ -1,10 +1,18 @@ -subroutine graycode(dat,n,idir) - - integer dat(n) - do i=1,n - dat(i)=igray(dat(i),idir) - enddo - - return -end subroutine graycode +module graycode_mod + implicit none + interface + integer function igray(n, idir) + integer, intent(in) :: n, idir + end function igray + end interface +contains + subroutine graycode(dat, n, idir) + integer, intent(in) :: n, idir + integer, intent(inout) :: dat(n) + integer :: i + do i = 1, n + dat(i) = igray(dat(i), idir) + enddo + end subroutine graycode +end module graycode_mod diff --git a/map65/libm65/graycode65.f90 b/map65/libm65/graycode65.f90 index bb2c669c..2129a146 100644 --- a/map65/libm65/graycode65.f90 +++ b/map65/libm65/graycode65.f90 @@ -1,9 +1,23 @@ -subroutine graycode65(dat,n,idir) +module graycode65_mod + implicit none - integer dat(n) - do i=1,n - dat(i)=igray(dat(i),idir) - enddo + ! Fortran-only interface to igray + interface + integer function igray(n, idir) + integer, intent(in) :: n, idir + end function igray + end interface - return -end subroutine graycode65 +contains + + subroutine graycode65(dat, n, idir) + integer, intent(in) :: n, idir + integer, intent(inout) :: dat(n) + integer :: i + + do i = 1, n + dat(i) = igray(dat(i), idir) + enddo + end subroutine graycode65 + +end module graycode65_mod diff --git a/map65/libm65/grid2deg.f90 b/map65/libm65/grid2deg.f90 index 344351dd..b4552031 100644 --- a/map65/libm65/grid2deg.f90 +++ b/map65/libm65/grid2deg.f90 @@ -1,38 +1,42 @@ -subroutine grid2deg(grid0,dlong,dlat) +module grid2deg_mod + implicit none +contains + subroutine grid2deg(grid0,dlong,dlat) + character(len=6), intent(in) :: grid0 + real, intent(out) :: dlong, dlat + + character(len=6) grid + character(len=1) g1,g2,g3,g4,g5,g6 + integer :: i, nlong, n20d, nlat + real :: xminlong, xminlat -! Converts Maidenhead grid locator to degrees of West longitude -! and North latitude. + grid=grid0 + i=ichar(grid(5:5)) + if(grid(5:5).eq.' ' .or. i.le.64 .or. i.ge.128) grid(5:6)='mm' - character*6 grid0,grid - character*1 g1,g2,g3,g4,g5,g6 + if(grid(1:1).ge.'a' .and. grid(1:1).le.'z') grid(1:1)= & + char(ichar(grid(1:1))+ichar('A')-ichar('a')) + if(grid(2:2).ge.'a' .and. grid(2:2).le.'z') grid(2:2)= & + char(ichar(grid(2:2))+ichar('A')-ichar('a')) + if(grid(5:5).ge.'A' .and. grid(5:5).le.'Z') grid(5:5)= & + char(ichar(grid(5:5))-ichar('A')+ichar('a')) + if(grid(6:6).ge.'A' .and. grid(6:6).le.'Z') grid(6:6)= & + char(ichar(grid(6:6))-ichar('A')+ichar('a')) - grid=grid0 - i=ichar(grid(5:5)) - if(grid(5:5).eq.' ' .or. i.le.64 .or. i.ge.128) grid(5:6)='mm' + g1=grid(1:1) + g2=grid(2:2) + g3=grid(3:3) + g4=grid(4:4) + g5=grid(5:5) + g6=grid(6:6) - if(grid(1:1).ge.'a' .and. grid(1:1).le.'z') grid(1:1)= & - char(ichar(grid(1:1))+ichar('A')-ichar('a')) - if(grid(2:2).ge.'a' .and. grid(2:2).le.'z') grid(2:2)= & - char(ichar(grid(2:2))+ichar('A')-ichar('a')) - if(grid(5:5).ge.'A' .and. grid(5:5).le.'Z') grid(5:5)= & - char(ichar(grid(5:5))-ichar('A')+ichar('a')) - if(grid(6:6).ge.'A' .and. grid(6:6).le.'Z') grid(6:6)= & - char(ichar(grid(6:6))-ichar('A')+ichar('a')) + nlong = 180 - 20*(ichar(g1)-ichar('A')) + n20d = 2*(ichar(g3)-ichar('0')) + xminlong = 5*(ichar(g5)-ichar('a')+0.5) + dlong = nlong - n20d - xminlong/60.0 + nlat = -90+10*(ichar(g2)-ichar('A')) + ichar(g4)-ichar('0') + xminlat = 2.5*(ichar(g6)-ichar('a')+0.5) + dlat = nlat + xminlat/60.0 - g1=grid(1:1) - g2=grid(2:2) - g3=grid(3:3) - g4=grid(4:4) - g5=grid(5:5) - g6=grid(6:6) - - nlong = 180 - 20*(ichar(g1)-ichar('A')) - n20d = 2*(ichar(g3)-ichar('0')) - xminlong = 5*(ichar(g5)-ichar('a')+0.5) - dlong = nlong - n20d - xminlong/60.0 - nlat = -90+10*(ichar(g2)-ichar('A')) + ichar(g4)-ichar('0') - xminlat = 2.5*(ichar(g6)-ichar('a')+0.5) - dlat = nlat + xminlat/60.0 - - return -end subroutine grid2deg + end subroutine grid2deg +end module grid2deg_mod diff --git a/map65/libm65/grid2k.f90 b/map65/libm65/grid2k.f90 index f68b1409..593ec75b 100644 --- a/map65/libm65/grid2k.f90 +++ b/map65/libm65/grid2k.f90 @@ -1,12 +1,18 @@ -subroutine grid2k(grid,k) +module grid2k_mod + implicit none +contains + subroutine grid2k(grid,k) + use grid2deg_mod + character(len=6), intent(in) :: grid + integer, intent(out) :: k + real :: xlong, xlat + integer :: nlong, nlat - character*6 grid + call grid2deg(grid,xlong,xlat) + nlong=nint(xlong) + nlat=nint(xlat) + k=0 + if(nlat.ge.85) k=5*(nlong+179)/2 + nlat-84 - call grid2deg(grid,xlong,xlat) - nlong=nint(xlong) - nlat=nint(xlat) - k=0 - if(nlat.ge.85) k=5*(nlong+179)/2 + nlat-84 - - return -end subroutine grid2k + end subroutine grid2k +end module grid2k_mod diff --git a/map65/libm65/indexx.f90 b/map65/libm65/indexx.f90 index 7a35f53b..53eca25c 100644 --- a/map65/libm65/indexx.f90 +++ b/map65/libm65/indexx.f90 @@ -1,91 +1,121 @@ -subroutine indexx(arr,n,indx) - - parameter (M=7,NSTACK=50) - integer n,indx(n) - real arr(n) - integer i,indxt,ir,itemp,j,jstack,k,l,istack(NSTACK) - real a - - do j=1,n - indx(j)=j - enddo - - jstack=0 - l=1 - ir=n -1 if(ir-l.lt.M) then - do j=l+1,ir - indxt=indx(j) - a=arr(indxt) - do i=j-1,1,-1 - if(arr(indx(i)).le.a) goto 2 - indx(i+1)=indx(i) - enddo - i=0 -2 indx(i+1)=indxt - enddo - if(jstack.eq.0) return - - ir=istack(jstack) - l=istack(jstack-1) - jstack=jstack-2 - - else - k=(l+ir)/2 - itemp=indx(k) - indx(k)=indx(l+1) - indx(l+1)=itemp - - if(arr(indx(l+1)).gt.arr(indx(ir))) then - itemp=indx(l+1) - indx(l+1)=indx(ir) - indx(ir)=itemp - endif - - if(arr(indx(l)).gt.arr(indx(ir))) then - itemp=indx(l) - indx(l)=indx(ir) - indx(ir)=itemp - endif - - if(arr(indx(l+1)).gt.arr(indx(l))) then - itemp=indx(l+1) - indx(l+1)=indx(l) - indx(l)=itemp - endif - - i=l+1 - j=ir - indxt=indx(l) - a=arr(indxt) -3 continue - i=i+1 - if(arr(indx(i)).lt.a) goto 3 - -4 continue - j=j-1 - if(arr(indx(j)).gt.a) goto 4 - if(j.lt.i) goto 5 - itemp=indx(i) - indx(i)=indx(j) - indx(j)=itemp - goto 3 - -5 indx(l)=indx(j) - indx(j)=indxt - jstack=jstack+2 - if(jstack.gt.NSTACK) stop 'NSTACK too small in indexx' - if(ir-i+1.ge.j-l)then - istack(jstack)=ir - istack(jstack-1)=i - ir=j-1 +module indexx_mod + implicit none +contains + subroutine indexx(arr, n, indx) + implicit none + integer, intent(in) :: n + real, intent(in) :: arr(n) + integer, intent(out) :: indx(n) + + integer, parameter :: M = 7, NSTACK = 50 + integer :: i, j, k, l, ir, jstack + integer :: istack(NSTACK) + integer :: indxt, itemp + real :: a + + ! Initialize index array + do j = 1, n + indx(j) = j + end do + + jstack = 0 + l = 1 + ir = n + + do ! main loop replacing label 1 + + ! Use insertion sort for small subarrays + if (ir - l < M) then + do j = l+1, ir + indxt = indx(j) + a = arr(indxt) + + do i = j-1, l, -1 + if (arr(indx(i)) <= a) exit + indx(i+1) = indx(i) + end do + + indx(i+1) = indxt + end do + + if (jstack == 0) return + + ir = istack(jstack) + l = istack(jstack-1) + jstack = jstack - 2 + else - istack(jstack)=j-1 - istack(jstack-1)=l - l=i - endif - endif - goto 1 - -end subroutine indexx + ! Quicksort partitioning + k = (l + ir) / 2 + itemp = indx(k); indx(k) = indx(l+1); indx(l+1) = itemp + + if (arr(indx(l+1)) > arr(indx(ir))) then + itemp = indx(l+1); indx(l+1) = indx(ir); indx(ir) = itemp + end if + + if (arr(indx(l)) > arr(indx(ir))) then + itemp = indx(l); indx(l) = indx(ir); indx(ir) = itemp + end if + + if (arr(indx(l+1)) > arr(indx(l))) then + itemp = indx(l+1); indx(l+1) = indx(l); indx(l) = itemp + end if + + i = l + 1 + j = ir + indxt = indx(l) + a = arr(indxt) + + ! Partition loop replacing labels 3 and 4 + do + ! Move i right + do + i = i + 1 + if (i > ir) exit ! exit inner loop + if (arr(indx(i)) >= a) exit + end do + + ! Move j left + do + j = j - 1 + if (j < l) then + exit ! exit inner loop + end if + if (arr(indx(j)) <= a) exit + end do + + ! If j < i, partition is done + if (j < i) exit + + ! Swap + itemp = indx(i) + indx(i) = indx(j) + indx(j) = itemp + end do + + ! But now j might be < l, so clamp it: + if (j < l) j = l + + indx(l) = indx(j) + indx(j) = indxt + + ! Push larger segment, process smaller first + jstack = jstack + 2 + if (jstack > NSTACK) stop 'NSTACK too small in indexx' + + if (ir - i + 1 >= j - l) then + istack(jstack) = ir + istack(jstack-1) = i + ir = j - 1 + else + istack(jstack) = j - 1 + istack(jstack-1) = l + l = i + end if + end if + + end do + + end subroutine indexx +end module indexx_mod diff --git a/map65/libm65/init_rs.c b/map65/libm65/init_rs.c index 876819f8..6dff0392 100644 --- a/map65/libm65/init_rs.c +++ b/map65/libm65/init_rs.c @@ -35,7 +35,7 @@ void *INIT_RS(unsigned int symsize,unsigned int gfpoly,unsigned fcr,unsigned pri int i, j, sr,root,iprim; /* Check parameter ranges */ - if(symsize < 0 || symsize > (int)(8*sizeof(DTYPE))) + if(symsize > (int)(8*sizeof(DTYPE))) return NULL; /* Need version with ints rather than chars */ if(fcr >= (1<<symsize)) diff --git a/map65/libm65/interleave63.f90 b/map65/libm65/interleave63.f90 index a32ef34c..8101a0c4 100644 --- a/map65/libm65/interleave63.f90 +++ b/map65/libm65/interleave63.f90 @@ -1,25 +1,29 @@ -subroutine interleave63(d1,idir) +module interleave63_mod + implicit none +contains + subroutine interleave63(d1,idir) + use set_mod + implicit none + integer, intent(inout) :: d1(0:6,0:8) + integer, intent(in) :: idir + integer :: d2(0:8,0:6) + integer :: i, j -! Interleave (idir=1) or de-interleave (idir=-1) the array d1. - - integer d1(0:6,0:8) - integer d2(0:8,0:6) - - if(idir.ge.0) then - do i=0,6 - do j=0,8 - d2(j,i)=d1(i,j) - enddo - enddo - call move(d2,d1,63) - else - call move(d1,d2,63) - do i=0,6 - do j=0,8 - d1(i,j)=d2(j,i) - enddo - enddo - endif - - return -end subroutine interleave63 + if(idir.ge.0) then + do i=0,6 + do j=0,8 + d2(j,i)=d1(i,j) + enddo + enddo + call move(d2,d1,63) + else + call move(d1,d2,63) + do i=0,6 + do j=0,8 + d1(i,j)=d2(j,i) + enddo + enddo + endif + + end subroutine interleave63 +end module interleave63_mod diff --git a/map65/libm65/iqcal.f90 b/map65/libm65/iqcal.f90 index c0c4fce2..521e04a8 100644 --- a/map65/libm65/iqcal.f90 +++ b/map65/libm65/iqcal.f90 @@ -1,30 +1,49 @@ -subroutine iqcal(nn,c,nfft,gain,phase,zsum,ipk,reject) - - complex c(0:nfft-1) - complex z,zsum,zave - - if(nn.eq.0) then - zsum=0. - endif - nn=nn+1 - smax=0. - ipk=1 - do i=1,nfft-1 !Find strongest signal - s=real(c(i))**2 + aimag(c(i))**2 - if(s.gt.smax) then - smax=s - ipk=i - endif - enddo - pimage=real(c(nfft-ipk))**2 + aimag(c(nfft-ipk))**2 - p=smax + pimage - z=c(ipk)*c(nfft-ipk)/p !Synchronous detection of image - zsum=zsum+z - zave=zsum/nn - tmp=sqrt(1.0 - (2.0*real(zave))**2) - phase=asin(2.0*aimag(zave)/tmp) !Estimate phase - gain=tmp/(1.0-2.0*real(zave)) !Estimate gain - reject=10.0*log10(pimage/smax) - - return -end subroutine iqcal +module iqcal_mod + implicit none +contains + subroutine iqcal(nn,c,nfft,gain,phase,zsum,ipk,reject) & + bind(C, name="iqcal_") + implicit none + integer, intent(in) :: nn + integer, intent(in) :: nfft + complex, intent(in) :: c(0:nfft-1) + real, intent(out) :: gain, phase, reject + complex, intent(inout) :: zsum + integer, intent(out) :: ipk + + complex :: z,zave + real :: s,smax,pimage,p,tmp + integer :: i, n_avg + + if(nn.eq.0) then + zsum=0. + endif + n_avg = nn + 1 + + smax=0. + ipk=1 + do i=1,nfft-1 + s=real(c(i))**2 + aimag(c(i))**2 + if(s.gt.smax) then + smax=s + ipk=i + endif + enddo + pimage=real(c(nfft-ipk))**2 + aimag(c(nfft-ipk))**2 + p=smax + pimage + z=c(ipk)*c(nfft-ipk)/p + zsum=zsum+z + + zave=zsum/real(n_avg) + + tmp=sqrt(1.0 - (2.0*real(zave))**2) + phase=asin(2.0*aimag(zave)/tmp) + gain=tmp/(1.0-2.0*real(zave)) + if(smax > 0.0) then + reject=10.0*log10(pimage/smax) + else + reject=0.0 + endif + + end subroutine iqcal +end module iqcal_mod diff --git a/map65/libm65/iqfix.f90 b/map65/libm65/iqfix.f90 index 93cace4b..fef60b2d 100644 --- a/map65/libm65/iqfix.f90 +++ b/map65/libm65/iqfix.f90 @@ -1,28 +1,37 @@ -subroutine iqfix(c,nfft,gain,phase) - - complex c(0:nfft-1) - complex z,h,u,v - - nh=nfft/2 - h=gain*cmplx(cos(phase),sin(phase)) - - do i=1,nh-1 - u=c(i) - v=c(nfft-i) - x=real(u) + real(v) - (aimag(u) + aimag(v))*aimag(h) + & - (real(u) - real(v))*real(h) - y=aimag(u) - aimag(v) + (aimag(u) + aimag(v))*real(h) + & - (real(u) - real(v))*aimag(h) - c(i)=0.5*cmplx(x,y) - z=u - u=v - v=z - x=real(u) + real(v) - (aimag(u) + aimag(v))*aimag(h) + & - (real(u) - real(v))*real(h) - y=aimag(u) - aimag(v) + (aimag(u) + aimag(v))*real(h) + & - (real(u) - real(v))*aimag(h) - c(nfft-i)=0.5*cmplx(x,y) - enddo - - return -end subroutine iqfix +module iqfix_mod + implicit none +contains + subroutine iqfix(c,nfft,gain,phase) & + bind(C, name="iqfix_") + implicit none + integer, intent(in) :: nfft + complex, intent(inout) :: c(0:nfft-1) + real, intent(in) :: gain, phase + + complex :: z,h,u,v + integer :: i, nh + real :: x,y + + nh=nfft/2 + h=gain*cmplx(cos(phase),sin(phase)) + + do i=1,nh-1 + u=c(i) + v=c(nfft-i) + x=real(u) + real(v) - (aimag(u) + aimag(v))*aimag(h) + & + (real(u) - real(v))*real(h) + y=aimag(u) - aimag(v) + (aimag(u) + aimag(v))*real(h) + & + (real(u) - real(v))*aimag(h) + c(i)=0.5*cmplx(x,y) + z=u + u=v + v=z + x=real(u) + real(v) - (aimag(u) + aimag(v))*aimag(h) + & + (real(u) - real(v))*real(h) + y=aimag(u) - aimag(v) + (aimag(u) + aimag(v))*real(h) + & + (real(u) - real(v))*aimag(h) + c(nfft-i)=0.5*cmplx(x,y) + enddo + + end subroutine iqfix +end module iqfix_mod diff --git a/map65/libm65/jt65code.f90 b/map65/libm65/jt65code.f90 index b232fcdd..cd75d2b1 100644 --- a/map65/libm65/jt65code.f90 +++ b/map65/libm65/jt65code.f90 @@ -1,15 +1,25 @@ program JT65code + use chkmsg_mod + use packjt + use interleave63_mod + use graycode_mod + implicit none + external rs_encode_ + external rs_decode_ + ! Provides examples of message packing, bit and symbol ordering, ! Reed Solomon encoding, and other necessary details of the JT65 ! protocol. character*22 msg0,msg,decoded,cok*3 integer dgen(12),sent(63),recd(12),era(51) + integer :: nargs, nspecial, nerr + real(real32) :: flip nargs=iargc() if(nargs.ne.1) then - print*,'Usage: JT65code "message"' + ! print*,'Usage: JT65code "message"' go to 999 endif @@ -31,7 +41,7 @@ program JT65code write(*,1040) dgen 1040 format('Packed message, 6-bit symbols: ',12i3) !Display packed symbols - call rs_encode(dgen,sent) !RS encode + call rs_encode_(dgen,sent) !RS encode call interleave63(sent,1) !Interleave channel symbols call graycode(sent,63,1) !Apply Gray code write(*,1050) sent @@ -39,9 +49,11 @@ program JT65code call graycode(sent,63,-1) call interleave63(sent,-1) - call rs_decode(sent,era,0,recd,nerr) + call rs_decode_(sent,era,0,recd,nerr) call unpackmsg(recd,decoded) !Unpack the user message write(*,1060) decoded,cok 1060 format('Decoded message: ',a22,2x,a3) 999 end program JT65code + +!does not require end module
\ No newline at end of file diff --git a/map65/libm65/k2grid.f90 b/map65/libm65/k2grid.f90 index aa763157..03bdf5e2 100644 --- a/map65/libm65/k2grid.f90 +++ b/map65/libm65/k2grid.f90 @@ -1,12 +1,20 @@ -subroutine k2grid(k,grid) - character grid*6 - - nlong=2*mod((k-1)/5,90)-179 - if(k.gt.450) nlong=nlong+180 - nlat=mod(k-1,5)+ 85 - dlat=nlat - dlong=nlong - call deg2grid(dlong,dlat,grid) - - return -end subroutine k2grid +module k2grid_mod + implicit none +contains + subroutine k2grid(k,grid) + use deg2grid_mod, only: deg2grid + character(len=6), intent(out) :: grid + integer, intent(in) :: k + + integer :: nlong, nlat + real :: dlong, dlat + + nlong=2*mod((k-1)/5,90)-179 + if(k.gt.450) nlong=nlong+180 + nlat=mod(k-1,5)+ 85 + dlat=nlat + dlong=nlong + call deg2grid(dlong,dlat,grid) + + end subroutine k2grid +end module k2grid_mod diff --git a/map65/libm65/lorentzian.f90 b/map65/libm65/lorentzian.f90 index cd2257a7..75d5b070 100644 --- a/map65/libm65/lorentzian.f90 +++ b/map65/libm65/lorentzian.f90 @@ -1,102 +1,108 @@ -subroutine lorentzian(y,npts,a) +module lorentzian_mod + implicit none +contains + subroutine lorentzian(y,npts,a) + use fchisq0_mod + implicit none -! Input: y(npts); assume x(i)=i, i=1,npts -! Output: a(5) -! a(1) = baseline -! a(2) = amplitude -! a(3) = x0 -! a(4) = width -! a(5) = chisqr + ! Input: y(npts); assume x(i)=i, i=1,npts + ! Output: a(5) + ! a(1) = baseline + ! a(2) = amplitude + ! a(3) = x0 + ! a(4) = width + ! a(5) = chisqr - real y(npts) - real a(5) - real deltaa(4) + integer, intent(in) :: npts + real, intent(in) :: y(npts) + real, intent(out) :: a(5) - a=0. - df=12000.0/8192.0 !df = 1.465 Hz - width=0. - ipk=0 - ymax=-1.e30 - do i=1,npts - if(y(i).gt.ymax) then - ymax=y(i) - ipk=i - endif -! write(50,3001) i,i*df,y(i) -!3001 format(i6,2f12.3) - enddo -! base=(sum(y(ipk-149:ipk-50)) + sum(y(ipk+51:ipk+150)))/200.0 - base=(sum(y(1:20)) + sum(y(npts-19:npts)))/40.0 - stest=ymax - 0.5*(ymax-base) - ssum=y(ipk) - do i=1,50 - if(ipk+i.gt.npts) exit - if(y(ipk+i).lt.stest) exit - ssum=ssum + y(ipk+i) - enddo - do i=1,50 - if(ipk-i.lt.1) exit - if(y(ipk-i).lt.stest) exit - ssum=ssum + y(ipk-i) - enddo - ww=ssum/y(ipk) - width=2 - t=ww*ww - 5.67 - if(t.gt.0.0) width=sqrt(t) - a(1)=base - a(2)=ymax-base - a(3)=ipk - a(4)=width + real :: deltaa(4) + real :: df, width, ymax, base, stest, ssum, ww, t, fn + real :: chisqr, chisqr0, chisq1, chisq2, chisq3, delta, tmp + integer :: i, ipk, nterms, iter, j -! Now find Lorentzian parameters + a=0. + df=12000.0/8192.0 !df = 1.465 Hz + width=0. + ipk=0 + ymax=-1.e30 + do i=1,npts + if(y(i).gt.ymax) then + ymax=y(i) + ipk=i + endif + enddo - deltaa(1)=0.1 - deltaa(2)=0.1 - deltaa(3)=1.0 - deltaa(4)=1.0 - nterms=4 + base=(sum(y(1:20)) + sum(y(npts-19:npts)))/40.0 + stest=ymax - 0.5*(ymax-base) + ssum=y(ipk) + do i=1,50 + if(ipk+i.gt.npts) exit + if(y(ipk+i).lt.stest) exit + ssum=ssum + y(ipk+i) + enddo + do i=1,50 + if(ipk-i.lt.1) exit + if(y(ipk-i).lt.stest) exit + ssum=ssum + y(ipk-i) + enddo + ww=ssum/y(ipk) + width=2 + t=ww*ww - 5.67 + if(t.gt.0.0) width=sqrt(t) + a(1)=base + a(2)=ymax-base + a(3)=ipk + a(4)=width -! Start the iteration - chisqr=0. - chisqr0=1.e6 - do iter=1,5 - do j=1,nterms - chisq1=fchisq0(y,npts,a) - fn=0. - delta=deltaa(j) -10 a(j)=a(j)+delta - chisq2=fchisq0(y,npts,a) - if(chisq2.eq.chisq1) go to 10 - if(chisq2.gt.chisq1) then - delta=-delta !Reverse direction - a(j)=a(j)+delta - tmp=chisq1 - chisq1=chisq2 - chisq2=tmp - endif -20 fn=fn+1.0 - a(j)=a(j)+delta - chisq3=fchisq0(y,npts,a) - if(chisq3.lt.chisq2) then - chisq1=chisq2 - chisq2=chisq3 - go to 20 - endif + ! Now find Lorentzian parameters -! Find minimum of parabola defined by last three points - delta=delta*(1./(1.+(chisq1-chisq2)/(chisq3-chisq2))+0.5) - a(j)=a(j)-delta - deltaa(j)=deltaa(j)*fn/3. -! write(*,4000) iter,j,a,chisq2 -!4000 format(i1,i2,4f10.4,f11.3) - enddo - chisqr=fchisq0(y,npts,a) -! write(*,4000) 0,0,a,chisqr - if(chisqr/chisqr0.gt.0.99) exit - chisqr0=chisqr - enddo - a(5)=chisqr + deltaa(1)=0.1 + deltaa(2)=0.1 + deltaa(3)=1.0 + deltaa(4)=1.0 + nterms=4 - return -end subroutine lorentzian + ! Start the iteration + chisqr=0. + chisqr0=1.e6 + do iter=1,5 + do j=1,nterms + chisq1=fchisq0(y,npts,a) + fn=0. + delta=deltaa(j) + 10 a(j)=a(j)+delta + chisq2=fchisq0(y,npts,a) + if(chisq2.eq.chisq1) go to 10 + if(chisq2.gt.chisq1) then + delta=-delta !Reverse direction + a(j)=a(j)+delta + tmp=chisq1 + chisq1=chisq2 + chisq2=tmp + endif + 20 fn=fn+1.0 + a(j)=a(j)+delta + chisq3=fchisq0(y,npts,a) + if(chisq3.lt.chisq2) then + chisq1=chisq2 + chisq2=chisq3 + go to 20 + endif + + ! Find minimum of parabola defined by last three points + delta=delta*(1./(1.+(chisq1-chisq2)/(chisq3-chisq2))+0.5) + a(j)=a(j)-delta + deltaa(j)=deltaa(j)*fn/3. + enddo + chisqr=fchisq0(y,npts,a) + if(chisqr/chisqr0.gt.0.99) exit + chisqr0=chisqr + enddo + a(5)=chisqr + + return + end subroutine lorentzian +end module lorentzian_mod diff --git a/map65/libm65/m65.f90 b/map65/libm65/m65.f90 deleted file mode 100644 index c93357c7..00000000 --- a/map65/libm65/m65.f90 +++ /dev/null @@ -1,195 +0,0 @@ -program m65 - -! Decoder for map65. Can run stand-alone, reading data from *.tf2 files; -! or as the back end of map65, with data placed in a shared memory region. - -! Fortran logical units -! -! 10 binary input data, *.tf2 files -! 11 prefixes.txt -! 12 wb_w65.txt -! 13 map65.log -! 14 -! 15 -! 16 tquick log -! 17 saved *.tf2 files -! 18 test file to be transmitted (wsjtgen.f90) -! 19 livecq.txt -! 20 -! 21 map65_rx.log -! 22 -! 23 CALL3.TXT -! 24 -! 25 -! 26 tmp26.txt - - use timer_module, only: timer - use timer_impl, only: init_timer, fini_timer - - include 'njunk.f90' - parameter (NFFT=32768) - parameter (NSMAX=60*96000) - parameter (NREAD=2048) - integer*2 i2(NREAD) - real*8 hsym - real*4 ssz5a(NFFT) - logical*1 lstrong(0:1023),ldecoded,eof - real*8 fc0,fcenter - character*80 arg,infile - character mycall*12,hiscall*12,mygrid*6,hisgrid*6,datetime*20 - common/datcom/dd(4,5760000),ss(4,322,NFFT),savg(4,NFFT),fc0,nutc0,junk(NJUNK) - common/npar/fcenter,nutc,idphi,mousedf,mousefqso,nagain, & - ndepth,ndiskdat,neme,newdat,nfa,nfb,nfcal,nfshift, & - mcall3,nkeep,ntol,nxant,nrxlog,nfsample,nxpol,nmode, & - ndop00,nsave,max_drift,nhsym,mycall,mygrid,hiscall,hisgrid,datetime - common/early/nhsym1,nhsym2,ldecoded(32768) - - nargs=iargc() - if(nargs.ne.1 .and. nargs.lt.5) then - print*,'Usage: m65 Jsub Qsub Xpol <95238|96000> file1 [file2 ...]' - print*,'Examples: m65 B A X 96000 *.tf2' - print*,' m65 C C N 96000 *.iq' - print*,'' - print*,' m65 -s' - print*,' (Gets data from MAP65, via shared memory region.)' - go to 999 - endif - nstandalone=1 - nhsym1=280 - nhsym2=302 - call getarg(1,arg) - if(arg(1:2).eq.'-s') then - call m65a - go to 999 - endif - n=1 - if(arg(1:1).eq.'0') n=0 - if(arg(1:1).eq.'A') n=1 - if(arg(1:1).eq.'B') n=2 - if(arg(1:1).eq.'C') n=3 - - call getarg(2,arg) - m=1 - if(arg(1:1).eq.'0') m=0 - if(arg(1:1).eq.'A') m=1 - if(arg(1:1).eq.'B') m=2 - if(arg(1:1).eq.'C') m=3 - if(arg(1:1).eq.'D') m=4 - if(arg(1:1).eq.'E') m=5 - nmode=10*m + n - - call getarg(3,arg) - nxpol=0 - if(arg(1:1).eq.'X') nxpol=1 - - call getarg(4,arg) - nfsample=96000 - if(arg.eq.'95238') nfsample=95238 - - ifile1=5 - -! Some default parameters for command-line execution, in early testing. - mycall='K1JT' - mygrid='FN20QI' - hiscall='K9AN' - hisgrid='EN50' - nfa=100 !144.100 - nfb=162 !144.162 - ntol=100 - nkeep=10 !??? - mousefqso=140 !For IK4WLV in 210220_1814.tf2 - mousedf=0 - nfcal=0 - nkhz_center=125 - - if(nxpol.eq.0) then - nfa=55 !For KA1GT files - nfb=143 - mousefqso=69 !W2HRO signal - nkhz_center=100 - endif - - call ftninit('.') - call init_timer('timer.out') - call timer('m65 ',0) - - do ifile=ifile1,nargs - call getarg(ifile,infile) - open(10,file=infile,access='stream',status='old',err=998) - i1=index(infile,'.tf2') - if(i1.lt.1) i1=index(infile,'.iq') - read(infile(i1-4:i1-1),*,err=1) nutc0 - go to 2 -1 nutc0=0 -2 hsym=2048.d0*96000.d0/11025.d0 !Samples per half symbol - read(10) fcenter - newdat=1 - nhsym0=-999 - k=0 - - nch=2 - if(nxpol.eq.1) nch=4 - eof=.false. - do irec=1,9999999 - if(.not.eof) read(10,end=4) i2 - go to 6 -4 eof=.true. -6 if(eof) i2=0 - do i=1,NREAD,nch - k=k+1 - if(k.gt.60*96000) exit - dd(1,k)=i2(i) - dd(2,k)=i2(i+1) - if(nxpol.eq.1) then - dd(3,k)=i2(i+2) - dd(4,k)=i2(i+3) - endif - enddo - nhsym=(k-2048)/hsym - if(nhsym.ge.1 .and. nhsym.ne.nhsym0) then - ndiskdat=1 - nb=0 -! Emit signal readyForFFT - fgreen=-13.0 - iqadjust=0 - iqapply=0 - nbslider=100 - gainx=0.9962 - gainy=1.0265 - phasex=0.01426 - phasey=-0.01195 - call timer('symspec ',0) - call symspec(k,nxpol,ndiskdat,nb,nbslider,idphi,nfsample, & - fgreen,iqadjust,iqapply,gainx,gainy,phasex,phasey,rejectx, & - rejecty,pxdb,pydb,ssz5a,nkhz,ihsym,nzap,slimit,lstrong) - call timer('symspec ',1) - nhsym0=nhsym - - nutc=nutc0 - if(nhsym.eq.nhsym1) call decode0(dd,ss,savg,nstandalone) - if(nhsym.eq.nhsym2) then - call decode0(dd,ss,savg,nstandalone) - exit - endif - endif - enddo ! irec - - if(iqadjust.ne.0) write(*,3002) rejectx,rejecty -3002 format('Image rejection:',2f7.1,' dB') - enddo ! ifile - - call timer('m65 ',1) - call timer('m65 ',101) - go to 999 - -998 print*,'Cannot open file:' - print*,infile - -999 call fini_timer() - if(arg(1:2).eq.'-s') then - write(21,1999) datetime(:17) -1999 format('Subprocess m65 terminated normally at UTC ',a17) - close(21) - endif - -end program m65 diff --git a/map65/libm65/m65_mod.f90 b/map65/libm65/m65_mod.f90 new file mode 100644 index 00000000..7710293f --- /dev/null +++ b/map65/libm65/m65_mod.f90 @@ -0,0 +1,69 @@ +module m65_mod + +use iso_c_binding, only: c_int8_t,c_int,c_loc,c_ptr,c_int64_t +use decodes_mod, only: nhsym1,nhsym2,ldecoded + +implicit none + +contains + +subroutine m65c() bind(C) + use decode0_mod + use npar_ptrs_mod, only: nhsym, nrxlog, datetime, active_input_generation, nagain, ndiskdat, manualDecodeFlag + use debug_log, only: dbg, itoa, rtoa + use sec_midn_mod, only: sec_midn + integer :: npatience, nstandalone + integer, save :: nhsym_prev_m65c = -1 + integer(c_int64_t), save :: previous_input_generation = -1 + + npatience=1 + call dbg('m65c: ENTRY at t=' // rtoa(sec_midn()) // ' nhsym=' // itoa(nhsym) // & + ' nrxlog=' // itoa(nrxlog) // ' bit4_set=' // itoa(merge(1,0,iand(nrxlog,4).ne.0))) + if(nhsym.eq.nhsym1 .and. iand(nrxlog,1).ne.0) then + write(21,1000) datetime(1:17) +1000 format(/'UTC Date: ', a17, /78('-')) + flush(21) + endif + ! Consume the erase request once, independent of the decode pass. + if(iand(nrxlog,2).ne.0) then + rewind(21) + endfile(21) + backspace(21) + nrxlog = ibclr(nrxlog,1) + endif + if(iand(nrxlog,4).ne.0) then + ! rewind alone only repositions to record 1 for writing; it does not + ! shrink the file, so old history beyond whatever gets written this + ! cycle would stay on disk and could resurface via display.f90's own + ! rewind+read the same way the missing endfile there did (see + ! set_map65RxLog in npar_ptrs_mod.f90 for how Erase reaches here). + ! endfile makes this an immediate, real truncation to empty -- but it + ! leaves the file positioned after the EOF marker it just wrote, and + ! Fortran forbids further sequential I/O from there without + ! repositioning first, so backspace right away to land back on that + ! marker, ready for the next append. + ! + ! An expired final request must not hide the next accumulation cycle. + if(nhsym.eq.nhsym1 .and. (nhsym_prev_m65c.ne.nhsym1 .or. & + previous_input_generation.ne.active_input_generation)) then + call dbg('m65c: UNIT26 TRUNCATED (endfile) at t=' // rtoa(sec_midn()) // & + ' nhsym=' // itoa(nhsym) // ' nrxlog=' // itoa(nrxlog)) + rewind(26) + endfile(26) + backspace(26) + else if (nhsym.eq.nhsym1) then + call dbg('m65c: UNIT26 truncation SKIPPED (repeat call at nhsym1) at t=' // & + rtoa(sec_midn()) // ' nrxlog=' // itoa(nrxlog)) + endif + if(nhsym.eq.nhsym2) backspace(26) + endif + nhsym_prev_m65c = nhsym + if(nagain.eq.0 .and. ndiskdat.eq.0 .and. manualDecodeFlag.eq.0) & + previous_input_generation = active_input_generation + + nstandalone=0 + + call decode0(nstandalone) + +end subroutine m65c +end module m65_mod diff --git a/map65/libm65/m65a.f90 b/map65/libm65/m65a.f90 index ffeb176a..ab2af114 100644 --- a/map65/libm65/m65a.f90 +++ b/map65/libm65/m65a.f90 @@ -1,107 +1,52 @@ -subroutine m65a +module m65a_mod + implicit none +contains + +subroutine m65a() use timer_module, only: timer - use timer_impl, only: init_timer !, limtrace use, intrinsic :: iso_c_binding, only: C_NULL_CHAR + use npar_ptrs_mod, only: wsjtx_dir + use datcom_ptrs_mod, only: dd,ss,savg + use m65_mod use FFTW3 + use ftninit_mod - interface - function address_m65() - integer*1, pointer :: address_m65 - end function address_m65 - end interface + implicit none - integer*1 attach_m65 - integer size_m65 - integer*1, pointer :: p_m65 - character*80 cwd - character wisfile*256 - logical fileExists - - call getcwd(cwd) - call ftninit(trim(cwd)) - call init_timer (trim(cwd)//'/timer.out') + character(len=256) cwd + + cwd = trim(wsjtx_dir) - limtrace=0 - lu=12 - i1=attach_m65() + if (len_trim(cwd) == 0) then + call get_environment_variable("PWD", cwd) + end if -10 inquire(file=trim(cwd)//'/.lock',exist=fileExists) - if(fileExists) then - call sleep_msec(100) - go to 10 - endif + if (len_trim(cwd) == 0) then + call get_environment_variable("CD", cwd) + end if - inquire(file=trim(cwd)//'/.quit',exist=fileExists) - if(fileExists) then - call timer('decode0 ',101) - i=detach_m65() - ! Save FFTW wisdom and free memory - wisfile=trim(cwd)//'/m65_wisdom.dat'// C_NULL_CHAR - if(len(trim(wisfile)).gt.0) iret=fftwf_export_wisdom_to_filename(wisfile) - call four2a(a,-1,1,1,1) - call filbig(a,-1,1,0.0,0,0,0,0,0) !used for FFT plans - call fftwf_cleanup_threads() - call fftwf_cleanup() - go to 999 - endif + if (len_trim(cwd) == 0) then + cwd = "." + end if - nbytes=size_m65() - if(nbytes.le.0) then - print*,'m65a: Shared memory mem_m65 does not exist.' - print*,'Program m65a should be started automatically from within map65.' - go to 999 - endif - p_m65=>address_m65() - call m65b(p_m65,nbytes) - call sleep_msec(500) ! wait for .lock to be recreated - go to 10 - -999 return -end subroutine m65a - -subroutine m65b(m65com,nbytes) - integer*1 m65com(0:nbytes-1) - kss=4*4*60*96000 - ksavg=kss+4*4*322*32768 - kfcenter=ksavg+4*4*32768 - call m65c(m65com(0),m65com(kss),m65com(ksavg),m65com(kfcenter)) - return -end subroutine m65b - -subroutine m65c(dd,ss,savg,nparams0) - - include 'njunk.f90' - real*4 dd(4,5760000),ss(4,322,32768),savg(4,32768) - real*8 fcenter - integer nparams0(NJUNK+2),nparams(NJUNK+2) - logical ldecoded - character*12 mycall,hiscall - character*6 mygrid,hisgrid - character*20 datetime - common/npar/fcenter,nutc,idphi,mousedf,mousefqso,nagain, & - ndepth,ndiskdat,neme,newdat,nfa,nfb,nfcal,nfshift, & - mcall3,nkeep,ntol,nxant,nrxlog,nfsample,nxpol,nmode, & - ndop00,nsave,max_drift,nhsym,mycall,mygrid,hiscall,hisgrid, & - datetime,junk1,junk2 - common/early/nhsym1,nhsym2,ldecoded(32768) - equivalence (nparams,fcenter) + call ftninit(trim(cwd)) + + if (.not. associated(savg)) then + ! print *, 'ERROR:M65A savg is not associated!' + end if + + if (.not. associated(dd)) then + ! print *, 'ERROR: M65A dd is not associated!' + end if - nparams=nparams0 !Copy parameters into common/npar/ - npatience=1 - if(nhsym.eq.nhsym1 .and. iand(nrxlog,1).ne.0) then - write(21,1000) datetime(:17) -1000 format(/'UTC Date: 'a17/78('-')) - flush(21) - endif - if(iand(nrxlog,2).ne.0) rewind(21) - if(iand(nrxlog,4).ne.0) then - if(nhsym.eq.nhsym1) rewind(26) - if(nhsym.eq.nhsym2) backspace(26) - endif + if (.not. associated(ss)) then + ! print *, 'ERROR: M65A ss is not associated!' + end if + + call m65c() + return - nstandalone=0 - if(sum(nparams).ne.0) call decode0(dd,ss,savg,nstandalone) +end subroutine m65a - return -end subroutine m65c +end module m65a_mod diff --git a/map65/libm65/map65_polarization_score.f90 b/map65/libm65/map65_polarization_score.f90 new file mode 100644 index 00000000..24fa9a6f --- /dev/null +++ b/map65/libm65/map65_polarization_score.f90 @@ -0,0 +1,74 @@ +module map65_polarization_score_mod + use iso_fortran_env, only: real64 + implicit none + private + + real(real64), parameter :: pi=acos(-1.0_real64) + real(real64), parameter :: correlation_margin=1.0e-6_real64 + + public :: generalized_polarization_score + public :: polarization_matrix + +contains + + pure subroutine polarization_matrix(projections,g00,g11,g01) + real(real64), intent(in) :: projections(4) + real(real64), intent(out) :: g00,g11,g01 + + g00=projections(1) + g11=projections(3) + g01=0.5_real64*(projections(2)-projections(4)) + end subroutine polarization_matrix + + pure subroutine generalized_polarization_score(g00,g11,g01,n00,n11,n01,score, & + physical_angle_degrees,combine_angle_degrees,valid) + real(real64), intent(in) :: g00,g11,g01,n00,n11,n01 + real(real64), intent(out) :: score,physical_angle_degrees,combine_angle_degrees + logical, intent(out) :: valid + real(real64) :: alpha,ell,h00,h01,h11,m00,m01,m11,rho,sx,sy + real(real64) :: ux,uy,vx,vy,w0,w1 + + score=0.0_real64 + physical_angle_degrees=0.0_real64 + combine_angle_degrees=0.0_real64 + valid=.false. + if (n00 <= tiny(1.0_real64) .or. n11 <= tiny(1.0_real64)) return + + sx=sqrt(n00) + sy=sqrt(n11) + rho=n01/(sx*sy) + if (.not.(abs(rho) < huge(1.0_real64))) return + if (abs(rho) > 1.0_real64+correlation_margin) return + if (abs(rho) >= 1.0_real64-correlation_margin) then + rho=sign(1.0_real64-correlation_margin,rho) + endif + ell=sqrt(max(correlation_margin,1.0_real64-rho*rho)) + + m00=g00/n00 + m01=g01/(sx*sy) + m11=g11/n11 + h00=m00 + h01=(m01-rho*m00)/ell + h11=(m11-2.0_real64*rho*m01+rho*rho*m00)/(ell*ell) + score=max(0.0_real64,0.5_real64*(h00+h11)+ & + hypot(0.5_real64*(h00-h11),h01)) + + alpha=0.5_real64*atan2(2.0_real64*h01,h00-h11) + w0=cos(alpha) + w1=sin(alpha) + vx=(w0-rho*w1/ell)/sx + vy=(w1/ell)/sy + ux=sx*w0 + uy=sy*(rho*w0+ell*w1) + combine_angle_degrees=half_circle_angle(vx,vy) + physical_angle_degrees=half_circle_angle(ux,uy) + valid=.true. + end subroutine generalized_polarization_score + + pure real(real64) function half_circle_angle(x,y) + real(real64), intent(in) :: x,y + + half_circle_angle=modulo(atan2(y,x)*180.0_real64/pi,180.0_real64) + end function half_circle_angle + +end module map65_polarization_score_mod diff --git a/map65/libm65/map65a.f90 b/map65/libm65/map65a.f90 index f01bf557..cece6ec9 100644 --- a/map65/libm65/map65a.f90 +++ b/map65/libm65/map65a.f90 @@ -1,529 +1,1169 @@ -subroutine map65a(dd,ss,savg,newdat,nutc,fcenter,ntol,idphi,nfa,nfb, & - mousedf,mousefqso,nagain,ndecdone,nfshift,ndphi,max_drift, & - nfcal,nkeep,mcall3b,nsum,nsave,nxant,mycall,mygrid, & - neme,ndepth,nstandalone,hiscall,hisgrid,nhsym,nfsample, & - ndiskdat,nxpol,nmode,ndop00) - -! Processes timf2 data from Linrad to find and decode JT65 signals. - - use wideband_sync - use timer_module, only: timer - - parameter (MAXMSG=1000) !Size of decoded message list - parameter (NSMAX=60*96000) - real dd(4,NSMAX) - real*4 ss(4,322,NFFT),savg(4,NFFT) - real tavg(-50:50) !Temp for finding local base level - real base(4) !Local basel level at 4 pol'ns - real sig(MAXMSG,30) !Parameters of detected signals - real a(5) - real*8 fcenter - character*22 msg(MAXMSG) - character*3 shmsg0(4) - character mycall*12,hiscall*12,mygrid*6,hisgrid*6,cp*1,cm*1 - integer indx(MAXMSG),nsiz(MAXMSG) - logical done(MAXMSG) - logical xpol,bq65,q65b_called - logical candec(MAX_CANDIDATES) - logical ldecoded - character decoded*22,blank*22,cmode*2 - real short(3,NFFT) !SNR dt ipol for potential shorthands - real qphi(12) - type(candidate) :: cand(MAX_CANDIDATES) - - common/c3com/ mcall3a - common/testcom/ifreq - common/early/nhsym1,nhsym2,ldecoded(32768) - common/decodes/ndecodes - - data blank/' '/,cm/'#'/ - data shmsg0/'ATT','RO ','RRR','73 '/ - data nfile/0/,nutc0/-999/,nid/0/,ip000/1/,ip001/1/,mousefqso0/-999/ - save - - rewind 12 - ndecodes=0 - -! Clean start for Q65 at early decode - if(nhsym.eq.nhsym1 .or. nagain.ne.0) ldecoded=.false. - if(ndiskdat.eq.1) ldecoded=.false. - - nkhz_center=nint(1000.0*(fcenter-int(fcenter))) - mfa=nfa-nkhz_center+48 - mfb=nfb-nkhz_center+48 - mode65=mod(nmode,10) - if(mode65.eq.3) mode65=4 - mode_q65=nmode/10 - nts_jt65=mode65 !JT65 tone separation factor - nts_q65=2**(mode_q65-1) !Q65 tone separation factor - xpol=(nxpol.ne.0) - -! No second decode for JT65? - if(nhsym.eq.nhsym2 .and. nagain.eq.0 .and.ndiskdat.eq.0) mode65=0 - - if(nagain.eq.0) then - call timer('get_cand',0) - call get_candidates(ss,savg,xpol,nhsym,mfa,mfb,nts_jt65,nts_q65,cand,ncand) - call timer('get_cand',1) - candec=.false. - endif -!### -! do k=1,ncand -! freq=cand(k)%f+nkhz_center-48.0 -! ipk=cand(k)%indx -! write(71,3071) k,db(cand(k)%snr),freq,cand(k)%xdt, & -! cand(k)%ipol,cand(k)%iflip,ipk,ldecoded(ipk) -!3071 format(i3,f8.2,f10.3,f8.2,2i3,i6,L4) -! enddo -!### - - nwrite_q65=0 - bq65=mode_q65.gt.0 - - mcall3a=mcall3b - mousefqso0=mousefqso - if(.not.xpol) ndphi=0 - nsum=0 - -!### Should use AppDir! ### - open(23,file='CALL3.TXT',status='unknown') - - df=96000.0/NFFT !df = 96000/NFFT = 2.930 Hz - if(nfsample.eq.95238) df=95238.1/NFFT - ftol=0.010 !Frequency tolerance (kHz) - dphi=idphi/57.2957795 - foffset=0.001*(1270 + nfcal) !Offset from sync tone, plus CAL - fqso=mousefqso + foffset - 0.5*(nfa+nfb) + nfshift !fqso at baseband (khz) - iloop=0 - -2 if(ndphi.eq.1) dphi=30*iloop/57.2957795 - - if(nutc.ne.nutc0) nfile=nfile+1 - nutc0=nutc - - do nqd=1,0,-1 - if(nqd.eq.1) then !Quick decode, at fQSO - fa=1000.0*(fqso+0.001*mousedf) - ntol - fb=1000.0*(fqso+0.001*mousedf) + ntol + 4*53.8330078 - else !Wideband decode at all freqs - fa=-1000*0.5*(nfb-nfa) + 1000*nfshift - fb= 1000*0.5*(nfb-nfa) + 1000*nfshift - endif - ia=nint(fa/df) + 16385 - ib=nint(fb/df) + 16385 - ia=max(51,ia) - ib=min(32768-51,ib) - if(ndiskdat.eq.1 .and. mode65.eq.0) ib=ia - - km=0 - nkm=1 - nz=n/8 - freq0=-999. - sync10=-999. - fshort0=-999. - syncshort0=-999. - ntry=0 - short=0. !Zero the whole short array - jpz=1 - if(xpol) jpz=4 - -! First steps for JT65 decoding - do i=ia,ib !Search over freq range - freq=0.001*(i-16385)*df +module map65a_mod + use txpol_mod + use trimlist_mod + use iso_fortran_env, only: real64 + implicit none +contains + + subroutine map65a(dd, newdat, nutc, fcenter, ntol, idphi, nfa, nfb, & + mousedf, mousefqso, nagain, ndecdone, nfshift, ndphi, max_drift, & + nfcal, nkeep, mcall3b, nsum, nsave, nxant, mycall, mygrid, & + neme, ndepth, nstandalone, hiscall, hisgrid, nhsym, nfsample, & + ndiskdat, nxpol, nmode, ndop00) + + use iso_c_binding + use wideband_sync + use timer_module, only: timer + use debug_log, only: dbg, itoa, rtoa + use sec_midn_mod, only: sec_midn + use q65b_mod + use decode1a_mod + use ccf65_legacy_mod + use pctile_mod + use stdout_channel_mod, only: write_stdout + use decodes_mod, only: nhsym1, ldecoded, ljt65decoded, ndecodes, mcall3a, decodes_init + use display_mod + use timf2_mod + use getdphi_mod + use datcom_ptrs_mod, only: ss_old, savg_old + use npar_ptrs_mod, only: nsmax_active, nrate_active, nfft_active, t_start, abort_decode, & + manualDecodeFlag, active_input_generation + use sec0_mod, only: sec0 + use q65_decode, only: nsnr0, msg0, xdt0, nfreq0 + + implicit none + + integer, parameter :: MAXMSG = 1000 + real, parameter :: RESULT_DT_TOLERANCE = 0.2 + ! Neighborhood radius (in symspec FFT bins) for ljt65decoded's + ! cross-call "already decoded" check/mark, below. At df ~= 2.9 Hz/bin + ! this is ~+/-15 Hz, covering the couple-of-bin spread a single real + ! JT65 signal can show across separate automatic calls. + integer, parameter :: JT65_LOCAL_BINS = 5 + real, intent(in) :: dd(4, nsmax_active) + integer, intent(inout) :: newdat + integer, intent(inout) :: nutc + real(real64), intent(in) :: fcenter + integer, intent(in) :: ntol, idphi, nfa, nfb + integer, intent(in) :: mousedf, mousefqso, nagain + integer, intent(inout) :: ndecdone + integer, intent(in) :: nfshift + integer, intent(inout) :: ndphi + integer, intent(in) :: max_drift, nfcal, nkeep + integer, intent(inout) :: mcall3b + integer, intent(inout) :: nsum, nsave + integer, intent(in) :: nxant + character(len=12), intent(in) :: mycall, hiscall + character(len=6), intent(in) :: mygrid, hisgrid + integer, intent(in) :: neme, ndepth, nstandalone + integer, intent(in) :: nhsym, nfsample, ndiskdat, nxpol, nmode, ndop00 + + ! --- local variables (unchanged) --- + real tavg(-50:50), base(4), sig(MAXMSG,30), a(5) + real :: df, dphi, dt, dt2, fa, fb, flip, flipk, foffset, freq, freq0, fshort + real :: ftol, pol, qual, s2db, smax, snr2, ssmax, sync1, sync10, sync2, syncshort + real :: tdec, thresh0, thresh1, tsec0, fshort0, fqso, syncshort0 + real(real64) :: f0 + character(len=22) msg(MAXMSG) + character(len=3) shmsg0(4) + character(len=1) :: cp, cm + integer indx(MAXMSG) + integer :: ipol, mode65 + integer :: i, ia, ib, i0, icand, idf, ifreq, ii, iii, ikhz + integer :: iloop, ip000, ip001, ipol2, j, jp, jpmax, jpz + integer :: k, km, mfa, mfb, mhz, mode_q65 + integer :: mousefqso0, n, ncand, ndf, ndf0, ndf1, ndf2 + integer :: nfile, nflip, nhist, nhzdiff, nid, nkhz, nkm, nkv + integer :: noffset, npol, nqd, nqual, nsync1, nsync2, ntry + integer :: nts_jt65, nts_q65, ntxpol, nutc0, nwrite, nwrite_q65, nz + integer :: idec + logical xpol, bq65, q65b_called + logical candec(MAX_CANDIDATES) + character(len=22) decoded, blank, decoded_jt65 + character(len=2) cmode + real short(3, nfft_active) + real qphi(12) + type(candidate) :: cand(MAX_CANDIDATES) + real(real64) :: f00 + character(len=256) :: line + integer :: n_rms, i2 + real*8 :: rms, sumsq, v + real*4 :: tsec_mod + integer :: t_now, t_rate + logical :: m65_inited = .false. + logical :: abort_saved + integer :: icenter + logical :: initialization_only, shorthand_detected, jt65_success, q65_success + logical :: already_decoded_nearby + real :: best_sync1, best_dt, best_flipk, best_syncshort, best_snr2, best_dt2 + integer :: best_i, best_ipol2 + real :: sync1_tmp, dt_tmp, flipk_tmp, syncshort_tmp, snr2_tmp, dt2_tmp + integer :: ipol_tmp, ipol2_tmp,ftol_bins, manualDecodeFlag_initial + real :: freq_q65 + integer :: nhsym_prev_call + integer(c_int64_t) :: previous_input_generation = -1 + + data blank/' '/, cm/'#'/ + data shmsg0/'ATT','RO ','RRR','73 '/ + data nfile/0/, nutc0/-999/, nid/0/, ip000/1/, ip001/1/, mousefqso0/-999/ + data nhsym_prev_call/-1/ + save + + real(c_float), pointer :: ss_dec(:,:,:) + real(c_float), pointer :: savg_dec(:,:) + + manualDecodeFlag_initial = manualDecodeFlag + +!------------------------------------------------------------ +! BUFFER SELECTION +!------------------------------------------------------------ + ! Always use the snapshot (see decode0.f90) -- ss/savg are live and + ! can be reset/overwritten mid-decode by symspec_() on the GUI thread + ! once the next cycle's UDP data starts arriving. + ss_dec => ss_old + savg_dec => savg_old + + abort_decode = .false. + + if (.not. m65_inited) then + call decodes_init() + call init_wideband_sync() + m65_inited = .true. + endif + + rewind 12 + ndecodes = 0 + km = 0 + ipol = 1 + +!------------------------------------------------------------ +! BASIC DECODE SETUP (shared by manual + wideband) +!------------------------------------------------------------ + ! Share the ledger across early/final passes, but start a new cycle + ! even when the preceding final request expired before execution. + if ((nhsym .eq. nhsym1 .and. (nhsym_prev_call .ne. nhsym1 .or. & + previous_input_generation .ne. active_input_generation)) .or. nagain .ne. 0) then + ldecoded = .false. + ljt65decoded = .false. + call dbg('map65a: ldecoded/ljt65decoded RESET at t=' // rtoa(sec_midn()) // & + ' nhsym=' // itoa(nhsym) // ' nhsym_prev_call=' // itoa(nhsym_prev_call) // & + ' nagain=' // itoa(nagain)) + else if (nhsym .eq. nhsym1) then + call dbg('map65a: ldecoded/ljt65decoded NOT reset (repeat call at nhsym1) at t=' // rtoa(sec_midn()) // & + ' nhsym=' // itoa(nhsym)) + endif + nhsym_prev_call = nhsym + if (nagain .eq. 0 .and. ndiskdat .eq. 0 .and. manualDecodeFlag .eq. 0) & + previous_input_generation = active_input_generation + if (ndiskdat .eq. 1) then + ldecoded = .false. + ljt65decoded = .false. + endif + + df = real(nrate_active)/real(nfft_active) + if (nfsample .eq. 95238) df = 95238.1/real(nfft_active) + + mode65 = mod(nmode,10) + if (mode65 .eq. 3) mode65 = 4 + mode_q65 = nmode/10 + nts_jt65 = mode65 + nts_q65 = 2**(mode_q65 - 1) + xpol = (nxpol .ne. 0) + + nwrite_q65 = 0 + bq65 = mode_q65 .gt. 0 + + mcall3a = mcall3b + mousefqso0 = mousefqso + if (.not. xpol) ndphi = 0 + nsum = 0 + + dphi = idphi/57.2957795 + foffset = 0.001*(1270 + nfcal) + iloop = 0 + + ! qphi is "save"d across calls (blanket SAVE above) but only gets + ! written for a trial (iloop=1..12) that actually decodes something; + ! without this reset, a trial that finds nothing leaves behind + ! whatever unrelated value qphi(iloop) held from an earlier Find-dPhi + ! run, silently mixing stale data into getdphi's best-fit calculation. + if (ndphi .eq. 1) qphi = 0.0 + +2 if (ndphi .eq. 1) dphi = 30*iloop/57.2957795 + + if (nutc .ne. nutc0) nfile = nfile + 1 + nutc0 = nutc + + !### Should use AppDir! ### + open (23, file='CALL3.TXT', status='unknown') + +!------------------------------------------------------------ +! MANUAL NARROWBAND DECODE PATH +!------------------------------------------------------------ + if (manualDecodeFlag /= 0) then + abort_saved = abort_decode + km = 0 + icenter = nfft_active/2 + 1 + + ! JT65/Q65 RF frame (kHz) + foffset = 0.001*(1270 + nfcal) + fqso = mousefqso + foffset - 0.5*(nfa + nfb) + nfshift + + ! Manual clicked RF (kHz) + freq = fqso + 0.001*mousedf + + ! Bin index + i = nint(freq*1000.0/df) + icenter + + ! Tolerance from GUI + ftol = real(ntol) ! Hz + ftol_bins = nint(ftol / df) + + i = nint(freq*1000.0/df) + icenter ! bin corresponding to that RF + i = max(51, min(nfft_active - 51, i)) + + ! --- local search around clicked bin within ftol --- + ftol = real(ntol) + ftol_bins = nint(ftol / df) + + jpz = merge(4,1,xpol) + + best_sync1 = -1.e9 + best_i = i + best_dt = 0.0 + best_flipk = 0.0 + best_syncshort = 0.0 + best_snr2 = 0.0 + best_ipol2 = 1 + best_dt2 = 0.0 + + do ii = -ftol_bins, ftol_bins + iii = i + ii + if (iii < 51 .or. iii > nfft_active - 51) cycle + + ssmax = 1.e30 + call timer('ccf65 ',0) + call ccf65(ss_dec(:,:,iii), nhsym, ssmax, sync1_tmp, ipol_tmp, jpz, dt_tmp, flipk_tmp, & + syncshort_tmp, snr2_tmp, ipol2_tmp, dt2_tmp) + call timer('ccf65 ',1) + + if (sync1_tmp > best_sync1) then + best_sync1 = sync1_tmp + best_i = iii + best_dt = dt_tmp + best_flipk = flipk_tmp + best_syncshort = syncshort_tmp + best_snr2 = snr2_tmp + best_ipol2 = ipol2_tmp + best_dt2 = dt2_tmp + endif + enddo + + ! use best bin and metrics from the search + i = best_i + sync1 = best_sync1 + dt = best_dt + flipk = best_flipk + syncshort = best_syncshort + snr2 = best_snr2 + ipol2 = best_ipol2 + dt2 = best_dt2 + + ! Match the 3.0.1 double-click ("quick decode", nqd=1) rule: use a + ! lower sync threshold at the clicked frequency when ftol <= 100 Hz. + ! A fixed 1.0 here gates the click exactly like the wideband pass, + ! so a signal the wideband pass missed could never be decoded. + thresh1 = 1.0 + if (ntol .le. 100) thresh1 = 0. + nflip = nint(flipk) + call dbg('map65a manual: click nutc=' // itoa(nutc) // ' mousefqso=' // itoa(mousefqso) // & + ' mousedf=' // itoa(mousedf) // ' ntol=' // itoa(ntol) // & + ' best sync1=' // rtoa(sync1) // ' thresh1=' // rtoa(thresh1) // & + ' syncshort=' // rtoa(syncshort) // ' mode65=' // itoa(mode65)) + + !=========================== + ! SHORTHAND DETECTION (JT65) + !=========================== + shorthand_detected = .false. + + thresh0 = 1.0 + if (syncshort > thresh0 .and. mode65 > 0) then + shorthand_detected = .true. + + km = 1 + sig(1,1) = nfile + sig(1,2) = nutc + sig(1,3) = freq + sig(1,4) = syncshort + sig(1,5) = dt2 + sig(1,6) = 45*(ipol2 - 1)/57.2957795 + sig(1,7) = 0 + sig(1,8) = snr2 + sig(1,9) = 0 + sig(1,10)= 0 + sig(1,12)= savg_dec(ipol2,i) + msg(1) = shmsg0(1) + endif + + ! Bin frequency for this click (for decode1a’s f00) + f00 = (i - 1)*df + + ikhz = nint(freq + 0.5*(nfa + nfb) - foffset) - nfshift + idf = nint(1000.0*(freq + 0.5*(nfa + nfb) - foffset - (ikHz + nfshift))) + + noffset = nint(1000.0*(freq - fqso) - mousedf) + + ! JT65-specific rejects only when JT65 is active + if (mode65 > 0) then + if (sync1 <= thresh1) then + + if (.not. bq65) then + ! JT65-only mode → real reject + newdat = 0 + km = 0 + ncand = 0 + msg(1) = blank + msg(2) = blank + do j = 1, 30 + sig(1,j) = 0.0 + enddo + manualDecodeFlag = 0 + return + endif + + ! JT65 failed but Q65 is active → DO NOT RETURN + endif + + if (abs(noffset) > ntol) then + + if (.not. bq65) then + ! JT65-only mode → real reject + + newdat = 0 + km = 0 + ncand = 0 + + msg(1) = blank + msg(2) = blank + + do j = 1, 30 + sig(1,j) = 0.0 + enddo + + manualDecodeFlag = 0 + return + endif + + ! JT65 failed but Q65 is active → DO NOT RETURN + endif + endif + + !=========================== + ! JT65 MANUAL DECODE (if active) + !=========================== + jt65_success = .false. + decoded_jt65 = ' ' + + if (mode65 > 0 .and. sync1 > thresh1 .and. abs(noffset) <= ntol) then + + call timer('decode1a',0) + ifreq = i + + call decode1a(dd,newdat,f00,nflip,mode65,nfsample,xpol,mycall,hiscall, & + hisgrid,neme,ndepth,1,dphi,ndphi,nutc,ikHz,idf,ipol,ntol, & + sync2,a,dt,pol,nkv,nhist,nsum,nsave,qual,decoded_jt65) + call timer('decode1a',1) + + abort_decode = abort_saved + ! Fit and averaging details, to tell a normal decode from a strange one + ! (e.g. an odd DT). dt_in is the DT decode1a was given (from ccf65 at the + ! best bin), dt_out the DT it returned. nsum > 0 means the single-period + ! decode failed and decode1a went on to try averaging saved spectra; + ! nkv >= 2 with a decode means the message came from that average. + call dbg('map65a manual: decode1a called, decoded=[' // trim(decoded_jt65) // ']' // & + ' dt_in=' // rtoa(best_dt) // ' dt_out=' // rtoa(dt) // & + ' sync2=' // rtoa(sync2) // ' a1_df=' // rtoa(a(1)) // & + ' nkv=' // itoa(nkv) // ' nsum=' // itoa(nsum) // ' nsave=' // itoa(nsave) // & + ' nhist=' // itoa(nhist) // ' qual=' // rtoa(qual) // & + ' nflip=' // itoa(nflip) // ' f00=' // rtoa(real(f00))) + + if (decoded_jt65 /= ' ') then + jt65_success = .true. + + km = km + 1 + sig(km,1) = nfile + sig(km,2) = nutc + sig(km,3) = freq + 0.5*(nfa+nfb) + sig(km,4) = sync1 + sig(km,5) = dt + sig(km,6) = pol + sig(km,7) = flipk + sig(km,8) = sync2 + sig(km,9) = nkv + sig(km,10)= qual + sig(km,12)= savg_dec(ipol,i) + sig(km,13)= a(1) + sig(km,14)= a(2) + sig(km,15)= a(3) + sig(km,16)= a(4) + sig(km,18)= nhist + msg(km) = decoded_jt65 + endif + endif + + !=========================== + ! Q65 MANUAL DECODE (if active) + !=========================== + q65_success = .false. + + if (bq65) then + ! Include mousedf (the sub-kHz part of the click) so the search + ! is centered on the actual clicked frequency, not just rounded + ! to the nearest kHz -- matters once q65b targets this exactly + ! (see the manualDecodeFlag handling around k0 in q65b.F90). + freq = mousefqso + 0.001*mousedf + freq_q65 = freq + f0 = freq_q65 - (nkhz_center - real(nrate_active)/2000.0 - 1.27046) + nqd = 1 ! target-frequency decode, like wideband's quick pass at + ! fQSO; also required so q65b's own write_stdout/output + ! path (gated on nqd==1) actually emits the result + ikhz = nint(freq_q65) + ! NB: mousedf must stay relative to mousefqso here, unmodified -- + ! q65b.F90 also uses it (via f_mouse) to pick k0, the actual + ! sample-extraction point for the decode. A previous attempt to + ! re-reference it to ikhz here (for q65b's output gate, which + ! compares against ikhz-relative nq65df) fixed the gate but broke + ! k0/f_mouse, silently decoding whatever signal sits near the + ! *other* kHz bucket instead of the one actually clicked. The + ! gate's reference-frame mismatch is now fixed inside q65b.F90 + ! itself instead, from f0 (already unambiguous), leaving this + ! mousedf untouched for f_mouse/k0 to keep working correctly. + + call dbg('map65a manual: Q65 call nutc=' // itoa(nutc) // ' nqd=' // itoa(nqd) // & + ' ikhz=' // itoa(ikhz) // ' mousedf=' // itoa(mousedf) // ' ntol=' // itoa(ntol) // & + ' mode_q65=' // itoa(mode_q65) // ' f0=' // rtoa(real(f0)) // & + ' newdat=' // itoa(newdat) // ' nagain=' // itoa(nagain) // & + ' ndepth=' // itoa(ndepth) // ' max_drift=' // itoa(max_drift)) + + call timer('q65b ', 0) + call q65b(nutc, nqd, nxant, fcenter, nfcal, nfsample, ikhz, mousedf, & + ntol, xpol, idphi, mycall, mygrid, hiscall, hisgrid, mode_q65, f0, fqso, & + newdat, nagain, max_drift, ndop00, idec) + call timer('q65b ', 1) + + call dbg('map65a manual: Q65 result idec=' // itoa(idec) // ' nsnr0=' // itoa(nsnr0) // & + ' nfreq0=' // itoa(nfreq0) // ' xdt0=' // rtoa(xdt0) // ' msg0=[' // trim(msg0) // ']') + + ! NB: idec, as returned by q65b, is not a trustworthy success flag: + ! q65b derives it by parsing cq0(2:2) (see q65b.F90, label 900), and + ! cq0 is not reset on a failed attempt, so it can still read back + ! whatever digit was left over from an earlier, unrelated decode. + ! nsnr0 is q65b's own internal success test (freshly reset to -99 + ! immediately before it attempts this decode), so use that instead. + + q65_success = (nsnr0 .gt. -99) + ! On success, q65b has already written the decoded text itself + ! (write_stdout, plus units 26/21/12) because nqd=1 and the result + ! is within ntol of mousedf -- the same mechanism the wideband + ! quick-decode pass uses. Nothing further to add to km/msg/sig here. + endif + + !=========================== + ! EMIT DECODE(S) DIRECTLY + !=========================== + ! NB: this used to "go to 600" to reuse the wideband write/rescan + ! block, but that block lives inside "do nqd = 1, 0, -1 ... enddo" + ! while this code is lexically outside that loop. Branching into + ! the interior of a DO construct from outside it is illegal and + ! was causing a stray re-entrant q65b call (via the stale, never- + ! populated "cand" array) plus a "if (mode65.eq.0) km = 0" reset + ! that silently discarded the manual Q65 decode before it could be + ! written. Emit the km/msg/sig entries here instead. + if (jt65_success .or. q65_success .or. shorthand_detected) then + nwrite = 0 + + do k = 1, km + decoded = msg(k) + if (decoded .ne. ' ') then + nutc = sig(k,2) + freq = sig(k,3) + sync1 = sig(k,4) + dt = sig(k,5) + npol = nint(57.2957795*sig(k,6)) + flip = sig(k,7) + sync2 = sig(k,8) + nkv = sig(k,9) + nqual = sig(k,10) + if (flip .lt. 0.0) then + i = len_trim(decoded) + if (i .eq. 0) stop 'Error in message format' + if (i .le. 18) decoded(i + 2:i + 4) = 'OOO' + endif + nkHz = nint(freq - foffset) - nfshift + mhz = fcenter + f0 = mhz + 0.001*nkHz + ndf = nint(1000.0*(freq - foffset - (nkHz + nfshift))) + nsync1 = sync1 + s2db = 10.0*log10(sync2) - 40 + nsync2 = nint(s2db) + if (decoded(1:4) .eq. 'RO ' .or. decoded(1:4) .eq. 'RRR ' .or. & + decoded(1:4) .eq. '73 ') then + nsync2 = nint(1.33*s2db + 2.0) + endif + + nwrite = nwrite + 1 + if (nxant .ne. 0) then + npol = npol - 45 + if (npol .lt. 0) npol = npol + 180 + endif + + call txpol(xpol, decoded, mygrid, npol, nxant, ntxpol, cp) + + write (line, '("!",I3,I5,I4,I6.4,F5.1,I5,1X,A1,1X,A22,I2,I5,I5,1X,A1)') & + nkHz, ndf, npol, nutc, dt, nsync2, cm, decoded, nkv, nqual, ntxpol, cp + call write_stdout(trim(line)//new_line('a')) + endif + enddo ! k=1,km + + manualDecodeFlag = 0 + return + endif + + newdat = 0 + km = 0 + ncand = 0 + msg(1) = blank + msg(2) = blank + do j = 1, 30 + sig(1,j) = 0.0 + enddo + manualDecodeFlag = 0 + return + endif + + +!------------------------------------------------------------ +! WIDEBAND CODE RESUMES HERE +!------------------------------------------------------------ + +! km is "save"d across calls, but this point runs once per Find-dPhi trial +! (iloop 0..12 via "go to 2" below) as well as once for a normal decode. +! Without resetting it here, each later trial's "do k=1,km" write-out loop +! replays every earlier trial's decode(s) again verbatim -- the repeated, +! made-up-looking decodes seen with Find Delta Phi. +km = 0 + +! Only JT65 applies the trial phase; Q65 keeps the same input each time. +if (ndphi .eq. 1) then + ljt65decoded = .false. +endif + +ftol = 0.010 +fqso = mousefqso + foffset - 0.5*(nfa + nfb) + nfshift +nkhz_center = nint(1000.0*(fcenter - int(fcenter))) +mfa = nfa - nkhz_center + int(nrate_active/2000.0) +mfb = nfb - nkhz_center + int(nrate_active/2000.0) + +tsec_mod = real(mod(t_start, 60), kind=4) +! Number of samples to use for RMS check +n_rms = min(322, 2048) + +sumsq = 0.0d0 +do i2 = 1, n_rms + v = ss_dec(1, i2, 1) + sumsq = sumsq + v*v +end do + +if (n_rms > 0) then + rms = sqrt(sumsq / dble(n_rms)) +else + rms = 0.0d0 +endif + +if (nagain .eq. 0) then + call timer('get_cand', 0) + call get_candidates(ss_dec, savg_dec, xpol, nhsym, mfa, mfb, nts_jt65, nts_q65, cand, ncand) + call timer('get_cand', 1) + candec = .false. + ! TEMP diagnostic 2026-09-09 for the missing-upper-Q65-decode investigation. + call dbg('map65a: get_candidates done at t=' // rtoa(sec_midn()) // & + ' ncand=' // itoa(ncand) // ' n_q65cand=' // itoa(count(cand(1:max(ncand,0))%iflip == 0)) // & + ' bq65=' // itoa(merge(1,0,bq65)) // ' xpol=' // itoa(merge(1,0,xpol)) // & + ' nhsym=' // itoa(nhsym) // ' manualDecodeFlag_initial=' // itoa(manualDecodeFlag_initial)) +endif + + do nqd = 1, 0, -1 + + call system_clock(t_now, t_rate) + call dbg('map65a: nqd loop top at t=' // rtoa(sec_midn()) // & + ' nqd=' // itoa(nqd) // ' elapsed=' // rtoa(real(t_now - t_start)/real(t_rate)) // & + ' manualDecodeFlag_initial=' // itoa(manualDecodeFlag_initial)) + if (real(t_now - t_start)/real(t_rate) > 40.0) then + abort_decode = .true. + call dbg('map65a: ABORT (40s budget exceeded) at t=' // rtoa(sec_midn()) // ' nqd=' // itoa(nqd)) + go to 700 + endif + + if (manualDecodeFlag_initial == 1 .and. nqd == 0) then + call dbg('map65a: nqd=0 CYCLE-skipped (manualDecodeFlag_initial=1) at t=' // rtoa(sec_midn())) + cycle + endif + + + if (nqd .eq. 1) then !Quick decode, at fQSO + fa = 1000.0*(fqso + 0.001*mousedf) - ntol + fb = 1000.0*(fqso + 0.001*mousedf) + ntol + 4*(96000.0/1783.0) + else !Wideband decode at all freqs + fa = -1000*0.5*(nfb - nfa) + 1000*nfshift + fb = 1000*0.5*(nfb - nfa) + 1000*nfshift + + ! Debug: report JT65 wideband search window + +!write(sfa, '(F20.6)') fa +!write(sfb, '(F20.6)') fb +!write(sspan, '(F20.6)') (fb-fa)/1000.0 + + endif + icenter = nfft_active/2 + 1 + ia = nint(fa/df) + icenter + ib = nint(fb/df) + icenter + ia = max(51, ia) + ib = min(nfft_active - 51, ib) + if (ndiskdat .eq. 1 .and. mode65 .eq. 0) ib = ia + + nkm = 1 + freq0 = -999. + sync10 = -999. + fshort0 = -999. + syncshort0 = -999. + ntry = 0 + short = 0. !Zero the whole short array + jpz = 1 + if (xpol) jpz = 4 + + ! TEMP diagnostic 2026-09-09 for the missing-other-JT65-signal investigation. + call dbg('map65a: JT65 sweep window at t=' // rtoa(sec_midn()) // & + ' nqd=' // itoa(nqd) // ' fa=' // rtoa(fa) // ' fb=' // rtoa(fb) // & + ' ia=' // itoa(ia) // ' ib=' // itoa(ib) // ' km_entering=' // itoa(km)) + + do i = ia, ib !Search over freq range + + call system_clock(t_now, t_rate) + if (real(t_now - t_start)/real(t_rate) > 40.0) then + call dbg('Decode abort: exceeded 40 seconds in do i = ia, ib pass, nqd=' // itoa(nqd) // ' i=' // itoa(i)) + abort_decode = .true. + ! "go to 700" here used to jump past the Q65 candidate-decode + ! loop below (do icand = 1, ncand), which only runs after this + ! JT65 sweep completes -- so a slow JT65 sweep (e.g. many + ! birdie-triggered decode1a calls) could burn the whole 40 s + ! budget and starve Q65 of any decode attempt at all, even + ! though its candidates were already found by get_candidates() + ! before this loop started. Just stop scanning more JT65 bins + ! instead, so Q65 still gets its turn this pass. + exit + endif + + freq = 0.001*(i - icenter)*df ! Find the local base level for each polarization; update every 10 bins. - if(mod(i-ia,10).eq.0) then - do jp=1,jpz - do ii=-50,50 - iii=i+ii - if(iii.ge.1 .and. iii.le.32768) then - tavg(ii)=savg(jp,iii) - else - write(13,*) 'Error in iii:',iii,ia,ib,fa,fb - flush(13) - go to 900 - endif - enddo - call pctile(tavg,101,50,base(jp)) - enddo - endif + if (mod(i - ia, 10) .eq. 0) then + do jp = 1, jpz + do ii = -50, 50 + iii = i + ii + if (iii .ge. 1 .and. iii .le. nfft_active) then + tavg(ii) = savg_dec(jp, iii) + else + write (13, *) 'Error in iii:', iii, ia, ib, fa, fb + flush (13) + go to 900 + endif + enddo + call pctile(tavg, 101, 50, base(jp)) + enddo + endif ! Find max signal at this frequency - smax=0. - do jp=1,jpz - if(savg(jp,i)/base(jp).gt.smax) then - smax=savg(jp,i)/base(jp) - jpmax=jp - endif - enddo - - if(smax.gt.1.1 .or. ia.eq.ib) then + smax = 0. + jpmax = 1 + do jp = 1, jpz + if (savg_dec(jp, i)/base(jp) .gt. smax) then + smax = savg_dec(jp, i)/base(jp) + jpmax = jp + endif + enddo + + if (smax .gt. 1.1 .or. ia .eq. ib) then + ! Look for JT65 sync patterns and shorthand square-wave patterns. - call timer('ccf65 ',0) - ssmax=1.e30 - call ccf65(ss(1,1,i),nhsym,ssmax,sync1,ipol,jpz,dt, & - flipk,syncshort,snr2,ipol2,dt2) -!### if(dt.lt.-2.6 .or. dt.gt.2.5) sync1=-99.0 !### - call timer('ccf65 ',1) - if(mode65.eq.0) syncshort=-99.0 !If "No JT65", don't waste time + call timer('ccf65 ', 0) + ssmax = 1.e30 + call ccf65(ss_dec(:,:,i), nhsym, ssmax, sync1, ipol, jpz, dt, flipk, & + syncshort, snr2, ipol2, dt2) + call timer('ccf65 ', 1) + ! 2026-09-12: instrumentation for the "identical anomalous + ! dtbest across several consecutive nqd=0 candidates" investigation. + ! Logging ccf65's own per-candidate dt (the value that becomes + ! decode1a's dt00 input) so a live capture can show directly + ! whether the staleness/repetition already exists at THIS + ! input, before decode1a/afc65b ever runs. + call dbg('map65a: ccf65 result at t=' // rtoa(sec_midn()) // & + ' nqd=' // itoa(nqd) // ' i=' // itoa(i) // ' dt=' // rtoa(dt) // & + ' sync1=' // rtoa(sync1) // ' ntry=' // itoa(ntry)) + if (mode65 .eq. 0) syncshort = -99.0 !If "No JT65", don't waste time ! ########################### Search for Shorthand Messages ################# ! Is there a shorthand tone above threshold? - thresh0=1.0 + thresh0 = 1.0 ! Use lower thresh0 at fQSO - if(nqd.eq.1 .and. ntol.le.100) thresh0=0. - if(syncshort.gt.thresh0) then + if (nqd .eq. 1 .and. ntol .le. 100) thresh0 = 0. + if (syncshort .gt. thresh0) then ! ### Do shorthand AFC here (or maybe after finding a pair?) ### - short(1,i)=syncshort - short(2,i)=dt2 - short(3,i)=ipol2 + short(1, i) = syncshort + short(2, i) = dt2 + short(3, i) = ipol2 ! Check to see if lower tone of shorthand pair was found. - do j=2,4 - i0=i-nint(j*mode65*10.0*(11025.0/4096.0)/df) + do j = 2, 4 + i0 = i - nint(j*mode65*10.0*(11025.0/4096.0)/df) ! Should this be i0 +/- 1, or just i0? ! Should we also insist that difference in DT be either 1.5 or -1.5 s? - if(short(1,i0).gt.thresh0) then - fshort=0.001*(i0-16385)*df - noffset=0 - if(nqd.eq.1) noffset=nint(1000.0*(fshort-fqso)-mousedf) - if(abs(noffset).le.ntol) then + if (short(1, i0) .gt. thresh0) then + fshort = 0.001*(i0 - icenter)*df + noffset = 0 + if (nqd .eq. 1) noffset = nint(1000.0*(fshort - fqso) - mousedf) + if (abs(noffset) .le. ntol) then ! Keep only the best candidate within ftol. !### NB: sync2 was not defined here! ! sync2=syncshort !### try this ??? - if(fshort-fshort0.le.ftol .and. & + if (fshort - fshort0 .le. ftol .and. & syncshort.gt.syncshort0 .and. nkm.eq.2) km=km-1 - if(fshort-fshort0.gt.ftol .or. & - syncshort.gt.syncshort0) then - if(km.lt.MAXMSG) km=km+1 - sig(km,1)=nfile - sig(km,2)=nutc - sig(km,3)=fshort + 0.5*(nfa+nfb) - sig(km,4)=syncshort - sig(km,5)=dt2 - sig(km,6)=45*(ipol2-1)/57.2957795 - sig(km,7)=0 - sig(km,8)=snr2 - sig(km,9)=0 - sig(km,10)=0 + if (fshort - fshort0 .gt. ftol .or. & + syncshort .gt. syncshort0) then + if (km .lt. MAXMSG) km = km + 1 + sig(km, 1) = nfile + sig(km, 2) = nutc + sig(km, 3) = fshort + 0.5*(nfa + nfb) + sig(km, 4) = syncshort + sig(km, 5) = dt2 + sig(km, 6) = 45*(ipol2 - 1)/57.2957795 + sig(km, 7) = 0 + sig(km, 8) = snr2 + sig(km, 9) = 0 + sig(km, 10) = 0 ! sig(km,11)=rms0 - sig(km,12)=savg(ipol2,i) - sig(km,13)=0 - sig(km,14)=0 - sig(km,15)=0 - sig(km,16)=0 + sig(km, 12) = savg_dec(ipol2, i) + sig(km, 13) = 0 + sig(km, 14) = 0 + sig(km, 15) = 0 + sig(km, 16) = 0 ! sig(km,17)=0 - sig(km,18)=0 - msg(km)=shmsg0(j) - fshort0=fshort - syncshort0=syncshort - nkm=2 - endif - endif - endif - enddo - endif + sig(km, 18) = 0 + msg(km) = shmsg0(j) + + fshort0 = fshort + syncshort0 = syncshort + nkm = 2 + endif + endif + endif + enddo + endif ! ########################### Search for Normal Messages ########### ! Is sync1 above threshold? - thresh1=1.0 + thresh1 = 1.0 ! Use lower thresh1 at fQSO - if(nqd.eq.1 .and. ntol.le.100) thresh1=0. - noffset=0 - if(nqd.ge.1) noffset=nint(1000.0*(freq-fqso)-mousedf) - if(newdat.eq.1 .and. sync1.gt.-99.0) then - sync1=thresh1+1.0 - noffset=0 - endif - if(sync1.gt.thresh1 .and. abs(noffset).le.ntol) then + if (nqd .eq. 1 .and. ntol .le. 100) thresh1 = 0. + noffset = 0 + if (nqd .ge. 1) noffset = nint(1000.0*(freq - fqso) - mousedf) + initialization_only = .false. + if (newdat .eq. 1 .and. sync1 .gt. -99.0 .and. & + (sync1 .le. thresh1 .or. abs(noffset) .gt. ntol)) then + initialization_only = .true. + sync1 = thresh1 + 1.0 + noffset = 0 + endif + ! Computed once per candidate, before the "keep only best + ! within ftol" collapse logic just below -- see the SKIPPED + ! branch right after for why the ordering matters. Must be + ! false whenever initialization_only is true: that probe + ! doesn't accumulate anything regardless, but still needs + ! decode1a() called once per sweep for its own internal + ! state, so it must not be intercepted here. + already_decoded_nearby = (.not. initialization_only) .and. & + any(ljt65decoded(max(1,i-JT65_LOCAL_BINS):min(nfft_active,i+JT65_LOCAL_BINS))) + + if (sync1 .gt. thresh1 .and. abs(noffset) .le. ntol) then + if (already_decoded_nearby) then + ! Skip a candidate whose bin (or a nearby one, within + ! JT65_LOCAL_BINS) already produced a real decode + ! earlier this same accumulation cycle, mirroring + ! Q65's ldecoded(ipk) (decodes_mod.f90) -- otherwise a + ! repeat automatic call re-discovers and re-emits the + ! same JT65 decode. + ! + ! Must run before the "keep only best within ftol" + ! collapse logic below, not after: that logic's + ! "km=km-1" runs unconditionally, on the assumption + ! that accumulation always follows with a matching + ! "km=km+1" -- skipping AFTER that decrement leaves it + ! unmatched and silently drives km negative, hiding + ! the whole signal from this pass's output. + call dbg('map65a: JT65 i=' // itoa(i) // & + ' SKIPPED (already decoded nearby this cycle) at t=' // rtoa(sec_midn())) + else ! Keep only the best candidate within ftol. ! (Am I deleting any good decodes by doing this?) if(freq-freq0.le.ftol .and. sync1.gt.sync10 .and. & nkm.eq.1) km=km-1 - if(freq-freq0.gt.ftol .or. sync1.gt.sync10) then - nflip=nint(flipk) - f00=(i-1)*df !Freq of detected sync tone (0-96000 Hz) - ntry=ntry+1 - if((nqd.eq.1 .and. ntry.ge.40) .or. & - (nqd.eq.0 .and. ntry.ge.400)) then -! Too many calls to decode1a! - write(*,*) '! Signal too strong, or suspect data? Decoding aborted.' - write(13,*) 'Signal too strong, or suspect data? Decoding aborted.' - call flush(13) - go to 900 - endif - - call timer('decode1a',0) - ifreq=i - ikhz=nint(freq+0.5*(nfa+nfb)-foffset)-nfshift - idf=nint(1000.0*(freq+0.5*(nfa+nfb)-foffset-(ikHz+nfshift))) - call decode1a(dd,newdat,f00,nflip,mode65,nfsample, & - xpol,mycall,hiscall,hisgrid,neme,ndepth,nqd,dphi, & - ndphi,nutc,ikHz,idf,ipol,ntol,sync2, & - a,dt,pol,nkv,nhist,nsum,nsave,qual,decoded) - call timer('decode1a',1) - -! The case sync1=2.0 is just to make sure decode1a is called and bigfft done. - if(mode65.ne.0 .and. sync1.ne.2.000000) then - if(km.lt.MAXMSG) km=km+1 - sig(km,1)=nfile - sig(km,2)=nutc - sig(km,3)=freq + 0.5*(nfa+nfb) - sig(km,4)=sync1 - sig(km,5)=dt - sig(km,6)=pol - sig(km,7)=flipk - sig(km,8)=sync2 - sig(km,9)=nkv - sig(km,10)=qual + if (freq - freq0 .gt. ftol .or. sync1 .gt. sync10) then + nflip = nint(flipk) + f00 = (i - 1)*df !Freq of detected sync tone (0-96000 Hz) + ntry = ntry + 1 + if ((nqd .eq. 1 .and. ntry .ge. 40) .or. & + (nqd .eq. 0 .and. ntry .ge. 400)) then + ! Too many calls to decode1a for this pass -- stop scanning more + ! frequency bins for JT65 candidates here, but only here: exit just this + ! do i=ia,ib sweep. A "go to 900" used to jump all the way past the rest + ! of this pass (including the wideband Q65 full-decode loop further + ! below when nqd=0), all remaining nqd passes, and the post-loop + ! cleanup/display() -- silently costing Q65 a whole minute even though + ! the abort was tripped by JT65 candidate volume, not a Q65 problem. + call dbg('map65a: Signal too strong, decoding aborted, nqd=' // itoa(nqd) // & + ' ntry=' // itoa(ntry) // ' i=' // itoa(i)) + call write_stdout('! Signal too strong, or suspect data? Decoding aborted.'//new_line('a')) + write (13, *) 'Signal too strong, or suspect data? Decoding aborted.' + flush (13) + exit + endif + + call timer('decode1a', 0) + ifreq = i + ikhz = nint(freq + 0.5*(nfa + nfb) - foffset) - nfshift + idf = nint(1000.0*(freq + 0.5*(nfa + nfb) - foffset - (ikHz + nfshift))) + + call decode1a(dd, newdat, f00, nflip, merge(0,mode65,initialization_only), nfsample, & + xpol, mycall, hiscall, hisgrid, neme, ndepth, nqd, dphi, & + ndphi, nutc, ikHz, idf, ipol, ntol, sync2, & + a, dt, pol, nkv, nhist, nsum, nsave, qual, decoded) + call timer('decode1a', 1) + ! 2026-09-12: paired with the ccf65 instrumentation above -- + ! logs decode1a's OUTPUT dt (dt00+dtbest+1.7, so this + ! encodes dtbest even though dtbest itself isn't passed + ! back to this scope), the running real-candidate count + ! this pass (ntry, already used for the "signal too + ! strong" abort check), and elapsed wall-clock time, so a + ! live capture can show whether the anomaly correlates + ! with how many real candidates/how much time this pass + ! has already chewed through before reaching this one. + call dbg('map65a: decode1a call ' // itoa(ntry) // ' this pass at t=' // & + rtoa(sec_midn()) // ' nqd=' // itoa(nqd) // ' i=' // itoa(i) // & + ' f00=' // rtoa(real(f00)) // ' dt_out=' // rtoa(dt) // & + ' initialization_only=' // itoa(merge(1,0,initialization_only)) // & + ' decoded="' // trim(decoded) // '"') + + call dbg('map65a: decode1a result at t=' // rtoa(sec_midn()) // & + ' nqd=' // itoa(nqd) // ' i=' // itoa(i) // ' freq=' // rtoa(freq) // & + ' sync1=' // rtoa(sync1) // ' initialization_only=' // itoa(merge(1,0,initialization_only)) // & + ' decoded="' // trim(decoded) // '"') + + if (mode65 .ne. 0 .and. .not. initialization_only) then + if (km .lt. MAXMSG) km = km + 1 + sig(km, 1) = nfile + sig(km, 2) = nutc + sig(km, 3) = freq + 0.5*(nfa + nfb) + sig(km, 4) = sync1 + sig(km, 5) = dt + sig(km, 6) = pol + sig(km, 7) = flipk + sig(km, 8) = sync2 + sig(km, 9) = nkv + sig(km, 10) = qual ! sig(km,11)=idphi - sig(km,12)=savg(ipol,i) - sig(km,13)=a(1) - sig(km,14)=a(2) - sig(km,15)=a(3) - sig(km,16)=a(4) + sig(km, 12) = savg_dec(ipol, i) + sig(km, 13) = a(1) + sig(km, 14) = a(2) + sig(km, 15) = a(3) + sig(km, 16) = a(4) ! sig(km,17)=a(5) - sig(km,18)=nhist - msg(km)=decoded - freq0=freq - sync10=sync1 - nkm=1 - endif - endif - endif - endif - enddo !i=ia,ib - - if(nqd.eq.1) then - nwrite=0 - if(mode65.eq.0) km=0 - do k=1,km - decoded=msg(k) - if(decoded.ne.' ') then - nutc=sig(k,2) - freq=sig(k,3) - sync1=sig(k,4) - dt=sig(k,5) - npol=nint(57.2957795*sig(k,6)) - flip=sig(k,7) - sync2=sig(k,8) - nkv=sig(k,9) - nqual=sig(k,10) + sig(km, 18) = nhist + msg(km) = decoded + freq0 = freq + sync10 = sync1 + nkm = 1 + ! The lookup supplies the neighborhood radius; + ! marking it here too would double the exclusion. + if (decoded .ne. ' ') & + ljt65decoded(i) = .true. + endif + endif + endif + endif + endif + enddo !i=ia,ib + + call dbg('map65a: JT65 sweep done at t=' // rtoa(sec_midn()) // & + ' nqd=' // itoa(nqd) // ' km_exiting=' // itoa(km) // ' ntry=' // itoa(ntry)) + + if (nqd .eq. 1) then + nwrite = 0 + if (mode65 .eq. 0) km = 0 + + do k = 1, km + decoded = msg(k) + if (decoded .ne. ' ') then + nutc = sig(k, 2) + freq = sig(k, 3) + sync1 = sig(k, 4) + dt = sig(k, 5) + npol = nint(57.2957795*sig(k, 6)) + flip = sig(k, 7) + sync2 = sig(k, 8) + nkv = sig(k, 9) + nqual = sig(k, 10) ! idphi=nint(sig(k,11)) - if(flip.lt.0.0) then - do i=22,1,-1 - if(decoded(i:i).ne.' ') go to 8 - enddo - stop 'Error in message format' -8 if(i.le.18) decoded(i+2:i+4)='OOO' - endif - nkHz=nint(freq-foffset)-nfshift - mhz=fcenter ! ... +fadd ??? - f0=mhz+0.001*nkHz - ndf=nint(1000.0*(freq-foffset-(nkHz+nfshift))) - nsync1=sync1 - - s2db=10.0*log10(sync2) - 40 !### empirical ### - nsync2=nint(s2db) - if(decoded(1:4).eq.'RO ' .or. decoded(1:4).eq.'RRR ' .or. & - decoded(1:4).eq.'73 ') then - nsync2=nint(1.33*s2db + 2.0) - endif - - nwrite=nwrite+1 - if(nxant.ne.0) then - npol=npol-45 - if(npol.lt.0) npol=npol+180 - endif - - call txpol(xpol,decoded,mygrid,npol,nxant,ntxpol,cp) - - if(ndphi.eq.0) then - write(*,1010) nkHz,ndf,npol,nutc,dt,nsync2, & - cm,decoded,nkv,nqual,ntxpol,cp -1010 format('!',i3,i5,i4,i6.4,f5.1,i5,1x,a1,1x,a22,i2,i5,i5,1x,a1) - else - if(iloop.ge.1) qphi(iloop)=sig(k,10) - write(*,1010) nkHz,ndf,npol,nutc,dt,nsync2, & - cm,decoded,nkv,nqual,30*iloop - write(27,1011) 30*iloop,nkHz,ndf,npol,nutc, & - dt,sync2,nkv,nqual,cm,decoded -1011 format(i3,i4,i5,i4,i6.4,1x,f5.1,f7.1,i3,i5,a1,1x,a22) - endif - endif - enddo ! k=1,km - - if(bq65) then - q65b_called=.false. - do icand=1,ncand - if(cand(icand)%iflip.ne.0) cycle !Keep only Q65 candidates - freq=cand(icand)%f+nkhz_center-48.0-1.27046 - nhzdiff=nint(1000.0*(freq-mousefqso)-mousedf) - nfcal + if (flip .lt. 0.0) then + do i = 22, 1, -1 + if (decoded(i:i) .ne. ' ') go to 8 + enddo + stop 'Error in message format' +8 if (i .le. 18) decoded(i + 2:i + 4) = 'OOO' + endif + nkHz = nint(freq - foffset) - nfshift + mhz = fcenter ! ... +fadd ??? + f0 = mhz + 0.001*nkHz + ndf = nint(1000.0*(freq - foffset - (nkHz + nfshift))) + nsync1 = sync1 + s2db = 10.0*log10(sync2) - 40 !### empirical ### + nsync2 = nint(s2db) + if (decoded(1:4) .eq. 'RO ' .or. decoded(1:4) .eq. 'RRR ' .or. & + decoded(1:4) .eq. '73 ') then + nsync2 = nint(1.33*s2db + 2.0) + endif + + nwrite = nwrite + 1 + if (nxant .ne. 0) then + npol = npol - 45 + if (npol .lt. 0) npol = npol + 180 + endif + + call txpol(xpol, decoded, mygrid, npol, nxant, ntxpol, cp) + + if (ndphi .eq. 0) then + write (line, '("!",I3,I5,I4,I6.4,F5.1,I5,1X,A1,1X,A22,I2,I5,I5,1X,A1)') & + nkHz, ndf, npol, nutc, dt, nsync2, cm, decoded, nkv, nqual, ntxpol, cp + call write_stdout(trim(line)//new_line('a')) + else + if (iloop .ge. 1) qphi(iloop) = sig(k, 10) + + write (line, '("!",I3,I5,I4,I6.4,F5.1,I5,1X,A1,1X,A22,I2,I5,I5,1X,A1)') & + nkHz, ndf, npol, nutc, dt, nsync2, cm, decoded, nkv, nqual, 30*iloop, '-' + call write_stdout(trim(line)//new_line('a')) + write (27, 1011) 30*iloop, nkHz, ndf, npol, nutc, & + dt, sync2, nkv, nqual, cm, decoded +1011 format(i3, i4, i5, i4, i6.4, 1x, f5.1, f7.1, i3, i5, a1, 1x, a22) + endif + endif + enddo ! k=1,km + + if (bq65) then + q65b_called = .false. + do icand = 1, ncand + if (cand(icand)%iflip .ne. 0) cycle !Keep only Q65 candidates + freq = cand(icand)%f + nkhz_center - real(nrate_active)/2000.0 - 1.27046 + nhzdiff = nint(1000.0*(freq - mousefqso) - mousedf) - nfcal ! Now looking for "quick decode" (nqd=1) candidates at cursor freq +/- ntol. - if(nqd.eq.1 .and. abs(nhzdiff).gt.ntol) cycle - ikhz=mousefqso - q65b_called=.true. - f0=cand(icand)%f - call timer('q65b ',0) - call q65b(nutc,nqd,nxant,fcenter,nfcal,nfsample,ikhz,mousedf, & - ntol,xpol,mycall,mygrid, hiscall,hisgrid,mode_q65,f0,fqso, & - newdat,nagain,max_drift,nhsym,ndop00,idec) - call timer('q65b ',1) - if(idec.ge.0) candec(icand)=.true. - enddo - if(.not.q65b_called) then - freq=mousefqso + 0.001*mousedf - ikhz=mousefqso - f0=freq - (nkhz_center-48.0-1.27046) !### ??? ### - call timer('q65b ',0) - call q65b(nutc,nqd,nxant,fcenter,nfcal,nfsample,ikhz,mousedf, & - ntol,xpol,mycall,mygrid,hiscall,hisgrid,mode_q65,f0,fqso, & - newdat,nagain,max_drift,nhsym,ndop00,idec) - call timer('q65b ',1) - endif - endif - - if(nwrite.eq.0 .and. nwrite_q65.eq.0) then - write(*,1012) mousefqso,nutc -1012 format('!',i3,9x,i6.4,' ') - endif - endif !nqd.eq.1 - - if(ndphi.eq.1 .and.iloop.lt.12) then - iloop=iloop+1 - go to 2 - endif - - if(ndphi.eq.1 .and.iloop.eq.12) call getdphi(qphi) - if(nqd.eq.1) then - call sec0(1,tdec) - write(*,1013) nsum,nsave,nstandalone,nhsym,tdec -1013 format('<QuickDecodeDone>',3i4,i6,f6.2) - flush(6) - open(16,file='tquick.dat',status='unknown',access='append') - write(16,1016) nutc,tdec -1016 format(i4.4,f7.1) - close(16) - endif - call sec0(1,tsec0) - if(nhsym.eq.nhsym1 .and. tsec0.gt.3.0) go to 700 - if(nqd.eq.1 .and. nagain.eq.1) go to 900 - - if(nqd.eq.0 .and. bq65) then -! Do the wideband Q65 decode - do icand=1,ncand - if(cand(icand)%iflip.ne.0) cycle !Do only Q65 candidates here - if(candec(icand)) cycle !Skip if already decoded - freq=cand(icand)%f+nkhz_center-48.0-1.27046 + if (nqd .eq. 1 .and. abs(nhzdiff) .gt. ntol) cycle + ikhz = mousefqso + q65b_called = .true. + f0 = cand(icand)%f + call timer('q65b ', 0) + + call q65b(nutc, nqd, nxant, fcenter, nfcal, nfsample, ikhz, mousedf, & + ntol, xpol, idphi, mycall, mygrid, hiscall, hisgrid, mode_q65, f0, fqso, & + newdat, nagain, max_drift, ndop00, idec) + + call timer('q65b ', 1) + + ! idec is not a trustworthy success flag here -- q65b + ! derives it from cq0(2:2), which is not reset on a + ! failed/no-op attempt, so a later candidate in this same + ! loop can falsely read back an earlier candidate's + ! leftover cq0 digit. nsnr0 is reset to -99 at the top of + ! every q65b() call (q65b.F90) and can't carry state + ! across candidates this way. + if (nsnr0 .gt. -99) candec(icand) = .true. + enddo + if (.not. q65b_called) then + freq = mousefqso + 0.001*mousedf + ikhz = mousefqso + f0 = freq - (nkhz_center - real(nrate_active)/2000.0 - 1.27046) + call timer('q65b ', 0) + + call q65b(nutc, nqd, nxant, fcenter, nfcal, nfsample, ikhz, mousedf, & + ntol, xpol, idphi, mycall, mygrid, hiscall, hisgrid, mode_q65, f0, fqso, & + newdat, nagain, max_drift, ndop00, idec, cursor_fallback=.true.) + + call timer('q65b ', 1) + endif + endif + + if (nwrite .eq. 0 .and. nwrite_q65 .eq. 0) then + write (line, '("!",I3,9X,I6.4," ")') mousefqso, nutc + call write_stdout(trim(line)//new_line('a')) + endif + endif !nqd.eq.1 + + if (ndphi .eq. 1 .and. iloop .lt. 12) then + iloop = iloop + 1 + go to 2 + endif + + if (ndphi .eq. 1 .and. iloop .eq. 12 .and. nqd .eq. 1) call getdphi(qphi) + if (nqd .eq. 1) then + call sec0(1, tdec) + write (line, '("<QuickDecodeDone>",3I4,I6,F6.2)') & + nsum, nsave, nstandalone, nhsym, tdec + + call write_stdout(trim(line)//new_line('a')) + + open (16, file='tquick.dat', status='unknown', position='append') + write (16, 1016) nutc, tdec +1016 format(i4.4, f7.1) + close (16) + endif + call sec0(1, tsec0) + call dbg('map65a: end of nqd=' // itoa(nqd) // ' body at t=' // rtoa(sec_midn()) // & + ' tsec0=' // rtoa(tsec0) // ' nhsym=' // itoa(nhsym) // ' nagain=' // itoa(nagain)) + if (nhsym .eq. nhsym1 .and. tsec0 .gt. 3.0) then + call dbg('map65a: ABORT (early-pass 3s budget) at t=' // rtoa(sec_midn()) // & + ' tsec0=' // rtoa(tsec0) // ' -- nqd=0 will NOT run this pass') + go to 700 + endif + if (nqd .eq. 1 .and. nagain .eq. 1) then + call dbg('map65a: SKIP nqd=0 (nagain=1, manual repeat) at t=' // rtoa(sec_midn())) + go to 900 + endif + + if (nqd .eq. 0 .and. bq65) then +! Do the wideband Q65 decode + do icand = 1, ncand + if (cand(icand)%iflip .ne. 0) cycle !Do only Q65 candidates here + if (candec(icand)) cycle !Skip if already decoded + freq = cand(icand)%f + nkhz_center - real(nrate_active)/2000.0 - 1.27046 !###! If here at nqd=1, do only candidates at mousefqso +/- ntol !### if(nqd.eq.1 .and. abs(freq-mousefqso).gt.0.001*ntol) cycle - ikhz=nint(freq) - f0=cand(icand)%f - call timer('q65b ',0) - call q65b(nutc,nqd,nxant,fcenter,nfcal,nfsample,ikhz,mousedf,ntol, & - xpol,mycall,mygrid,hiscall,hisgrid,mode_q65,f0,fqso,newdat, & - nagain,max_drift,nhsym,ndop00,idec) - call timer('q65b ',1) - if(idec.ge.0) candec(icand)=.true. - enddo ! icand - endif - call sec0(1,tsec0) - - enddo ! nqd - -! Trim the list and produce a sorted index and sizes of groups. -! (Should trimlist remove all but best SNR for given UTC and message content?) -700 call trimlist(sig,km,ftol,indx,nsiz,nz) - done(1:km)=.false. - j=0 - ilatest=-1 - do n=1,nz - ifile0=0 - do m=1,nsiz(n) - i=indx(j+m) - ifile=sig(i,1) - if(ifile.gt.ifile0 .and.msg(i).ne.blank) then - ilatest=i - ifile0=ifile - endif - enddo - i=ilatest - - if(i.ge.1) then - if(.not.done(i)) then - done(i)=.true. - nutc=sig(i,2) - freq=sig(i,3) - sync1=sig(i,4) - dt=sig(i,5) - npol=nint(57.2957795*sig(i,6)) - flip=sig(i,7) - sync2=sig(i,8) - nkv=sig(i,9) - nqual=min(sig(i,10),10.0) + ikhz = nint(freq) + f0 = cand(icand)%f + call timer('q65b ', 0) + + call q65b(nutc, nqd, nxant, fcenter, nfcal, nfsample, ikhz, mousedf, & + ntol, xpol, idphi, mycall, mygrid, hiscall, hisgrid, mode_q65, f0, fqso, & + newdat, nagain, max_drift, ndop00, idec) + + call timer('q65b ', 1) + + ! See the matching note on the nqd==1 candidate loop above -- + ! idec is unreliable across back-to-back q65b() calls in the + ! same loop; use nsnr0 instead. + if (nsnr0 .gt. -99) candec(icand) = .true. + if (abort_decode) go to 700 + enddo ! icand + endif + call sec0(1, tsec0) + + call system_clock(t_now, t_rate) + if (real(t_now - t_start)/real(t_rate) > 40.0) then + call dbg('Decode abort: exceeded 40 seconds at end of do nqd = 1, 0, -1 pass, nqd=' // itoa(nqd)) + abort_decode = .true. + go to 700 + endif + + enddo ! nqd + +700 continue + ! TEMP diagnostic 2026-09-09 for the missing-other-signals-in-Messages investigation. + call dbg('map65a: reached label 700 at t=' // rtoa(sec_midn()) // & + ' km=' // itoa(km) // ' abort_decode=' // itoa(merge(1,0,abort_decode)) // & + ' nhsym=' // itoa(nhsym)) + call select_unique_decodes(sig, msg, km, ftol, RESULT_DT_TOLERANCE, indx, nz) + call dbg('map65a: select_unique_decodes done at t=' // rtoa(sec_midn()) // & + ' km=' // itoa(km) // ' nz=' // itoa(nz)) + + do n = 1, nz + i = indx(n) + if (i .ge. 1) then + nutc = sig(i, 2) + freq = sig(i, 3) + sync1 = sig(i, 4) + dt = sig(i, 5) + npol = nint(57.2957795*sig(i, 6)) + flip = sig(i, 7) + sync2 = sig(i, 8) + nkv = sig(i, 9) + nqual = min(sig(i, 10), 10.0) ! rms0=sig(i,11) - do k=1,5 - a(k)=sig(i,12+k) - enddo - nhist=sig(i,18) - decoded=msg(i) - - if(flip.lt.0.0) then - do i=22,1,-1 - if(decoded(i:i).ne.' ') go to 10 - enddo - stop 'Error in message format' -10 if(i.le.18) decoded(i+2:i+4)='OOO' - endif - mhz=fcenter !... +fadd ??? - nkHz=nint(freq-foffset)-nfshift - f0=mhz+0.001*nkHz - ndf=nint(1000.0*(freq-foffset-(nkHz+nfshift))) - ndf0=nint(a(1)) - ndf1=nint(a(2)) - ndf2=nint(a(3)) - nsync1=sync1 - - s2db=10.0*log10(sync2) - 40 !### empirical ### - nsync2=nint(s2db) - if(decoded(1:4).eq.'RO ' .or. decoded(1:4).eq.'RRR ' .or. & - decoded(1:4).eq.'73 ') then - nsync2=nint(1.33*s2db + 2.0) - endif - - if(nxant.ne.0) then - npol=npol-45 - if(npol.lt.0) npol=npol+180 - endif - - call txpol(xpol,decoded,mygrid,npol,nxant,ntxpol,cp) - - cmode='#A' - if(mode65.eq.2) cmode='#B' - if(mode65.eq.4) cmode='#C' - write(26,1014) f0,ndf,ndf0,ndf1,ndf2,dt,npol,nsync1, & - nsync2,nutc,decoded,'#',cp,cmode ! was decoded,cp, -1014 format(f8.3,i5,3i3,f5.1,i4,i3,i4,i5.4,4x,a22,7x,2a1,2x,a2) ! was a22,2x,a1,3x,a2 - ndecodes=ndecodes+1 - write(21,1100) f0,ndf,dt,npol,nsync2,nutc,decoded,'#',cp, & - cmode(1:1),cmode(2:2)! was decoded,cp, -1100 format(f8.3,i5,f5.1,2i4,i5.4,2x,a22,7x,2a1,3x,a1,1x,a1) ! was a22,2x,a1,1x,a1 - endif - - endif - j=j+nsiz(n) - enddo !i=1,km - - write(26,1015) nutc -1015 format(37x,i6.4,' ') - call flush(21) - call flush(26) - call display(nkeep,ftol) - ndecdone=2 - -900 close(23) - call flush(12) - ndphi=0 - mcall3b=mcall3a - - return -end subroutine map65a + do k = 1, 5 + a(k) = sig(i, 12 + k) + enddo + nhist = sig(i, 18) + decoded = msg(i) + + if (flip .lt. 0.0) then + do i = 22, 1, -1 + if (decoded(i:i) .ne. ' ') go to 10 + enddo + stop 'Error in message format' +10 if (i .le. 18) decoded(i + 2:i + 4) = 'OOO' + endif + mhz = fcenter !... +fadd ??? + nkHz = nint(freq - foffset) - nfshift + f0 = mhz + 0.001*nkHz + ndf = nint(1000.0*(freq - foffset - (nkHz + nfshift))) + ndf0 = nint(a(1)) + ndf1 = nint(a(2)) + ndf2 = nint(a(3)) + nsync1 = sync1 + + s2db = 10.0*log10(sync2) - 40 !### empirical ### + nsync2 = nint(s2db) + if (decoded(1:4) .eq. 'RO ' .or. decoded(1:4) .eq. 'RRR ' .or. & + decoded(1:4) .eq. '73 ') then + nsync2 = nint(1.33*s2db + 2.0) + endif + + if (nxant .ne. 0) then + npol = npol - 45 + if (npol .lt. 0) npol = npol + 180 + endif + + call txpol(xpol, decoded, mygrid, npol, nxant, ntxpol, cp) + + cmode = '#A' + if (mode65 .eq. 2) cmode = '#B' + if (mode65 .eq. 4) cmode = '#C' + write (26, 1014) f0, ndf, ndf0, ndf1, ndf2, dt, npol, nsync1, & + nsync2, nutc, decoded, '#', cp, cmode ! was decoded,cp, +1014 format(f8.3, i5, 3i3, f5.1, i4, i3, i4, i5.4, 4x, a22, 7x, 2a1, 2x, a2) ! was a22,2x,a1,3x,a2 + ndecodes = ndecodes + 1 + write (21, 1100) f0, ndf, dt, npol, nsync2, nutc, decoded, '#', cp, & + cmode(1:1), cmode(2:2)! was decoded,cp, +1100 format(f8.3, i5, f5.1, 2i4, i5.4, 2x, a22, 7x, 2a1, 3x, a1, 1x, a1) ! was a22,2x,a1,1x,a1 + endif + enddo + + write (26, 1015) nutc +1015 format(37x, i6.4, ' ') + flush (21) + flush (26) + call display(nkeep, ftol) + ndecdone = 2 + +900 close (23) + flush (12) + ndphi = 0 + mcall3b = mcall3a + + return + end subroutine map65a + +end module map65a_mod diff --git a/map65/libm65/mapsim.f90 b/map65/libm65/mapsim.f90 index 26933fa8..9daa21ed 100644 --- a/map65/libm65/mapsim.f90 +++ b/map65/libm65/mapsim.f90 @@ -1,51 +1,146 @@ +module dopspread_mod + implicit none +contains + + subroutine dopspread(cwave, npts, fsample, fspread) + use four2a_mod + use gran_interface + use iso_fortran_env, only: real32, real64 + implicit none + integer, intent(in) :: npts + real(real64), intent(in) :: fsample, fspread + complex(real32), intent(inout) :: cwave(npts) + + integer :: nfft, nh, i + complex(real32), allocatable :: cspread(:) + real(real32) :: twopi, df, b, f, x, a, phi1, phi2 + real(real32) :: sum, p, avep, fac + complex(real32) :: z + + nfft = npts + nh = nfft/2 + allocate(cspread(0:nfft-1)) + + twopi = 8.0*atan(1.0) + df = real(fsample,real32)/real(nfft,real32) + + cspread(0)=1.0 + cspread(nh)=0. + b=6.0 !Use truncated Lorenzian shape for fspread + do i=1,nh + f=i*df + x=b*f/fspread + z=0. + a=0. + if(x.lt.3.0) then !Cutoff beyond x=3 + a=sqrt(1.111/(1.0+x*x)-0.1) !Lorentzian amplitude + phi1=twopi*rran() !Random phase + z=a*cmplx(cos(phi1),sin(phi1)) + endif + cspread(i)=z + z=0. + if(x.lt.3.0) then !Same thing for negative freqs + phi2=twopi*rran() + z=a*cmplx(cos(phi2),sin(phi2)) + endif + cspread(nfft-i)=z + enddo + + call four2a(cspread,nfft,1,1,1) !Transform to time domain + + sum=0. + do i=0,nfft-1 + p=real(cspread(i))**2 + aimag(cspread(i))**2 + sum=sum+p + enddo + avep=sum/nfft + fac=sqrt(1.0/avep) + cspread=fac*cspread !Normalize to constant avg power + cwave=cspread*cwave !Apply Rayleigh fading + + deallocate(cspread) + return + end subroutine dopspread + +end module dopspread_mod + program mapsim ! Generate simulated data for testing of MAP65 + use iso_c_binding + use gen_q65_cwave_mod + use four2a_mod + use cgen65_mod + use noisegen_mod + use dopspread_mod + use iso_fortran_env, only: real32, real64, int16 + implicit none + + integer :: NMAX + + real(real32), allocatable :: d4(:,:) !Floating-point data + integer(int16), allocatable :: id4(:,:) !i*2 data, dual polarization + integer(int16), allocatable :: id2(:,:) !i*2 data, single polarization + complex(real32), allocatable :: cwave(:) !i*2 data, single polarization + complex(real32) z,zx,zy + real(real32) :: dt0, fa, fb, snrdb, rmsdb, rad, fac, pol, a, b, sig, snrdbx + real(real32) :: rms + real(real64) :: fcenter, fsample, twopi, phi, dphi, xphi + real(real64) :: f, dt, samfac, fdop - parameter (NMAX=60*96000) - real*4 d4(4,NMAX) !Floating-point data - integer*2 id4(4,NMAX) !i*2 data, dual polarization - integer*2 id2(2,NMAX) !i*2 data, single polarization - complex cwave(NMAX) !Generated complex waveform (no noise) - complex z,zx,zy - real*8 fcenter,fsample,samfac,f,dt,twopi,phi,dphi logical bq65 - character msg0*24,message*24,msgsent*24,arg*8,fname*11,mode*2 !w3sz msg* was size 22 - character*24 msg_list(60) ! was *16 - integer*2 hhmm + character(len=24) msg0 !w3sz msg0 was size 22 + character(len=24)message + character(len=24)msgsent + character(len=8)arg + character(len=11)fname + character(len=2)mode + character(len=24) msg_list(60) ! was *16 + integer(int16) hhmm + integer :: nargs, nsigs, npol, nfiles, isig, nmin, ifile + integer :: ntone_spacing, ntxfreq, nsendingsh, nwave, npts + integer :: ilist, i0, i, j + integer :: sRatekHz + data msg_list/ & - 'CQ K1WDG/R','CQ YL/EA8DBM','<YL/EA8DBM> OH3LWP KP11', & - 'CQ PJ4/KA1ABC','CQ KH1/KH7Z','CQ QU1RK FN20', & - '<K1WDG/P> W3SZ fn20','<PJ4/KA1ABC> WA9XYZ -10','WA9XYZ <KH1/KH7Z> -12', & - '<YW18FIFA> KA1ABC 73','CQ TEST KA1GT FN54','CQ YW18FIFA', & - 'PJ4/KA1ABC <WA9XYZ> -11','<WA9XYZ> PJ4/KA1ABC 73','<WA9XYZ> PJ4/KA1ABC RR73', & - '<YW18FIFA> KA1ABC FN42','<PJ4/KA1ABC> WA9XYZ R-09','<PJ4/KA1ABC> WA9XYZ EN90', & - 'CQ DL4KGC JN68','CQ HB9Q JN47','CQ G3LTF IO91', & - 'CQ K1JT/P FN20','CQ W3SZ/2 FN20','CQ DL3WDG JN68', & - 'CQ GM/N5L IO98','CQ 3DA0RS JJ22','CQ W7RPI/2 FN31', & - 'CQ 123 456 78','CQ DX 167 DXP','CQYDHRT 678', & + ! 'CQ K1WDG/R','CQ YL/EA8DBM','<YL/EA8DBM> OH3LWP KP11', & + ! 'CQ PJ4/KA1ABC','CQ KH1/KH7Z','CQ QU1RK FN20', & + ! '<K1WDG/P> W3SZ fn20','<PJ4/KA1ABC> WA9XYZ -10','WA9XYZ <KH1/KH7Z> -12', & + ! '<YW18FIFA> KA1ABC 73','CQ TEST KA1GT FN54','CQ YW18FIFA', & + ! 'PJ4/KA1ABC <WA9XYZ> -11','<WA9XYZ> PJ4/KA1ABC 73','<WA9XYZ> PJ4/KA1ABC RR73', & + ! '<YW18FIFA> KA1ABC FN42','<PJ4/KA1ABC> WA9XYZ R-09','<PJ4/KA1ABC> WA9XYZ EN90', & + ! 'CQ DL4KGC JN68','CQ HB9Q JN47','CQ G3LTF IO91', & + ! 'CQ K1JT/P FN20','CQ W3SZ/2 FN20','CQ DL3WDG JN68', & + ! 'CQ GM/N5L IO98','CQ 3DA0RS JJ22','CQ W7RPI/2 FN31', & + ! 'CQ 123 456 78','CQ DX 167 DXP','CQYDHRT 678', & + ! 'CQ K1JT FN20','CQ W3SZ FN10','CQ DL3WDG JN68', & + ! 'CQ DG2YCB JO42','CQ ON4AOI JO21','CQ KA1GT FN54', & + ! 'CQ DL4KGC JN68','CQ HB9Q JN47','CQ G3LTF IO91', & + 'W1AAA K2BBB EM00','W2CCC K3DDD EM01','W3EEE K4FFF EM02', & + 'W5GGG K6HHH EM03','W7III K8JJJ EM04','W9KKK K0LLL EM05', & + 'G0MMM F1NNN JN06','G2OOO F3PPP JN07','G4QQQ F5RRR JN08', & + 'G6SSS F7TTT JN09','W1XAA K2XBB EM10','W2XCC K3XDD EM11', & + 'W3XEE K4XFF EM12','W5XGG K6XHH EM13','W7XII K8XJJ EM14', & 'W9XKK K0XLL EM15','G0XMM F1XNN JN16','G2XOO F3XPP JN17', & - ! 'G4XQQ F5XRR JN18','G6XSS F7XTT JN19','W1YAA K2YBB EM20', & - ! 'W2YCC K3YDD EM21','W3YEE K4YFF EM22','W5YGG K6YHH EM23', & - ! 'W7YII K8YJJ EM24','W9YKK K0YLL EM25','G0YMM F1YNN JN26', & - ! 'G2YOO F3YPP JN27','G4YQQ F5YRR JN28','G6YSS F7YTT JN29', & - ! 'W1ZAA K2ZBB EM30','W2ZCC K3ZDD EM31','W3ZEE K4ZFF EM32', & - ! 'W5ZGG K6ZHH EM33','W7ZII K8ZJJ EM34','W9ZKK K0ZLL EM35', & - ! 'G0ZMM F1ZNN JN36','G2ZOO F3ZPP JN37','G4ZQQ F5ZRR JN38', & + 'G4XQQ F5XRR JN18','G6XSS F7XTT JN19','W1YAA K2YBB EM20', & + 'W2YCC K3YDD EM21','W3YEE K4YFF EM22','W5YGG K6YHH EM23', & + 'W7YII K8YJJ EM24','W9YKK K0YLL EM25','G0YMM F1YNN JN26', & + 'G2YOO F3YPP JN27','G4YQQ F5YRR JN28','G6YSS F7YTT JN29', & + 'W1ZAA K2ZBB EM30','W2ZCC K3ZDD EM31','W3ZEE K4ZFF EM32', & + 'W5ZGG K6ZHH EM33','W7ZII K8ZJJ EM34','W9ZKK K0ZLL EM35', & + 'G0ZMM F1ZNN JN36','G2ZOO F3ZPP JN37','G4ZQQ F5ZRR JN38', & 'G6ZSS F7ZTT JN39','W1AXA K2BXB EM40','W2CXC K3DXD EM41', & 'W3EXE K4FXF EM42','W5GXG K6HXH EM43','W7IXI K8JXJ EM44', & - 'CQ DG2YCB JO42','CQ ON4AOI JO21','CQ KA1GT FN54', & - 'G6SSS F7TTT JN09','W1XAA K2XBB EM10','W2XCC K3XDD EM11', & 'W9KXK K0LXL EM45','G0MXM F1NXN JN46','G2OXO F3PXP JN47', & 'G4QXQ F5RXR JN48','G6SXS F7TXT JN49','W1AYA K2BYB EM50', & 'W2CYC K3DYD EM51','W3EYE K4FYF EM52','W5GYG K6HYH EM53', & 'W7IYI K8JYJ EM54','W9KYK K0LYL EM55','G0MYM F1NYN JN56', & 'G2OYO F3PYP JN57','G4QYQ F5RYR JN58','G6SYS F7TYT JN59'/ - - nargs=iargc() - if(nargs.ne.12) then - print*,'Usage: mapsim "message" mode DT fa fb nsigs pol fDop SNR nfiles fcenter HHmm' - print*,'Example: mapsim "CQ K1ABC FN42" B 2.5 -20 20 21 45 0.0 -20 1 1296.1 1803' + + nargs=command_argument_count() + if(nargs.ne.13) then + print*,'Usage: mapsim "message" mode DT fa fb nsigs pol fDop SNR nfiles fcenter HHmm sRatekHz' + print*,'Example: mapsim "CQ K1ABC FN42" B 2.5 -20 20 21 45 0.0 -20 1 1296.1 1803 96' print*,' ' print*,' mode = A B C for JT65; QA-QE for Q65-60A' print*,' fa = lowest freq in kHz, relative to center' @@ -53,42 +148,58 @@ program mapsim print*,' message = "list" to use callsigns from list' print*,' pol = -1 to generate a range of polarization angles.' print*,' SNR = 0 to generate a range of SNRs.' + print*,' sRateKHz must be one of 96, 128, 192,256' go to 999 endif - call getarg(1,msg0) - call getarg(2,mode) !JT65 sub-mode (A B C QA-QE) - call getarg(3,arg) + call get_command_argument(1,msg0) + call get_command_argument(2,mode) !JT65 sub-mode (A B C QA-QE) + call get_command_argument(3,arg) read(arg,*) dt0 !Time delay - call getarg(4,arg) + call get_command_argument(4,arg) read(arg,*) fa !Lowest freq (kHz, relative to fcenter) - call getarg(5,arg) + call get_command_argument(5,arg) read(arg,*) fb !Highest freq - call getarg(6,arg) + call get_command_argument(6,arg) read(arg,*) nsigs !Number of signals in each file - call getarg(7,arg) + call get_command_argument(7,arg) read(arg,*) npol !Polarization in degrees pol=npol - call getarg(8,arg) + call get_command_argument(8,arg) read(arg,*) fdop !Doppler spread - call getarg(9,arg) + call get_command_argument(9,arg) read(arg,*) snrdb !S/N - call getarg(10,arg) + call get_command_argument(10,arg) read(arg,*) nfiles !Number of files !S/N - call getarg(11,arg) ! added by w3sz + call get_command_argument(11,arg) ! added by w3sz read(arg,*) fcenter ! added by w3sz - call getarg(12,arg) ! added by w3sz + call get_command_argument(12,arg) ! added by w3sz read(arg,*) hhmm ! added by w3sz + call get_command_argument(13,arg) ! added by w3sz + read(arg,*) sRatekHz ! added by w3sz + + if (sRatekHz /= 96 .and. sRatekHz /= 128 .and. sRatekHz /= 192 .and. sRatekHz /= 256) then + write(*,*) 'ERROR: Invalid sample rate ', sRatekHz, ' kHz' + write(*,*) 'Allowed sample rates are: 96, 128, 192, 256 kHz' + stop + endif + + fsample = 1000.d0 * sRatekHz + dt = 1.d0 / fsample + NMAX = 60 * sRatekHz * 1000 + npts = NMAX + allocate(d4(4, NMAX)) + allocate(id4(4,NMAX)) + allocate(id2(2,NMAX)) + allocate(cwave(NMAX)) message=msg0 !Transmitted message rmsdb=25. rms=10.0**(0.05*rmsdb) ! w3sz fcenter=144.125d0 !Center frequency (MHz) - fsample=96000.d0 !Sample rate (Hz) - dt=1.d0/fsample !Sample interval (s) twopi=8.d0*atan(1.d0) rad=360.0/twopi - samfac=1.d0 + samfac = fsample / 96000.d0 bq65=(mode(1:1).eq.'Q') ntone_spacing=1 ntxfreq=1270 @@ -97,7 +208,7 @@ program mapsim if(mode(1:1).eq.'C' .or. mode(2:2).eq.'C') ntone_spacing=4 if(mode(2:2).eq.'D') ntone_spacing=8 if(mode(2:2).eq.'E') ntone_spacing=16 - npts=NMAX + nsendingsh=0 ! Initialize nsendingsh (was implicit?) write(*,1000) 1000 format('File N Mode DT freq pol fDop SNR Message'/68('-')) @@ -106,37 +217,24 @@ program mapsim ilist=0 nmin=ifile-1 if(mode(2:2).eq.' ') nmin=2*nmin - write(fname,1002) hhmm !Create the output filenames ! w3sz was nmin -1002 format('000000_',i4.4) - open(10,file=fname//'.iq',access='stream',status='unknown') - open(11,file=fname//'.tf2',access='stream',status='unknown') + write(fname, '(I6.6, "_", I4.4)') ifile, hhmm !Create the output filenames ! w3sz was nmin + open(10,file=fname//'.iq',access='stream',status='replace') + open(11,file=fname//'.tf2',access='stream',status='replace') call noisegen(d4,npts) !Generate Gaussuian noise if(msg0(1:4).ne.'list') then - if(bq65) then - call gen_q65_cwave(message,ntxfreq,ntone_spacing,msgsent, & - cwave,nwave) - else - call cgen65(message,ntone_spacing,samfac,nsendingsh,msgsent, & - cwave,nwave) - endif + call generate_cwave(message,msgsent,cwave,nwave) endif - if(fdop.gt.0.0) call dopspread(cwave,fdop) + if(fdop.gt.0.0) call dopspread(cwave,npts,fsample,fdop) do isig=1,nsigs if(msg0(1:4).eq.'list') then ilist=ilist+1 message=msg_list(ilist) - if(bq65) then - call gen_q65_cwave(message,ntxfreq,ntone_spacing,msgsent, & - cwave,nwave) - else - call cgen65(message,ntone_spacing,samfac,nsendingsh,msgsent, & - cwave,nwave) - endif + call generate_cwave(message,msgsent,cwave,nwave) endif if(npol.lt.0) pol=(isig-1)*180.0/nsigs @@ -148,7 +246,7 @@ program mapsim snrdbx=snrdb if(snrdb.eq.0.0) snrdbx=-15.0 - 15.0*(isig-1.0)/nsigs - sig=sqrt(2.2*2500.0/96000.0) * 10.0**(0.05*snrdbx) + sig = sqrt(2.2*2500.0/fsample) * 10.0**(0.05*snrdbx) write(*,1020) ifile,isig,mode,dt0,0.001*f,nint(pol),fDop,snrdbx,msgsent 1020 format(i3,i3,2x,a2,f6.2,f8.3,i5,2f7.1,2x,a24) !w3sz was a22 @@ -160,7 +258,8 @@ program mapsim if(phi.lt.-twopi) phi=phi+twopi if(phi.gt.twopi) phi=phi-twopi xphi=phi - z=sig*cwave(i)*cmplx(cos(xphi),-sin(xphi)) + z = sig * cwave(i) * cmplx( real(cos(xphi),kind=real32), & + real(-sin(xphi),kind=real32), kind=real32 ) zx=a*z zy=b*z j=i+i0 @@ -180,62 +279,38 @@ program mapsim id2(2,i)=id4(2,i) enddo + write(*,*) 'DEBUG: fsample =', fsample, ' sRatekHz =', sRatekHz, & + ' NMAX =', NMAX, ' npts =', npts + write(10) fcenter,id2(1:2,1:npts) write(11) fcenter,id4(1:4,1:npts) close(10) close(11) enddo -999 end program mapsim - -subroutine dopspread(cwave,fspread) - - parameter (NMAX=60*96000) - parameter (NFFT=NMAX,NH=NFFT/2) - complex cwave(NMAX) - complex cspread(0:NMAX-1) - - twopi=8.0*atan(1.0) - df=96000.0/nfft - cspread(0)=1.0 - cspread(NH)=0. - b=6.0 !Use truncated Lorenzian shape for fspread - do i=1,NH - f=i*df - x=b*f/fspread - z=0. - a=0. - if(x.lt.3.0) then !Cutoff beyond x=3 - a=sqrt(1.111/(1.0+x*x)-0.1) !Lorentzian amplitude - phi1=twopi*rran() !Random phase - z=a*cmplx(cos(phi1),sin(phi1)) - endif - cspread(i)=z - z=0. - if(x.lt.3.0) then !Same thing for negative freqs - phi2=twopi*rran() - z=a*cmplx(cos(phi2),sin(phi2)) - endif - cspread(nfft-i)=z - enddo + deallocate(d4) + deallocate(id4) + deallocate(id2) + deallocate(cwave) - call four2a(cspread,nfft,1,1,1) !Transform to time domain +999 continue +contains - sum=0. - do i=0,nfft-1 - p=real(cspread(i))**2 + aimag(cspread(i))**2 - sum=sum+p - enddo - avep=sum/nfft - fac=sqrt(1.0/avep) - cspread=fac*cspread !Normalize to constant avg power - cwave=cspread*cwave !Apply Rayleigh fading - -! do i=0,nfft-1 -! p=real(cspread(i))**2 + aimag(cspread(i))**2 -! write(14,3010) i,p,cspread(i) -!3010 format(i8,3f12.6) -! enddo - - return -end subroutine dopspread + subroutine generate_cwave(message,msgsent,cwave,nwave) + character(len=*),intent(inout) :: message + character(len=*),intent(out) :: msgsent + complex, intent(out) :: cwave(:) + integer, intent(out) :: nwave + + ! cgen65 defines only 22 characters; blank-fill so the a24 output is fully defined + msgsent = ' ' + if(bq65) then + call gen_q65_cwave(message,ntxfreq,ntone_spacing,fsample,msgsent, & + cwave,nwave) + else + call cgen65(message,ntone_spacing,samfac,nsendingsh,msgsent, & + cwave,nwave) + endif + end subroutine generate_cwave + +end program mapsim diff --git a/map65/libm65/moon2.f90 b/map65/libm65/moon2.f90 index 9fa72f1d..1bedd746 100644 --- a/map65/libm65/moon2.f90 +++ b/map65/libm65/moon2.f90 @@ -1,163 +1,169 @@ -subroutine moon2(y,m,Day,UT,lon,lat,RA,Dec,topRA,topDec,LST,HA,Az,El,dist) - +module moon2_mod + use iso_fortran_env, only: real64 implicit none - - integer y !Year - integer m !Month - integer Day !Day - real*8 UT !UTC in hours - real*8 RA,Dec !RA and Dec of moon - -! NB: Double caps are single caps in the writeup. - - real*8 NN !Longitude of ascending node - real*8 i !Inclination to the ecliptic - real*8 w !Argument of perigee - real*8 a !Semi-major axis - real*8 e !Eccentricity - real*8 MM !Mean anomaly - - real*8 v !True anomaly - real*8 EE !Eccentric anomaly - real*8 ecl !Obliquity of the ecliptic - - real*8 d !Ephemeris time argument in days - real*8 r !Distance to sun, AU - real*8 xv,yv !x and y coords in ecliptic - real*8 lonecl,latecl !Ecliptic long and lat of moon - real*8 xg,yg,zg !Ecliptic rectangular coords - real*8 Ms !Mean anomaly of sun - real*8 ws !Argument of perihelion of sun - real*8 Ls !Mean longitude of sun (Ns=0) - real*8 Lm !Mean longitude of moon - real*8 DD !Mean elongation of moon - real*8 FF !Argument of latitude for moon - real*8 xe,ye,ze !Equatorial geocentric coords of moon - real*8 mpar !Parallax of moon (r_E / d) - real*8 lat,lon !Station coordinates on earth - real*8 gclat !Geocentric latitude - real*8 rho !Earth radius factor - real*8 GMST0,LST,HA - real*8 g - real*8 topRA,topDec !Topocentric coordinates of Moon - real*8 Az,El - real*8 dist - - real*8 rad,twopi,pi,pio2 - data rad/57.2957795131d0/,twopi/6.283185307d0/ - - d=367*y - 7*(y+(m+9)/12)/4 + 275*m/9 + Day - 730530 + UT/24.d0 - ecl = 23.4393d0 - 3.563d-7 * d - -! Orbital elements for Moon: - NN = 125.1228d0 - 0.0529538083d0 * d - i = 5.1454d0 - w = mod(318.0634d0 + 0.1643573223d0 * d + 360000.d0,360.d0) - a = 60.2666d0 - e = 0.054900d0 - MM = mod(115.3654d0 + 13.0649929509d0 * d + 360000.d0,360.d0) - - EE = MM + e*rad*sin(MM/rad) * (1.d0 + e*cos(MM/rad)) - EE = EE - (EE - e*rad*sin(EE/rad)-MM) / (1.d0 - e*cos(EE/rad)) - EE = EE - (EE - e*rad*sin(EE/rad)-MM) / (1.d0 - e*cos(EE/rad)) - - xv = a * (cos(EE/rad) - e) - yv = a * (sqrt(1.d0-e*e) * sin(EE/rad)) - - v = mod(rad*atan2(yv,xv)+720.d0,360.d0) - r = sqrt(xv*xv + yv*yv) - -! Get geocentric position in ecliptic rectangular coordinates: - - xg = r * (cos(NN/rad)*cos((v+w)/rad)-sin(NN/rad)*sin((v+w)/rad)*cos(i/rad)) - yg = r * (sin(NN/rad)*cos((v+w)/rad)+cos(NN/rad)*sin((v+w)/rad)*cos(i/rad)) - zg = r * (sin((v+w)/rad)*sin(i/rad)) - -! Ecliptic longitude and latitude of moon: - lonecl = mod(rad*atan2(yg/rad,xg/rad)+720.d0,360.d0) - latecl = rad*atan2(zg/rad,sqrt(xg*xg + yg*yg)/rad) - -! Now include orbital perturbations: - Ms = mod(356.0470d0 + 0.9856002585d0 * d + 3600000.d0,360.d0) - ws = 282.9404d0 + 4.70935d-5*d - Ls = mod(Ms + ws + 720.d0,360.d0) - Lm = mod(MM + w + NN+720.d0,360.d0) - DD = mod(Lm - Ls + 360.d0,360.d0) - FF = mod(Lm - NN + 360.d0,360.d0) - - lonecl = lonecl & - - 1.274d0 * sin((MM-2.d0*DD)/rad) & - + 0.658d0 * sin(2.d0*DD/rad) & - - 0.186d0 * sin(Ms/rad) & - - 0.059d0 * sin((2.d0*MM-2.d0*DD)/rad) & - - 0.057d0 * sin((MM-2.d0*DD+Ms)/rad) & - + 0.053d0 * sin((MM+2.d0*DD)/rad) & - + 0.046d0 * sin((2.d0*DD-Ms)/rad) & - + 0.041d0 * sin((MM-Ms)/rad) & - - 0.035d0 * sin(DD/rad) & - - 0.031d0 * sin((MM+Ms)/rad) & - - 0.015d0 * sin((2.d0*FF-2.d0*DD)/rad) & - + 0.011d0 * sin((MM-4.d0*DD)/rad) - - latecl = latecl & - - 0.173d0 * sin((FF-2.d0*DD)/rad) & - - 0.055d0 * sin((MM-FF-2.d0*DD)/rad) & - - 0.046d0 * sin((MM+FF-2.d0*DD)/rad) & - + 0.033d0 * sin((FF+2.d0*DD)/rad) & - + 0.017d0 * sin((2.d0*MM+FF)/rad) - - r = 60.36298d0 & - - 3.27746d0*cos(MM/rad) & - - 0.57994d0*cos((MM-2.d0*DD)/rad) & - - 0.46357d0*cos(2.d0*DD/rad) & - - 0.08904d0*cos(2.d0*MM/rad) & - + 0.03865d0*cos((2.d0*MM-2.d0*DD)/rad) & - - 0.03237d0*cos((2.d0*DD-Ms)/rad) & - - 0.02688d0*cos((MM+2.d0*DD)/rad) & - - 0.02358d0*cos((MM-2.d0*DD+Ms)/rad) & - - 0.02030d0*cos((MM-Ms)/rad) & - + 0.01719d0*cos(DD/rad) & - + 0.01671d0*cos((MM+Ms)/rad) - - dist=r*6378.140d0 - -! Geocentric coordinates: -! Rectangular ecliptic coordinates of the moon: - - xg = r * cos(lonecl/rad)*cos(latecl/rad) - yg = r * sin(lonecl/rad)*cos(latecl/rad) - zg = r * sin(latecl/rad) - -! Rectangular equatorial coordinates of the moon: - xe = xg - ye = yg*cos(ecl/rad) - zg*sin(ecl/rad) - ze = yg*sin(ecl/rad) + zg*cos(ecl/rad) - -! Right Ascension, Declination: - RA = mod(rad*atan2(ye,xe)+360.d0,360.d0) - Dec = rad*atan2(ze,sqrt(xe*xe + ye*ye)) - -! Now convert to topocentric system: - mpar=rad*asin(1.d0/r) -! alt_topoc = alt_geoc - mpar*cos(alt_geoc) - gclat = lat - 0.1924d0*sin(2.d0*lat/rad) - rho = 0.99883d0 + 0.00167d0*cos(2.d0*lat/rad) - GMST0 = (Ls + 180.d0)/15.d0 - LST = mod(GMST0+UT+lon/15.d0+48.d0,24.d0) !LST in hours - HA = 15.d0*LST - RA !HA in degrees - g = rad*atan(tan(gclat/rad)/cos(HA/rad)) - topRA = RA - mpar*rho*cos(gclat/rad)*sin(HA/rad)/cos(Dec/rad) - topDec = Dec - mpar*rho*sin(gclat/rad)*sin((g-Dec)/rad)/sin(g/rad) - - HA = 15.d0*LST - topRA !HA in degrees - if(HA.gt.180.d0) HA=HA-360.d0 - if(HA.lt.-180.d0) HA=HA+360.d0 - - pi=0.5d0*twopi - pio2=0.5d0*pi - call dcoord(pi,pio2-lat/rad,0.d0,lat/rad,ha*twopi/360,topDec/rad,az,el) - Az=az*rad - El=El*rad - - return -end subroutine moon2 +contains + subroutine moon2(y,m,Day,UT,lon,lat,RA,Dec,topRA,topDec,LST,HA,Az,El,dist) + + use dcoord_mod + implicit none + + integer, intent(in) :: y !Year + integer, intent(in) :: m !Month + integer, intent(in) :: Day !Day + real(real64), intent(in) :: UT !UTC in hours + real(real64), intent(out) :: RA,Dec !RA and Dec of moon + real(real64), intent(in) :: lat,lon !Station coordinates on earth + real(real64), intent(out) :: topRA,topDec !Topocentric coordinates of Moon + real(real64), intent(out) :: LST,HA + real(real64), intent(out) :: Az,El + real(real64), intent(out) :: dist + + ! NB: Double caps are single caps in the writeup. + + real(real64) NN !Longitude of ascending node + real(real64) i !Inclination to the ecliptic + real(real64) w !Argument of perigee + real(real64) a !Semi-major axis + real(real64) e !Eccentricity + real(real64) MM !Mean anomaly + + real(real64) v !True anomaly + real(real64) EE !Eccentric anomaly + real(real64) ecl !Obliquity of the ecliptic + + real(real64) d !Ephemeris time argument in days + real(real64) r !Distance to sun, AU + real(real64) xv,yv !x and y coords in ecliptic + real(real64) lonecl,latecl !Ecliptic long and lat of moon + real(real64) xg,yg,zg !Ecliptic rectangular coords + real(real64) Ms !Mean anomaly of sun + real(real64) ws !Argument of perihelion of sun + real(real64) Ls !Mean longitude of sun (Ns=0) + real(real64) Lm !Mean longitude of moon + real(real64) DD !Mean elongation of moon + real(real64) FF !Argument of latitude for moon + real(real64) xe,ye,ze !Equatorial geocentric coords of moon + real(real64) mpar !Parallax of moon (r_E / d) + real(real64) gclat !Geocentric latitude + real(real64) rho !Earth radius factor + real(real64) GMST0 + real(real64) g + + real(real64) rad,twopi,pi,pio2 + data rad/57.2957795131d0/,twopi/6.283185307d0/ + + d=367*y - 7*(y+(m+9)/12)/4 + 275*m/9 + Day - 730530 + UT/24.d0 + ecl = 23.4393d0 - 3.563d-7 * d + + ! Orbital elements for Moon: + NN = 125.1228d0 - 0.0529538083d0 * d + i = 5.1454d0 + w = mod(318.0634d0 + 0.1643573223d0 * d + 360000.d0,360.d0) + a = 60.2666d0 + e = 0.054900d0 + MM = mod(115.3654d0 + 13.0649929509d0 * d + 360000.d0,360.d0) + + EE = MM + e*rad*sin(MM/rad) * (1.d0 + e*cos(MM/rad)) + EE = EE - (EE - e*rad*sin(EE/rad)-MM) / (1.d0 - e*cos(EE/rad)) + EE = EE - (EE - e*rad*sin(EE/rad)-MM) / (1.d0 - e*cos(EE/rad)) + + xv = a * (cos(EE/rad) - e) + yv = a * (sqrt(1.d0-e*e) * sin(EE/rad)) + + v = mod(rad*atan2(yv,xv)+720.d0,360.d0) + r = sqrt(xv*xv + yv*yv) + + ! Get geocentric position in ecliptic rectangular coordinates: + + xg = r * (cos(NN/rad)*cos((v+w)/rad)-sin(NN/rad)*sin((v+w)/rad)*cos(i/rad)) + yg = r * (sin(NN/rad)*cos((v+w)/rad)+cos(NN/rad)*sin((v+w)/rad)*cos(i/rad)) + zg = r * (sin((v+w)/rad)*sin(i/rad)) + + ! Ecliptic longitude and latitude of moon: + lonecl = mod(rad*atan2(yg/rad,xg/rad)+720.d0,360.d0) + latecl = rad*atan2(zg/rad,sqrt(xg*xg + yg*yg)/rad) + + ! Now include orbital perturbations: + Ms = mod(356.0470d0 + 0.9856002585d0 * d + 3600000.d0,360.d0) + ws = 282.9404d0 + 4.70935d-5*d + Ls = mod(Ms + ws + 720.d0,360.d0) + Lm = mod(MM + w + NN+720.d0,360.d0) + DD = mod(Lm - Ls + 360.d0,360.d0) + FF = mod(Lm - NN + 360.d0,360.d0) + + lonecl = lonecl & + - 1.274d0 * sin((MM-2.d0*DD)/rad) & + + 0.658d0 * sin(2.d0*DD/rad) & + - 0.186d0 * sin(Ms/rad) & + - 0.059d0 * sin((2.d0*MM-2.d0*DD)/rad) & + - 0.057d0 * sin((MM-2.d0*DD+Ms)/rad) & + + 0.053d0 * sin((MM+2.d0*DD)/rad) & + + 0.046d0 * sin((2.d0*DD-Ms)/rad) & + + 0.041d0 * sin((MM-Ms)/rad) & + - 0.035d0 * sin(DD/rad) & + - 0.031d0 * sin((MM+Ms)/rad) & + - 0.015d0 * sin((2.d0*FF-2.d0*DD)/rad) & + + 0.011d0 * sin((MM-4.d0*DD)/rad) + + latecl = latecl & + - 0.173d0 * sin((FF-2.d0*DD)/rad) & + - 0.055d0 * sin((MM-FF-2.d0*DD)/rad) & + - 0.046d0 * sin((MM+FF-2.d0*DD)/rad) & + + 0.033d0 * sin((FF+2.d0*DD)/rad) & + + 0.017d0 * sin((2.d0*MM+FF)/rad) + + r = 60.36298d0 & + - 3.27746d0*cos(MM/rad) & + - 0.57994d0*cos((MM-2.d0*DD)/rad) & + - 0.46357d0*cos(2.d0*DD/rad) & + - 0.08904d0*cos(2.d0*MM/rad) & + + 0.03865d0*cos((2.d0*MM-2.d0*DD)/rad) & + - 0.03237d0*cos((2.d0*DD-Ms)/rad) & + - 0.02688d0*cos((MM+2.d0*DD)/rad) & + - 0.02358d0*cos((MM-2.d0*DD+Ms)/rad) & + - 0.02030d0*cos((MM-Ms)/rad) & + + 0.01719d0*cos(DD/rad) & + + 0.01671d0*cos((MM+Ms)/rad) + + dist=r*6378.140d0 + + ! Geocentric coordinates: + ! Rectangular ecliptic coordinates of the moon: + + xg = r * cos(lonecl/rad)*cos(latecl/rad) + yg = r * sin(lonecl/rad)*cos(latecl/rad) + zg = r * sin(latecl/rad) + + ! Rectangular equatorial coordinates of the moon: + xe = xg + ye = yg*cos(ecl/rad) - zg*sin(ecl/rad) + ze = yg*sin(ecl/rad) + zg*cos(ecl/rad) + + ! Right Ascension, Declination: + RA = mod(rad*atan2(ye,xe)+360.d0,360.d0) + Dec = rad*atan2(ze,sqrt(xe*xe + ye*ye)) + + ! Now convert to topocentric system: + mpar=rad*asin(1.d0/r) + ! alt_topoc = alt_geoc - mpar*cos(alt_geoc) + gclat = lat - 0.1924d0*sin(2.d0*lat/rad) + rho = 0.99883d0 + 0.00167d0*cos(2.d0*lat/rad) + GMST0 = (Ls + 180.d0)/15.d0 + LST = mod(GMST0+UT+lon/15.d0+48.d0,24.d0) !LST in hours + HA = 15.d0*LST - RA !HA in degrees + g = rad*atan(tan(gclat/rad)/cos(HA/rad)) + topRA = RA - mpar*rho*cos(gclat/rad)*sin(HA/rad)/cos(Dec/rad) + topDec = Dec - mpar*rho*sin(gclat/rad)*sin((g-Dec)/rad)/sin(g/rad) + + HA = 15.d0*LST - topRA !HA in degrees + if(HA.gt.180.d0) HA=HA-360.d0 + if(HA.lt.-180.d0) HA=HA+360.d0 + + pi=0.5d0*twopi + pio2=0.5d0*pi + call dcoord(pi,pio2-lat/rad,0.d0,lat/rad,ha*twopi/360,topDec/rad,az,el) + Az=az*rad + El=El*rad + + end subroutine moon2 +end module moon2_mod diff --git a/map65/libm65/moondop.f90 b/map65/libm65/moondop.f90 index 096c3128..03b81d27 100644 --- a/map65/libm65/moondop.f90 +++ b/map65/libm65/moondop.f90 @@ -1,72 +1,89 @@ -subroutine MoonDop(nyear,month,nday,uth4,lon4,lat4,RAMoon4,DecMoon4, & - LST4,HA4,AzMoon4,ElMoon4,vr4,dist4) +module moondop_mod + implicit none +contains + subroutine MoonDop(nyear,month,nday,uth4,lon4,lat4,RAMoon4,DecMoon4, & + LST4,HA4,AzMoon4,ElMoon4,vr4,dist4) + + use dot_mod + use geocentric_mod + use moon2_mod + use toxyz_mod + use gran_interface + use iso_fortran_env, only: real32, real64 + implicit none - implicit real*8 (a-h,o-z) - real*4 uth4 !UT in hours - real*4 lon4 !West longitude, degrees - real*4 lat4 !Latitude, degrees - real*4 RAMoon4 !Topocentric RA of moon, hours - real*4 DecMoon4 !Topocentric Dec of Moon, degrees - real*4 LST4 !Locat sidereal time, hours - real*4 HA4 !Local Hour angle, degrees - real*4 AzMoon4 !Topocentric Azimuth of moon, degrees - real*4 ElMoon4 !Topocentric Elevation of moon, degrees - real*4 vr4 !Radial velocity of moon wrt obs, km/s - real*4 dist4 !Echo time, seconds - - real*8 LST - real*8 RME(6) !Vector from Earth center to Moon - real*8 RAE(6) !Vector from Earth center to Obs - real*8 RMA(6) !Vector from Obs to Moon - real*8 rme0(6) - logical km - - data rad/57.2957795130823d0/,twopi/6.28310530717959d0/ - - km=.true. - dlat=lat4/rad - dlong1=lon4/rad - elev1=200.d0 - call geocentric(dlat,elev1,dlat1,erad1) - - dt=100.d0 !For numerical derivative, in seconds - UT=uth4 - -! NB: geodetic latitude used here, but geocentric latitude used when -! determining Earth-rotation contribution to Doppler. - - call moon2(nyear,month,nDay,UT-dt/3600.d0,dlong1*rad,dlat*rad, & - RA,Dec,topRA,topDec,LST,HA,Az0,El0,dist) - call toxyz(RA/rad,Dec/rad,dist,rme0) !Convert to rectangular coords - - call moon2(nyear,month,nDay,UT,dlong1*rad,dlat*rad, & - RA,Dec,topRA,topDec,LST,HA,Az,El,dist) - call toxyz(RA/rad,Dec/rad,dist,rme) !Convert to rectangular coords - - phi=LST*twopi/24.d0 - call toxyz(phi,dlat1,erad1,rae) !Gencentric numbers used here! - radps=twopi/(86400.d0/1.002737909d0) - rae(4)=-rae(2)*radps !Vel of Obs wrt Earth center - rae(5)=rae(1)*radps - rae(6)=0.d0 - - do i=1,3 - rme(i+3)=(rme(i)-rme0(i))/dt - rma(i)=rme(i)-rae(i) - rma(i+3)=rme(i+3)-rae(i+3) - enddo - - call fromxyz(rma,alpha1,delta1,dtopo0) !Get topocentric coords - vr=dot(rma(4),rma)/dtopo0 - - RAMoon4=topRA - DecMoon4=topDec - LST4=LST - HA4=HA - AzMoon4=Az - ElMoon4=El - vr4=vr - dist4=dist - - return -end subroutine MoonDop + integer, intent(in) :: nyear, month, nday + real(real32), intent(in) :: uth4 !UT in hours + real(real32), intent(in) :: lon4 !West longitude, degrees + real(real32), intent(in) :: lat4 !Latitude, degrees + real(real32), intent(out) :: RAMoon4 !Topocentric RA of moon, hours + real(real32), intent(out) :: DecMoon4 !Topocentric Dec of Moon, degrees + real(real32), intent(out) :: LST4 !Locat sidereal time, hours + real(real32), intent(out) :: HA4 !Local Hour angle, degrees + real(real32), intent(out) :: AzMoon4 !Topocentric Azimuth of moon, degrees + real(real32), intent(out) :: ElMoon4 !Topocentric Elevation of moon, degrees + real(real32), intent(out) :: vr4 !Radial velocity of moon wrt obs, km/s + real(real32), intent(out) :: dist4 !Echo time, seconds + + real(real64) LST + real(real64) RME(6) !Vector from Earth center to Moon + real(real64) RAE(6) !Vector from Earth center to Obs + real(real64) RMA(6) !Vector from Obs to Moon + real(real64) rme0(6) + logical km + real(real64) :: dlat, dlong1, elev1, dlat1, erad1, dt, UT, RA, Dec, topRA + real(real64) :: topDec, HA, Az0, El0, Az, El, dist + real(real64) :: phi, radps, alpha1, delta1, dtopo0, vr + integer :: i + real(real64) :: rad, twopi + + data rad/57.2957795130823d0/,twopi/6.28318530717959d0/ + + km=.true. + dlat=lat4/rad + dlong1=lon4/rad + elev1=200.d0 + call geocentric(dlat,elev1,dlat1,erad1) + + dt=100.d0 !For numerical derivative, in seconds + UT=uth4 + + ! NB: geodetic latitude used here, but geocentric latitude used when + ! determining Earth-rotation contribution to Doppler. + + call moon2(nyear,month,nDay,UT-dt/3600.d0,dlong1*rad,dlat*rad, & + RA,Dec,topRA,topDec,LST,HA,Az0,El0,dist) + call toxyz(RA/rad,Dec/rad,dist,rme0) !Convert to rectangular coords + + call moon2(nyear,month,nDay,UT,dlong1*rad,dlat*rad, & + RA,Dec,topRA,topDec,LST,HA,Az,El,dist) + call toxyz(RA/rad,Dec/rad,dist,rme) !Convert to rectangular coords + + phi=LST*twopi/24.d0 + call toxyz(phi,dlat1,erad1,rae) !Gencentric numbers used here! + radps=twopi/(86400.d0/1.002737909d0) + rae(4)=-rae(2)*radps !Vel of Obs wrt Earth center + rae(5)=rae(1)*radps + rae(6)=0.d0 + + do i=1,3 + rme(i+3)=(rme(i)-rme0(i))/dt + rma(i)=rme(i)-rae(i) + rma(i+3)=rme(i+3)-rae(i+3) + enddo + + call fromxyz(rma,alpha1,delta1,dtopo0) !Get topocentric coords + vr=dot(rma(4),rma)/dtopo0 + + RAMoon4=topRA + DecMoon4=topDec + LST4=LST + HA4=HA + AzMoon4=Az + ElMoon4=El + vr4=vr + dist4=dist + + return + end subroutine MoonDop +end module moondop_mod diff --git a/map65/libm65/nchar.f90 b/map65/libm65/nchar.f90 index 21593bd1..5f8688f0 100644 --- a/map65/libm65/nchar.f90 +++ b/map65/libm65/nchar.f90 @@ -1,23 +1,25 @@ -function nchar(c) +module nchar_mod + implicit none +contains + integer function nchar(c) + implicit none + character, intent(in) :: c + integer :: n -! Convert ascii number, letter, or space to 0-36 for callsign packing. - - character c*1 - - n=0 !Silence compiler warning - if(c.ge.'0' .and. c.le.'9') then - n=ichar(c)-ichar('0') - else if(c.ge.'A' .and. c.le.'Z') then - n=ichar(c)-ichar('A') + 10 - else if(c.ge.'a' .and. c.le.'z') then - n=ichar(c)-ichar('a') + 10 - else if(c.ge.' ') then - n=36 - else - Print*,'Invalid character in callsign ',c,' ',ichar(c) - call exit(1) - endif - nchar=n - - return -end function nchar + n=0 !Silence compiler warning + if(c.ge.'0' .and. c.le.'9') then + n=ichar(c)-ichar('0') + else if(c.ge.'A' .and. c.le.'Z') then + n=ichar(c)-ichar('A') + 10 + else if(c.ge.'a' .and. c.le.'z') then + n=ichar(c)-ichar('a') + 10 + else if(c.ge.' ') then + n=36 + else + ! TODO: Return an invalid status instead of terminating MAP65. + ! Print*,'Invalid character in callsign ',c,' ',ichar(c) + stop 1 + endif + nchar=n + end function nchar +end module nchar_mod diff --git a/map65/libm65/njunk.f90 b/map65/libm65/njunk.f90 deleted file mode 100644 index 319fb5ab..00000000 --- a/map65/libm65/njunk.f90 +++ /dev/null @@ -1 +0,0 @@ - parameter(NJUNK=40) diff --git a/map65/libm65/noisegen.f90 b/map65/libm65/noisegen.f90 index 65d94316..1c2b19de 100644 --- a/map65/libm65/noisegen.f90 +++ b/map65/libm65/noisegen.f90 @@ -1,13 +1,22 @@ -subroutine noisegen(d4,nmax) - - real*4 d4(4,nmax) - - do i=1,nmax - d4(1,i)=gran() - d4(2,i)=gran() - d4(3,i)=gran() - d4(4,i)=gran() - enddo - - return -end subroutine noisegen +module noisegen_mod + implicit none +contains + subroutine noisegen(d4,nmax) + use iso_c_binding, only: c_ptr, c_loc, c_float + use gran_interface + use iso_fortran_env, only: real32 + implicit none + + integer, intent(in) :: nmax + real(real32), intent(out) :: d4(4,nmax) + integer :: i + + do i=1,nmax + d4(1,i)=gran() + d4(2,i)=gran() + d4(3,i)=gran() + d4(4,i)=gran() + enddo + + end subroutine noisegen +end module noisegen_mod diff --git a/map65/libm65/npar_ptrs_mod.f90 b/map65/libm65/npar_ptrs_mod.f90 new file mode 100644 index 00000000..f33a92fc --- /dev/null +++ b/map65/libm65/npar_ptrs_mod.f90 @@ -0,0 +1,817 @@ +module npar_ptrs_mod + use iso_c_binding + implicit none + + type :: decode_parameters + real(c_double) :: fcenter = 0 + real(c_double) :: ftol_nb = 0 + integer(c_int) :: nfa = 0 + integer(c_int) :: nfb = 0 + integer(c_int) :: nfshift = 0 + integer(c_int) :: nfcal = 0 + integer(c_int) :: nutc = 0 + integer(c_int) :: idphi = 0 + integer(c_int) :: mousedf = 0 + integer(c_int) :: mousefqso = 0 + integer(c_int) :: nagain = 0 + integer(c_int) :: ndepth = 0 + integer(c_int) :: ndiskdat = 0 + integer(c_int) :: neme = 0 + integer(c_int) :: newdat = 0 + integer(c_int) :: map65RxLog = 0 + integer(c_int) :: mcall3 = 0 + integer(c_int) :: ntimeout = 0 + integer(c_int) :: ntol = 0 + integer(c_int) :: nxant = 0 + integer(c_int) :: nfsample = 0 + integer(c_int) :: nxpol = 0 + integer(c_int) :: nmode = 0 + integer(c_int) :: nsave = 0 + integer(c_int) :: max_drift = 0 + integer(c_int) :: nhsym = 0 + integer(c_int) :: ndop00 = 0 + integer(c_int) :: nrxlog = 0 + integer(c_int) :: nkeep = 0 + integer(c_int) :: manualDecodeFlag = 0 + character(len=12) :: mycall = '' + character(len=12) :: hiscall = '' + character(len=6) :: mygrid = '' + character(len=6) :: hisgrid = '' + character(len=20) :: datetime = '' + end type + + ! GUI setters prepare draft; only the decoder changes active after claiming a request. + type(decode_parameters), target, save :: active + type(decode_parameters), save :: draft + type :: decode_request + type(decode_parameters) :: parameters + integer(c_int64_t) :: id + integer(c_int64_t) :: input_generation + type(decode_request), pointer :: next => null() + end type + type(decode_request), pointer, save :: pending_head => null(), pending_tail => null() + integer(c_int64_t), save :: published_request_id = 0 + integer(c_int64_t), save :: active_request_id = 0 + integer(c_int64_t), save :: live_input_generation = 0 + integer(c_int64_t), save :: active_input_generation = 0 + logical, save :: active_request_expired = .false. + + real(c_double), pointer :: fcenter => active%fcenter + real(c_double), pointer :: ftol_nb => active%ftol_nb + integer(c_int), pointer :: nfa => active%nfa + integer(c_int), pointer :: nfb => active%nfb + integer(c_int), pointer :: nfshift => active%nfshift + integer(c_int), pointer :: nfcal => active%nfcal + integer(c_int), pointer :: nutc => active%nutc + integer(c_int), pointer :: idphi => active%idphi + integer(c_int), pointer :: mousedf => active%mousedf + integer(c_int), pointer :: mousefqso => active%mousefqso + integer(c_int), pointer :: nagain => active%nagain + integer(c_int), pointer :: ndepth => active%ndepth + integer(c_int), pointer :: ndiskdat => active%ndiskdat + integer(c_int), pointer :: neme => active%neme + integer(c_int), pointer :: newdat => active%newdat + integer(c_int), pointer :: map65RxLog => active%map65RxLog + integer(c_int), pointer :: mcall3 => active%mcall3 + integer(c_int), pointer :: ntimeout => active%ntimeout + integer(c_int), pointer :: ntol => active%ntol + integer(c_int), pointer :: nxant => active%nxant + integer(c_int), pointer :: nfsample => active%nfsample + integer(c_int), pointer :: nxpol => active%nxpol + integer(c_int), pointer :: nmode => active%nmode + integer(c_int), pointer :: nsave => active%nsave + integer(c_int), pointer :: max_drift => active%max_drift + integer(c_int), pointer :: nhsym => active%nhsym + integer(c_int), pointer :: ndop00 => active%ndop00 + integer(c_int), pointer :: nrxlog => active%nrxlog + integer(c_int), pointer :: nkeep => active%nkeep + integer(c_int), pointer :: manualDecodeFlag => active%manualDecodeFlag + character(len=12), pointer :: mycall => active%mycall + character(len=12), pointer :: hiscall => active%hiscall + character(len=6), pointer :: mygrid => active%mygrid + character(len=6), pointer :: hisgrid => active%hisgrid + character(len=20), pointer :: datetime => active%datetime + integer(c_int) :: stop_m65 = 0 + integer(c_int) :: decoder_ready = 0 + character(len=512) :: wsjtx_dir = '' + + integer(c_int) :: nrate_active = 96000 + integer(c_int) :: nfft_active = 32768 + integer(c_int) :: nsmax_active = 60*96000 + integer(c_int) :: nfft_big_active = 56*96000 + integer(c_int) :: t_start = -1 + logical(c_bool) :: abort_decode = .false. + + interface + subroutine lock_decode_requests() bind(C) + end subroutine + subroutine unlock_decode_requests() bind(C) + end subroutine + end interface + +contains + + subroutine set_manual_decode_flag(val) bind(C, name="set_manual_decode_flag") + integer(c_int), value :: val + call lock_decode_requests() + draft%manualDecodeFlag = val + call unlock_decode_requests() + end subroutine + + function get_manual_decode_flag() bind(C, name="get_manual_decode_flag") + use iso_c_binding + integer(c_int) :: get_manual_decode_flag + call lock_decode_requests() + get_manual_decode_flag = draft%manualDecodeFlag + call unlock_decode_requests() + end function + + subroutine set_ftol_nb(val) bind(C, name="set_ftol_nb") + integer(c_int), value :: val + call lock_decode_requests() + draft%ftol_nb = val + call unlock_decode_requests() + end subroutine + + subroutine set_runtime_params(rate_hz, nfft, nfft_big) bind(C, name="set_runtime_params_") + use iso_c_binding + implicit none + integer(c_int), value :: rate_hz, nfft, nfft_big + + nrate_active = rate_hz + nfft_active = nfft + nsmax_active = 60*rate_hz + nfft_big_active = nfft_big + end subroutine set_runtime_params + + subroutine set_wsjtx_dir(path, path_len) bind(C, name="set_wsjtx_dir_") + use iso_c_binding + implicit none + character(kind=c_char), dimension(*), intent(in) :: path + integer(c_int), value :: path_len + integer :: n + + wsjtx_dir = '' + if (path_len > 0) then + n = min(path_len, len(wsjtx_dir)) + wsjtx_dir(1:n) = transfer(path(1:n), wsjtx_dir(1:n)) + end if + end subroutine set_wsjtx_dir + + + subroutine set_stop_m65(val) bind(C, name="set_stop_m65") + use iso_c_binding + integer(c_int), value :: val + call lock_decode_requests() + stop_m65 = 0 + if (val /= 0) then + stop_m65 = 1 + call clear_pending_requests() + endif + call unlock_decode_requests() + end subroutine + + subroutine set_decoder_ready(val) bind(C, name="set_decoder_ready") + use iso_c_binding + integer(c_int), value :: val + call lock_decode_requests() + decoder_ready = 0 + if (val /= 0) decoder_ready = 1 + call unlock_decode_requests() + end subroutine + + subroutine get_mycall(buf) bind(C, name="get_mycall") + character(kind=c_char), intent(out) :: buf(12) + integer :: i + + call lock_decode_requests() + do i = 1, 12 + buf(i) = draft%mycall(i:i) + end do + call unlock_decode_requests() + end subroutine get_mycall + + subroutine get_hiscall(buf) bind(C, name="get_hiscall") + character(kind=c_char), intent(out) :: buf(12) + integer :: i + call lock_decode_requests() + do i = 1, 12 + buf(i) = draft%hiscall(i:i) + end do + call unlock_decode_requests() + end subroutine + + subroutine get_mygrid(buf) bind(C, name="get_mygrid") + character(kind=c_char), intent(out) :: buf(6) + integer :: i + call lock_decode_requests() + do i = 1, 6 + buf(i) = draft%mygrid(i:i) + end do + call unlock_decode_requests() + end subroutine + + subroutine get_hisgrid(buf) bind(C, name="get_hisgrid") + character(kind=c_char), intent(out) :: buf(6) + integer :: i + call lock_decode_requests() + do i = 1, 6 + buf(i) = draft%hisgrid(i:i) + end do + call unlock_decode_requests() + end subroutine + +! NOTE ABOUT DATETIME LENGTH (17 vs 20) +! +! datetime is declared as CHARACTER(len=20) for legacy compatibility with the +! old COMMON block, but only the first 17 characters are meaningful. The decoder +! in m65_mod writes: +! +! write(..., '( "UTC Date: ", a17 )') datetime(1:17) +! +! so the timestamp format is always 17 characters (YYYY-MM-DD HH:MM). The extra +! 3 characters are unused padding. The C interface therefore exchanges only the +! first 17 bytes, which is intentional and correct. +! +! If the timestamp format changes in the future, this interface boundary should +! be updated accordingly. + + subroutine get_datetime(buf) bind(C, name="get_datetime") + character(kind=c_char), intent(out) :: buf(17) + integer :: i + call lock_decode_requests() + do i = 1, 17 + buf(i) = draft%datetime(i:i) + end do + call unlock_decode_requests() + end subroutine + + ! Helper subroutine to copy fixed-length Fortran string to C buffer + subroutine move_chars(dest, dest_len, src) + integer(c_int), intent(in) :: dest_len + character(kind=c_char), intent(out) :: dest(dest_len) + character(len=*), intent(in) :: src + integer :: i, n + + n = min(len(src), dest_len) + do i = 1, n + dest(i) = src(i:i) + end do + end subroutine move_chars + + function get_fcenter() bind(C, name="get_fcenter") + real(c_double) :: get_fcenter + call lock_decode_requests() + get_fcenter = draft%fcenter + call unlock_decode_requests() + end function + + function get_nkeep() bind(C, name="get_nkeep") + integer(c_int) :: get_nkeep + call lock_decode_requests() + get_nkeep = draft%nkeep + call unlock_decode_requests() + end function + + function get_ndop00() bind(C, name="get_ndop00") + integer(c_int) :: get_ndop00 + call lock_decode_requests() + get_ndop00 = draft%ndop00 + call unlock_decode_requests() + end function + + function get_map65RxLog() bind(C, name="get_map65RxLog") + integer(c_int) :: get_map65RxLog + call lock_decode_requests() + get_map65RxLog = draft%map65RxLog + call unlock_decode_requests() + end function + + function get_nutc() bind(C, name="get_nutc") + integer(c_int) :: get_nutc + call lock_decode_requests() + get_nutc = draft%nutc + call unlock_decode_requests() + end function + + function get_idphi() bind(C, name="get_idphi") + integer(c_int) :: get_idphi + call lock_decode_requests() + get_idphi = draft%idphi + call unlock_decode_requests() + end function + + function get_mousedf() bind(C, name="get_mousedf") + integer(c_int) :: get_mousedf + call lock_decode_requests() + get_mousedf = draft%mousedf + call unlock_decode_requests() + end function + + function get_mousefqso() bind(C, name="get_mousefqso") + integer(c_int) :: get_mousefqso + call lock_decode_requests() + get_mousefqso = draft%mousefqso + call unlock_decode_requests() + end function + + function get_nagain() bind(C, name="get_nagain") + integer(c_int) :: get_nagain + call lock_decode_requests() + get_nagain = draft%nagain + call unlock_decode_requests() + end function + + function get_ndepth() bind(C, name="get_ndepth") + integer(c_int) :: get_ndepth + call lock_decode_requests() + get_ndepth = draft%ndepth + call unlock_decode_requests() + end function + + function get_ndiskdat() bind(C, name="get_ndiskdat") + integer(c_int) :: get_ndiskdat + call lock_decode_requests() + get_ndiskdat = draft%ndiskdat + call unlock_decode_requests() + end function + + function get_neme() bind(C, name="get_neme") + integer(c_int) :: get_neme + call lock_decode_requests() + get_neme = draft%neme + call unlock_decode_requests() + end function + + function get_newdat() bind(C, name="get_newdat") + integer(c_int) :: get_newdat + call lock_decode_requests() + get_newdat = draft%newdat + call unlock_decode_requests() + end function + + function get_nfa() bind(C, name="get_nfa") + integer(c_int) :: get_nfa + call lock_decode_requests() + get_nfa = draft%nfa + call unlock_decode_requests() + end function + + function get_nfb() bind(C, name="get_nfb") + integer(c_int) :: get_nfb + call lock_decode_requests() + get_nfb = draft%nfb + call unlock_decode_requests() + end function + + function get_nfcal() bind(C, name="get_nfcal") + integer(c_int) :: get_nfcal + call lock_decode_requests() + get_nfcal = draft%nfcal + call unlock_decode_requests() + end function + + function get_nfshift() bind(C, name="get_nfshift") + integer(c_int) :: get_nfshift + call lock_decode_requests() + get_nfshift = draft%nfshift + call unlock_decode_requests() + end function + + function get_mcall3() bind(C, name="get_mcall3") + integer(c_int) :: get_mcall3 + call lock_decode_requests() + get_mcall3 = draft%mcall3 + call unlock_decode_requests() + end function + + function get_ntimeout() bind(C, name="get_ntimeout") + integer(c_int) :: get_ntimeout + call lock_decode_requests() + get_ntimeout = draft%ntimeout + call unlock_decode_requests() + end function + + function get_ntol() bind(C, name="get_ntol") + integer(c_int) :: get_ntol + call lock_decode_requests() + get_ntol = draft%ntol + call unlock_decode_requests() + end function + + function get_nxant() bind(C, name="get_nxant") + integer(c_int) :: get_nxant + call lock_decode_requests() + get_nxant = draft%nxant + call unlock_decode_requests() + end function + + function get_nfsample() bind(C, name="get_nfsample") + integer(c_int) :: get_nfsample + call lock_decode_requests() + get_nfsample = draft%nfsample + call unlock_decode_requests() + end function + + function get_nxpol() bind(C, name="get_nxpol") + integer(c_int) :: get_nxpol + call lock_decode_requests() + get_nxpol = draft%nxpol + call unlock_decode_requests() + end function + + function get_nmode() bind(C, name="get_nmode") + integer(c_int) :: get_nmode + call lock_decode_requests() + get_nmode = draft%nmode + call unlock_decode_requests() + end function + + function get_nsave() bind(C, name="get_nsave") + integer(c_int) :: get_nsave + call lock_decode_requests() + get_nsave = draft%nsave + call unlock_decode_requests() + end function + + function get_max_drift() bind(C, name="get_max_drift") + integer(c_int) :: get_max_drift + call lock_decode_requests() + get_max_drift = draft%max_drift + call unlock_decode_requests() + end function + + function get_nhsym() bind(C, name="get_nhsym") + integer(c_int) :: get_nhsym + call lock_decode_requests() + get_nhsym = draft%nhsym + call unlock_decode_requests() + end function + + subroutine set_fcenter(val) bind(C, name="set_fcenter") + use iso_c_binding + real(c_double), value :: val + call lock_decode_requests() + draft%fcenter = val + call unlock_decode_requests() + end subroutine + + subroutine set_nkeep(val) bind(C, name="set_nkeep") + use iso_c_binding + integer(c_int), value :: val + call lock_decode_requests() + draft%nkeep = val + call unlock_decode_requests() + end subroutine + + subroutine set_ndop00(val) bind(C, name="set_ndop00") + use iso_c_binding + integer(c_int), value :: val + call lock_decode_requests() + draft%ndop00 = val + call unlock_decode_requests() + end subroutine + + subroutine set_map65RxLog(val) bind(C, name="set_map65RxLog") + use iso_c_binding + integer(c_int), value :: val + ! map65RxLog is read back by get_map65RxLog() for debug logging only. + ! nrxlog is the variable m65c()/decode0.f90 actually check (iand bits + ! 1/2/4/8) to write the date header, erase map65_rx.log, clear the + ! decode-history file on Erase, and force manual dPhi. Before this fix + ! nrxlog was never assigned anywhere, so all four of those flag bits + ! were permanently dead -- e.g. Erase Band Map and Messages never + ! actually cleared unit 26, so the next display() cycle just replayed + ! the full decode history back into the Messages window. + call lock_decode_requests() + draft%map65RxLog = val + draft%nrxlog = val + call unlock_decode_requests() + end subroutine + + subroutine set_nutc(val) bind(C, name="set_nutc") + use iso_c_binding + integer(c_int), value :: val + call lock_decode_requests() + draft%nutc = val + call unlock_decode_requests() + end subroutine + + subroutine set_idphi(val) bind(C, name="set_idphi") + use iso_c_binding + integer(c_int), value :: val + call lock_decode_requests() + draft%idphi = val + call unlock_decode_requests() + end subroutine + + subroutine set_mousedf(val) bind(C, name="set_mousedf") + use iso_c_binding + integer(c_int), value :: val + call lock_decode_requests() + draft%mousedf = val + call unlock_decode_requests() + end subroutine + + subroutine set_mousefqso(val) bind(C, name="set_mousefqso") + use iso_c_binding + integer(c_int), value :: val + call lock_decode_requests() + draft%mousefqso = val + call unlock_decode_requests() + end subroutine + + subroutine set_nagain(val) bind(C, name="set_nagain") + use iso_c_binding + integer(c_int), value :: val + call lock_decode_requests() + draft%nagain = val + call unlock_decode_requests() + end subroutine + + subroutine set_ndepth(val) bind(C, name="set_ndepth") + use iso_c_binding + integer(c_int), value :: val + call lock_decode_requests() + draft%ndepth = val + call unlock_decode_requests() + end subroutine + + subroutine set_ndiskdat(val) bind(C, name="set_ndiskdat") + use iso_c_binding + integer(c_int), value :: val + call lock_decode_requests() + draft%ndiskdat = val + call unlock_decode_requests() + end subroutine + + subroutine set_neme(val) bind(C, name="set_neme") + use iso_c_binding + integer(c_int), value :: val + call lock_decode_requests() + draft%neme = val + call unlock_decode_requests() + end subroutine + + subroutine set_newdat(val) bind(C, name="set_newdat") + use iso_c_binding + integer(c_int), value :: val + call lock_decode_requests() + draft%newdat = val + call unlock_decode_requests() + end subroutine + + subroutine set_nfa(val) bind(C, name="set_nfa") + use iso_c_binding + integer(c_int), value :: val + call lock_decode_requests() + draft%nfa = val + call unlock_decode_requests() + end subroutine + + subroutine set_nfb(val) bind(C, name="set_nfb") + use iso_c_binding + integer(c_int), value :: val + call lock_decode_requests() + draft%nfb = val + call unlock_decode_requests() + end subroutine + + subroutine set_nfcal(val) bind(C, name="set_nfcal") + use iso_c_binding + integer(c_int), value :: val + call lock_decode_requests() + draft%nfcal = val + call unlock_decode_requests() + end subroutine + + subroutine set_nfshift(val) bind(C, name="set_nfshift") + use iso_c_binding + integer(c_int), value :: val + call lock_decode_requests() + draft%nfshift = val + call unlock_decode_requests() + end subroutine + + subroutine set_mcall3(val) bind(C, name="set_mcall3") + use iso_c_binding + integer(c_int), value :: val + call lock_decode_requests() + draft%mcall3 = val + call unlock_decode_requests() + end subroutine + + subroutine set_ntimeout(val) bind(C, name="set_ntimeout") + use iso_c_binding + integer(c_int), value :: val + call lock_decode_requests() + draft%ntimeout = val + call unlock_decode_requests() + end subroutine + + subroutine set_ntol(val) bind(C, name="set_ntol") + use iso_c_binding + integer(c_int), value :: val + call lock_decode_requests() + draft%ntol = val + call unlock_decode_requests() + end subroutine + + subroutine set_nxant(val) bind(C, name="set_nxant") + use iso_c_binding + integer(c_int), value :: val + call lock_decode_requests() + draft%nxant = val + call unlock_decode_requests() + end subroutine + + subroutine set_nfsample(val) bind(C, name="set_nfsample") + use iso_c_binding + integer(c_int), value :: val + call lock_decode_requests() + draft%nfsample = val + call unlock_decode_requests() + end subroutine + + subroutine set_nxpol(val) bind(C, name="set_nxpol") + use iso_c_binding + integer(c_int), value :: val + call lock_decode_requests() + draft%nxpol = val + call unlock_decode_requests() + end subroutine + + subroutine set_nmode(val) bind(C, name="set_nmode") + use iso_c_binding + integer(c_int), value :: val + call lock_decode_requests() + draft%nmode = val + call unlock_decode_requests() + end subroutine + + subroutine set_nsave(val) bind(C, name="set_nsave") + use iso_c_binding + integer(c_int), value :: val + call lock_decode_requests() + draft%nsave = val + call unlock_decode_requests() + end subroutine + + subroutine set_max_drift(val) bind(C, name="set_max_drift") + use iso_c_binding + integer(c_int), value :: val + call lock_decode_requests() + draft%max_drift = val + call unlock_decode_requests() + end subroutine + + subroutine set_nhsym(val) bind(C, name="set_nhsym") + use iso_c_binding + integer(c_int), value :: val + call lock_decode_requests() + draft%nhsym = val + call unlock_decode_requests() + end subroutine + + subroutine set_mycall(buf) bind(C, name="set_mycall") + use iso_c_binding + character(kind=c_char), intent(in) :: buf(12) + integer :: i + call lock_decode_requests() + do i = 1, 12 + draft%mycall(i:i) = buf(i) + end do + call unlock_decode_requests() + end subroutine + + subroutine set_hiscall(buf) bind(C, name="set_hiscall") + use iso_c_binding + character(kind=c_char), intent(in) :: buf(12) + integer :: i + call lock_decode_requests() + do i = 1, 12 + draft%hiscall(i:i) = buf(i) + end do + call unlock_decode_requests() + end subroutine + + subroutine set_mygrid(buf) bind(C, name="set_mygrid") + use iso_c_binding + character(kind=c_char), intent(in) :: buf(6) + integer :: i + call lock_decode_requests() + do i = 1, 6 + draft%mygrid(i:i) = buf(i) + end do + call unlock_decode_requests() + end subroutine + + subroutine set_hisgrid(buf) bind(C, name="set_hisgrid") + use iso_c_binding + character(kind=c_char), intent(in) :: buf(6) + integer :: i + call lock_decode_requests() + do i = 1, 6 + draft%hisgrid(i:i) = buf(i) + end do + call unlock_decode_requests() +end subroutine + +subroutine set_datetime(buf) bind(C, name="set_datetime") + use iso_c_binding + character(kind=c_char), intent(in) :: buf(17) + integer :: i + call lock_decode_requests() + do i = 1, 17 + draft%datetime(i:i) = buf(i) + end do + call unlock_decode_requests() +end subroutine + + function publish_decode_request() result(request_id) bind(C) + integer(c_int64_t) :: request_id + type(decode_request), pointer :: request + + allocate(request) + call lock_decode_requests() + published_request_id = published_request_id + 1 + request_id = published_request_id + request%id = request_id + request%input_generation = live_input_generation + request%parameters = draft + request%parameters%newdat = 1 + if (associated(pending_tail)) then + pending_tail%next => request + else + pending_head => request + endif + pending_tail => request + decoder_ready = 1 + draft%manualDecodeFlag = 0 + call unlock_decode_requests() + end function + + logical function claim_decode_request() + type(decode_request), pointer :: request + + call lock_decode_requests() + claim_decode_request = decoder_ready /= 0 .and. associated(pending_head) + if (claim_decode_request) then + request => pending_head + pending_head => request%next + if (.not. associated(pending_head)) nullify(pending_tail) + active = request%parameters + active_request_id = request%id + active_input_generation = request%input_generation + active_request_expired = active%ndiskdat == 0 .and. active%nagain == 0 .and. & + active%manualDecodeFlag == 0 .and. request%input_generation /= live_input_generation + deallocate(request) + endif + call unlock_decode_requests() + end function + + subroutine initialize_decode_parameters() + call lock_decode_requests() + active = draft + call unlock_decode_requests() + end subroutine + + subroutine advance_live_input_generation() bind(C) + call lock_decode_requests() + live_input_generation = live_input_generation + 1 + call unlock_decode_requests() + end subroutine + + subroutine clear_pending_requests() + type(decode_request), pointer :: request + do while (associated(pending_head)) + request => pending_head + pending_head => request%next + deallocate(request) + enddo + nullify(pending_tail) + end subroutine + + subroutine cancel_pending_decode_requests() bind(C) + call lock_decode_requests() + call clear_pending_requests() + decoder_ready = 0 + published_request_id = published_request_id + 1 + call unlock_decode_requests() + end subroutine + + function get_stop_m65() result(stopped) + integer(c_int) :: stopped + call lock_decode_requests() + stopped = stop_m65 + call unlock_decode_requests() + end function + + logical(c_bool) function is_current_decode_request(request_id) bind(C) + integer(c_int64_t), value :: request_id + call lock_decode_requests() + is_current_decode_request = request_id == published_request_id + call unlock_decode_requests() + end function + +end module npar_ptrs_mod diff --git a/map65/libm65/packjt.f90 b/map65/libm65/packjt.f90 index c1fc0089..c9928208 100644 --- a/map65/libm65/packjt.f90 +++ b/map65/libm65/packjt.f90 @@ -1,277 +1,317 @@ module packjt - + implicit none contains +pure logical function is_valid_jt65_codeword(dat) + integer, intent(in) :: dat(12) + + integer, parameter :: NBASE = 37*36*10*27*27*27 + integer, parameter :: LAST_V2_CALL = 267796945 + integer :: nc1, nc2, ng + + nc1 = ishft(dat(1),22) + ishft(dat(2),16) + ishft(dat(3),10) + & + ishft(dat(4),4) + iand(ishft(dat(5),-2),15) + nc2 = ishft(iand(dat(5),3),26) + ishft(dat(6),20) + & + ishft(dat(7),14) + ishft(dat(8),8) + ishft(dat(9),2) + & + iand(ishft(dat(10),-4),3) + ng = ishft(iand(dat(10),15),12) + ishft(dat(11),6) + dat(12) + + if (ng >= 32768) then + is_valid_jt65_codeword = .true. + else + is_valid_jt65_codeword = nc1 /= NBASE .and. nc1 <= LAST_V2_CALL .and. & + nc2 < NBASE + endif +end function is_valid_jt65_codeword + subroutine packbits(dbits,nsymd,m0,sym) ! Pack 0s and 1s from dbits() into sym() with m0 bits per word. ! NB: nsymd is the number of packed output words. + use iso_fortran_env, only: int8 + implicit none + integer, intent(in) :: nsymd, m0 + integer(int8), intent(in) :: dbits(:) + integer, intent(out) :: sym(:) + + integer :: i, j, k, m, n + + k = 0 + do i = 1, nsymd + n = 0 + do j = 1, m0 + k = k + 1 + m = dbits(k) + n = ior(ishft(n,1), m) + end do + sym(i) = n + end do +end subroutine packbits - integer sym(:) - integer*1 dbits(:) - - k=0 - do i=1,nsymd - n=0 - do j=1,m0 - k=k+1 - m=dbits(k) - n=ior(ishft(n,1),m) - enddo - sym(i)=n - enddo - - return - end subroutine packbits subroutine unpackbits(sym,nsymd,m0,dbits) ! Unpack bits from sym() into dbits(), one bit per byte. ! NB: nsymd is the number of input words, and m0 their length. ! there will be m0*nsymd output bytes, each 0 or 1. - - integer sym(:) - integer*1 dbits(:) - - k=0 - do i=1,nsymd - mask=ishft(1,m0-1) - do j=1,m0 - k=k+1 - dbits(k)=0 - if(iand(mask,sym(i)).ne.0) dbits(k)=1 - mask=ishft(mask,-1) - enddo - enddo - - return - end subroutine unpackbits - - subroutine packcall(callsign,ncall,text) - - ! Pack a valid callsign into a 28-bit integer. - - parameter (NBASE=37*36*10*27*27*27) - character callsign*6,c*1,tmp*6 - logical text - - text=.false. - - ! Work-around for Swaziland prefix: - if(callsign(1:4).eq.'3DA0') callsign='3D0'//callsign(5:6) - - if(callsign(1:3).eq.'CQ ') then - ncall=NBASE + 1 - if(callsign(4:4).ge.'0' .and. callsign(4:4).le.'9' .and. & - callsign(5:5).ge.'0' .and. callsign(5:5).le.'9' .and. & - callsign(6:6).ge.'0' .and. callsign(6:6).le.'9') then + use iso_fortran_env, only: int8 + implicit none + integer, intent(in) :: sym(:) + integer, intent(in) :: nsymd, m0 + integer(int8), intent(out) :: dbits(:) + + integer :: i, j, k, mask + + k = 0 + do i = 1, nsymd + mask = ishft(1, m0 - 1) + do j = 1, m0 + k = k + 1 + dbits(k) = 0 + if (iand(mask, sym(i)) .ne. 0) dbits(k) = 1 + mask = ishft(mask, -1) + end do + end do +end subroutine unpackbits + +subroutine packcall(callsign, ncall, text) + use nchar_mod + implicit none + integer, parameter :: NBASE = 37*36*10*27*27*27 + + character(len=6), intent(inout) :: callsign + integer, intent(out) :: ncall + logical, intent(out) :: text + + character(len=6) :: tmp + character(len=1) :: c + integer :: i, nfreq + integer :: n1, n2, n3, n4, n5, n6 + + text = .false. + + if (callsign(1:4) .eq. '3DA0') callsign = '3D0'//callsign(5:6) + + if (callsign(1:3) .eq. 'CQ ') then + ncall = NBASE + 1 + if (callsign(4:4) .ge. '0' .and. callsign(4:4) .le. '9' .and. & + callsign(5:5) .ge. '0' .and. callsign(5:5) .le. '9' .and. & + callsign(6:6) .ge. '0' .and. callsign(6:6) .le. '9') then read(callsign(4:6),*) nfreq - ncall=NBASE + 3 + nfreq - endif + ncall = NBASE + 3 + nfreq + end if return - else if(callsign(1:4).eq.'QRZ ') then - ncall=NBASE + 2 + else if (callsign(1:4) .eq. 'QRZ ') then + ncall = NBASE + 2 return - else if(callsign(1:3).eq.'DE ') then - ncall=267796945 + else if (callsign(1:3) .eq. 'DE ') then + ncall = 267796945 return - endif - - tmp=' ' - if(callsign(3:3).ge.'0' .and. callsign(3:3).le.'9') then - tmp=callsign - else if(callsign(2:2).ge.'0' .and. callsign(2:2).le.'9') then - if(callsign(6:6).ne.' ') then - text=.true. + end if + + tmp = ' ' + if (callsign(3:3) .ge. '0' .and. callsign(3:3) .le. '9') then + tmp = callsign + else if (callsign(2:2) .ge. '0' .and. callsign(2:2) .le. '9') then + if (callsign(6:6) .ne. ' ') then + text = .true. return - endif - tmp=' '//callsign(:5) + end if + tmp = ' '//callsign(:5) else - text=.true. + text = .true. return - endif - - do i=1,6 - c=tmp(i:i) - if(c.ge.'a' .and. c.le.'z') & - tmp(i:i)=char(ichar(c)-ichar('a')+ichar('A')) - enddo - - n1=0 - if((tmp(1:1).ge.'A'.and.tmp(1:1).le.'Z').or.tmp(1:1).eq.' ') n1=1 - if(tmp(1:1).ge.'0' .and. tmp(1:1).le.'9') n1=1 - n2=0 - if(tmp(2:2).ge.'A' .and. tmp(2:2).le.'Z') n2=1 - if(tmp(2:2).ge.'0' .and. tmp(2:2).le.'9') n2=1 - n3=0 - if(tmp(3:3).ge.'0' .and. tmp(3:3).le.'9') n3=1 - n4=0 - if((tmp(4:4).ge.'A'.and.tmp(4:4).le.'Z').or.tmp(4:4).eq.' ') n4=1 - n5=0 - if((tmp(5:5).ge.'A'.and.tmp(5:5).le.'Z').or.tmp(5:5).eq.' ') n5=1 - n6=0 - if((tmp(6:6).ge.'A'.and.tmp(6:6).le.'Z').or.tmp(6:6).eq.' ') n6=1 - - if(n1+n2+n3+n4+n5+n6 .ne. 6) then - text=.true. - return - endif - - ncall=nchar(tmp(1:1)) - ncall=36*ncall+nchar(tmp(2:2)) - ncall=10*ncall+nchar(tmp(3:3)) - ncall=27*ncall+nchar(tmp(4:4))-10 - ncall=27*ncall+nchar(tmp(5:5))-10 - ncall=27*ncall+nchar(tmp(6:6))-10 - - return - end subroutine packcall - - subroutine unpackcall(ncall,word,iv2,psfx) - - parameter (NBASE=37*36*10*27*27*27) - character word*12,c*37,psfx*4 - - data c/'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ '/ - - word='......' - psfx=' ' - n=ncall - iv2=0 - if(n.ge.262177560) go to 20 - word='......' - ! if(n.ge.262177560) go to 999 !Plain text message ... - i=mod(n,27)+11 - word(6:6)=c(i:i) - n=n/27 - i=mod(n,27)+11 - word(5:5)=c(i:i) - n=n/27 - i=mod(n,27)+11 - word(4:4)=c(i:i) - n=n/27 - i=mod(n,10)+1 - word(3:3)=c(i:i) - n=n/10 - i=mod(n,36)+1 - word(2:2)=c(i:i) - n=n/36 - i=n+1 - word(1:1)=c(i:i) - do i=1,4 - if(word(i:i).ne.' ') go to 10 - enddo + end if + + do i = 1, 6 + c = tmp(i:i) + if (c .ge. 'a' .and. c .le. 'z') & + tmp(i:i) = char(ichar(c) - ichar('a') + ichar('A')) + end do + + n1 = 0 + if ((tmp(1:1) .ge. 'A' .and. tmp(1:1) .le. 'Z') .or. tmp(1:1) .eq. ' ') n1 = 1 + if (tmp(1:1) .ge. '0' .and. tmp(1:1) .le. '9') n1 = 1 + n2 = 0 + if (tmp(2:2) .ge. 'A' .and. tmp(2:2) .le. 'Z') n2 = 1 + if (tmp(2:2) .ge. '0' .and. tmp(2:2) .le. '9') n2 = 1 + n3 = 0 + if (tmp(3:3) .ge. '0' .and. tmp(3:3) .le. '9') n3 = 1 + n4 = 0 + if ((tmp(4:4) .ge. 'A' .and. tmp(4:4) .le. 'Z') .or. tmp(4:4) .eq. ' ') n4 = 1 + n5 = 0 + if ((tmp(5:5) .ge. 'A' .and. tmp(5:5) .le. 'Z') .or. tmp(5:5) .eq. ' ') n5 = 1 + n6 = 0 + if ((tmp(6:6) .ge. 'A' .and. tmp(6:6) .le. 'Z') .or. tmp(6:6) .eq. ' ') n6 = 1 + + if (n1 + n2 + n3 + n4 + n5 + n6 .ne. 6) then + text = .true. + return + end if + + ncall = nchar(tmp(1:1)) + ncall = 36*ncall + nchar(tmp(2:2)) + ncall = 10*ncall + nchar(tmp(3:3)) + ncall = 27*ncall + nchar(tmp(4:4)) - 10 + ncall = 27*ncall + nchar(tmp(5:5)) - 10 + ncall = 27*ncall + nchar(tmp(6:6)) - 10 +end subroutine packcall + + +subroutine unpackcall(ncall, word, iv2, psfx) + implicit none + integer, intent(in) :: ncall + character(len=12), intent(out):: word + integer, intent(out) :: iv2 + character(len=4), intent(out) :: psfx + + integer :: n, i + character(len=37) :: c + + integer, parameter :: NBASE = 37*36*10*27*27*27 + integer, parameter :: LAST_V2_CALL = 267796945 + data c /'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ '/ + + word = '......' + psfx = ' ' + + if (ncall < 0 .or. ncall == NBASE .or. ncall > LAST_V2_CALL) then + write(*,*) 'unpackcall: ncall out of range = ', ncall + end if + + n = ncall + iv2 = 0 + + if (n .ge. 262177560) go to 20 + + word = '......' + i = mod(n,27) + 11 + word(6:6) = c(i:i) + n = n/27 + i = mod(n,27) + 11 + word(5:5) = c(i:i) + n = n/27 + i = mod(n,27) + 11 + word(4:4) = c(i:i) + n = n/27 + i = mod(n,10) + 1 + word(3:3) = c(i:i) + n = n/10 + i = mod(n,36) + 1 + word(2:2) = c(i:i) + n = n/36 + i = n + 1 + word(1:1) = c(i:i) + do i = 1, 4 + if (word(i:i) .ne. ' ') go to 10 + end do go to 999 - 10 word=word(i:) +10 word = word(i:) go to 999 - 20 if(n.ge.267796946) go to 999 - - ! We have a JT65v2 message - if((n.ge.262178563) .and. (n.le.264002071)) then - ! CQ with prefix - iv2=1 - n=n-262178563 - i=mod(n,37)+1 - psfx(4:4)=c(i:i) - n=n/37 - i=mod(n,37)+1 - psfx(3:3)=c(i:i) - n=n/37 - i=mod(n,37)+1 - psfx(2:2)=c(i:i) - n=n/37 - i=n+1 - psfx(1:1)=c(i:i) - - else if((n.ge.264002072) .and. (n.le.265825580)) then - ! QRZ with prefix - iv2=2 - n=n-264002072 - i=mod(n,37)+1 - psfx(4:4)=c(i:i) - n=n/37 - i=mod(n,37)+1 - psfx(3:3)=c(i:i) - n=n/37 - i=mod(n,37)+1 - psfx(2:2)=c(i:i) - n=n/37 - i=n+1 - psfx(1:1)=c(i:i) - - else if((n.ge.265825581) .and. (n.le.267649089)) then - ! DE with prefix - iv2=3 - n=n-265825581 - i=mod(n,37)+1 - psfx(4:4)=c(i:i) - n=n/37 - i=mod(n,37)+1 - psfx(3:3)=c(i:i) - n=n/37 - i=mod(n,37)+1 - psfx(2:2)=c(i:i) - n=n/37 - i=n+1 - psfx(1:1)=c(i:i) - - else if((n.ge.267649090) .and. (n.le.267698374)) then - ! CQ with suffix - iv2=4 - n=n-267649090 - i=mod(n,37)+1 - psfx(3:3)=c(i:i) - n=n/37 - i=mod(n,37)+1 - psfx(2:2)=c(i:i) - n=n/37 - i=n+1 - psfx(1:1)=c(i:i) - - else if((n.ge.267698375) .and. (n.le.267747659)) then - ! QRZ with suffix - iv2=5 - n=n-267698375 - i=mod(n,37)+1 - psfx(3:3)=c(i:i) - n=n/37 - i=mod(n,37)+1 - psfx(2:2)=c(i:i) - n=n/37 - i=n+1 - psfx(1:1)=c(i:i) - - else if((n.ge.267747660) .and. (n.le.267796944)) then - ! DE with suffix - iv2=6 - n=n-267747660 - i=mod(n,37)+1 - psfx(3:3)=c(i:i) - n=n/37 - i=mod(n,37)+1 - psfx(2:2)=c(i:i) - n=n/37 - i=n+1 - psfx(1:1)=c(i:i) - - else if(n.eq.267796945) then - ! DE with no prefix or suffix - iv2=7 +20 if (n .ge. 267796946) go to 999 + + if ((n .ge. 262178563) .and. (n .le. 264002071)) then + iv2 = 1 + n = n - 262178563 + i = mod(n,37) + 1 + psfx(4:4) = c(i:i) + n = n/37 + i = mod(n,37) + 1 + psfx(3:3) = c(i:i) + n = n/37 + i = mod(n,37) + 1 + psfx(2:2) = c(i:i) + n = n/37 + i = n + 1 + psfx(1:1) = c(i:i) + + else if ((n .ge. 264002072) .and. (n .le. 265825580)) then + iv2 = 2 + n = n - 264002072 + i = mod(n,37) + 1 + psfx(4:4) = c(i:i) + n = n/37 + i = mod(n,37) + 1 + psfx(3:3) = c(i:i) + n = n/37 + i = mod(n,37) + 1 + psfx(2:2) = c(i:i) + n = n/37 + i = n + 1 + psfx(1:1) = c(i:i) + + else if ((n .ge. 265825581) .and. (n .le. 267649089)) then + iv2 = 3 + n = n - 265825581 + i = mod(n,37) + 1 + psfx(4:4) = c(i:i) + n = n/37 + i = mod(n,37) + 1 + psfx(3:3) = c(i:i) + n = n/37 + i = mod(n,37) + 1 + psfx(2:2) = c(i:i) + n = n/37 + i = n + 1 + psfx(1:1) = c(i:i) + + else if ((n .ge. 267649090) .and. (n .le. 267698374)) then + iv2 = 4 + n = n - 267649090 + i = mod(n,37) + 1 + psfx(3:3) = c(i:i) + n = n/37 + i = mod(n,37) + 1 + psfx(2:2) = c(i:i) + n = n/37 + i = n + 1 + psfx(1:1) = c(i:i) + + else if ((n .ge. 267698375) .and. (n .le. 267747659)) then + iv2 = 5 + n = n - 267698375 + i = mod(n,37) + 1 + psfx(3:3) = c(i:i) + n = n/37 + i = mod(n,37) + 1 + psfx(2:2) = c(i:i) + n = n/37 + i = n + 1 + psfx(1:1) = c(i:i) + + else if ((n .ge. 267747660) .and. (n .le. 267796944)) then + iv2 = 6 + n = n - 267747660 + i = mod(n,37) + 1 + psfx(3:3) = c(i:i) + n = n/37 + i = mod(n,37) + 1 + psfx(2:2) = c(i:i) + n = n/37 + i = n + 1 + psfx(1:1) = c(i:i) + + else if (n .eq. 267796945) then + iv2 = 7 psfx = ' ' - endif + end if - 999 if(word(1:3).eq.'3D0') word='3DA0'//word(4:) - - return - end subroutine unpackcall +999 if (word(1:3) .eq. '3D0') word = '3DA0'//word(4:) +end subroutine unpackcall subroutine packgrid(grid,ng,text) + use grid2deg_mod, only: grid2deg + implicit none + + integer, parameter :: NGBASE=180*180 + character(len=4), intent(inout) :: grid ! modified when mapping extended reports + integer, intent(out) :: ng + logical, intent(out) :: text - parameter (NGBASE=180*180) - character*4 grid - character*1 c1 - logical text + integer :: n, long, lat + real :: dlong, dlat + character(len=1) :: c1 text=.false. if(grid.eq.' ') go to 90 !Blank grid is OK @@ -343,10 +383,18 @@ subroutine packbits(dbits,nsymd,m0,sym) return end subroutine packgrid - subroutine unpackgrid(ng,grid) + subroutine unpackgrid(ng, grid) + + use deg2grid_mod + implicit none + + integer, parameter :: NGBASE = 180*180 + integer, intent(in) :: ng + character(len=4), intent(out) :: grid - parameter (NGBASE=180*180) - character grid*4,grid6*6 + integer :: n + real :: dlong, dlat + character(len=6) :: grid6 grid=' ' if(ng.ge.32400) go to 10 @@ -390,26 +438,40 @@ subroutine packbits(dbits,nsymd,m0,sym) subroutine packmsg(msg0,dat,itype) + use getpfx1_mod + use fil6521_mod + use k2grid_mod + use fmtmsg_mod + + implicit none + ! Packs a JT4/JT9/JT65 message into twelve 6-bit symbols ! itype Message Type !-------------------- - ! 1 Standardd message + ! 1 Standard message ! 2 Type 1 prefix ! 3 Type 1 suffix ! 4 Type 2 prefix ! 5 Type 2 suffix ! 6 Free text ! -1 Does not decode correctly - - parameter (NBASE=37*36*10*27*27*27) - parameter (NBASE2=262178562) - character*22 msg0,msg - integer dat(:) - character*12 c1,c2 - character*4 c3 - character*6 grid6 - logical text1,text2,text3 + + character(len=22), intent(in) :: msg0 + integer, intent(out) :: dat(:) + integer, intent(out) :: itype + + integer, parameter :: NBASE = 37*36*10*27*27*27 + integer, parameter :: NBASE2 = 262178562 + + character(len=22) :: msg + character(len=12) :: c1, c2 + character(len=4) :: c3 + character(len=6) :: grid6 + logical :: text1, text2, text3 + integer :: i, ia, ib, ic, iz + integer :: k1, k2, nv2a, nv2b + integer :: nc1, nc2, ng, k msg=msg0 itype=1 @@ -457,10 +519,10 @@ subroutine packbits(dbits,nsymd,m0,sym) if(c3.eq.'OOO ') c3=' ' !Strip out the OOO flag call getpfx1(c1,k1,nv2a) if(nv2a.ge.4) go to 10 - call packcall(c1,nc1,text1) + call packcall(c1(1:6),nc1,text1) if(text1) go to 10 call getpfx1(c2,k2,nv2b) - call packcall(c2,nc2,text2) + call packcall(c2(1:6),nc2,text2) if(text2) go to 10 if(nv2a.eq.2 .or. nv2a.eq.3 .or. nv2b.eq.2 .or. nv2b.eq.3) then if(k1.lt.0 .or. k2.lt.0 .or. k1*k2.ne.0) go to 10 @@ -490,7 +552,7 @@ subroutine packbits(dbits,nsymd,m0,sym) ! The message will be treated as plain text. 10 itype=6 - call packtext(msg,nc1,nc2,ng) + call packtext(msg(1:13),nc1,nc2,ng) ng=ng+32768 ! Encode data into 6-bit words @@ -512,13 +574,26 @@ subroutine packbits(dbits,nsymd,m0,sym) return end subroutine packmsg - subroutine unpackmsg(dat,msg) +subroutine unpackmsg(dat, msg) + use getpfx2_mod + implicit none - parameter (NBASE=37*36*10*27*27*27) - parameter (NGBASE=180*180) - integer dat(:) - character c1*12,c2*12,grid*4,msg*22,grid6*6,psfx*4,junk2*4 - logical cqnnn + !==== Dummy arguments ===================================================== + integer, intent(in) :: dat(:) + character(len=22), intent(out) :: msg + + !==== Local variables ===================================================== + integer :: nc1, nc2, ng + integer :: iv2, nfreq + integer :: i, j, k, n1, n2 + integer :: junk1 + character(len=12) :: c1, c2 + character(len=4) :: grid, psfx, junk2 + character(len=6) :: grid6 + logical :: cqnnn + + integer, parameter :: NBASE = 37*36*10*27*27*27 + integer, parameter :: NGBASE = 180*180 cqnnn=.false. nc1=ishft(dat(1),22) + ishft(dat(2),16) + ishft(dat(3),10)+ & @@ -529,13 +604,21 @@ subroutine packbits(dbits,nsymd,m0,sym) iand(ishft(dat(10),-4),3) ng=ishft(iand(dat(10),15),12) + ishft(dat(11),6) + dat(12) + +!print *, 'UNPACKMSG PACKED: nc1=',nc1,' nc2=',nc2,' ng=',ng, ' dat=', & +! dat(1),dat(2),dat(3),dat(4),dat(5),dat(6),dat(7),dat(8),dat(9), & +! dat(10),dat(11),dat(12) + if(ng.ge.32768) then call unpacktext(nc1,nc2,ng,msg) go to 100 endif + +!print *, 'UNPACKMSG BEFORE unpackcall nc1: nc1=',nc1,' iv2(before)=',iv2 +call unpackcall(nc1,c1,iv2,psfx) +!print *, 'UNPACKMSG AFTER unpackcall nc1: iv2=',iv2,' c1="',trim(c1),'" psfx="',psfx,'"' - call unpackcall(nc1,c1,iv2,psfx) if(iv2.eq.0) then ! This is an "original JT65" message if(nc1.eq.NBASE+1) c1='CQ ' @@ -548,7 +631,10 @@ subroutine packbits(dbits,nsymd,m0,sym) endif endif - call unpackcall(nc2,c2,junk1,junk2) +! print *, 'UNPACKMSG BEFORE unpackcall nc2: nc2=',nc2 +call unpackcall(nc2,c2,junk1,junk2) +!print *, 'UNPACKMSG AFTER unpackcall nc2: c2="',trim(c2),'" junk2="',junk2,'"' + call unpackgrid(ng,grid) if(iv2.gt.0) then @@ -625,12 +711,17 @@ subroutine packbits(dbits,nsymd,m0,sym) return end subroutine unpackmsg - subroutine packtext(msg,nc1,nc2,nc3) +subroutine packtext(msg, nc1, nc2, nc3) + + implicit none + + integer, parameter :: MASK28 = 2**28 - 1 + character(len=13), intent(in) :: msg + integer, intent(out) :: nc1, nc2, nc3 - parameter (MASK28=2**28 - 1) - character*13 msg - character*42 c - data c/'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ +-./?'/ + integer :: i, j + character(len=42) :: c + data c /'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ +-./?'/ nc1=0 nc2=0 @@ -673,11 +764,14 @@ subroutine packbits(dbits,nsymd,m0,sym) return end subroutine packtext - subroutine unpacktext(nc1,nc2,nc3,msg) + subroutine unpacktext(nc1, nc2, nc3, msg) + implicit none + integer, intent(inout) :: nc1, nc2, nc3 + character(len=22), intent(out) :: msg - character*22 msg - character*44 c - data c/'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ +-./?'/ + integer :: i, j + character(len=44) :: c + data c /'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ +-./?'/ nc3=iand(nc3,32767) !Remove the "plain text" bit if(iand(nc1,1).ne.0) nc3=nc3+32768 @@ -707,158 +801,30 @@ subroutine packbits(dbits,nsymd,m0,sym) return end subroutine unpacktext - subroutine getpfx1(callsign,k,nv2) - - character*12 callsign0,callsign,lof,rof - character*8 c - character addpfx*8,tpfx*4,tsfx*3 - logical ispfx,issfx,invalid - common/pfxcom/addpfx - include 'pfx.f90' - - callsign0=callsign - nv2=1 - iz=index(callsign,' ') - 1 - if(iz.lt.0) iz=12 - islash=index(callsign(1:iz),'/') - k=0 - ! if(k.eq.0) go to 10 !Tnx to DL9RDZ for reminder:this was for tests only! - c=' ' - if(islash.gt.0 .and. islash.le.(iz-4)) then - ! Add-on prefix - c=callsign(1:islash-1) - callsign=callsign(islash+1:iz) - do i=1,NZ - if(pfx(i)(1:4).eq.c) then - k=i - nv2=2 - go to 10 - endif - enddo - if(addpfx.eq.c) then - k=449 - nv2=2 - go to 10 - endif - - else if(islash.eq.(iz-1)) then - ! Add-on suffix - c=callsign(islash+1:iz) - callsign=callsign(1:islash-1) - do i=1,NZ2 - if(sfx(i).eq.c(1:1)) then - k=400+i - nv2=3 - go to 10 - endif - enddo - endif - - 10 if(islash.ne.0 .and.k.eq.0) then - ! Original JT65 would force this compound callsign to be treated as - ! plain text. In JT65v2, we will encode the prefix or suffix into nc1. - ! The task here is to compute the proper value of k. - lof=callsign0(:islash-1) - rof=callsign0(islash+1:) - llof=len_trim(lof) - lrof=len_trim(rof) - ispfx=(llof.gt.0 .and. llof.le.4) - issfx=(lrof.gt.0 .and. lrof.le.3) - invalid=.not.(ispfx.or.issfx) - if(ispfx.and.issfx) then - if(llof.lt.3) issfx=.false. - if(lrof.lt.3) ispfx=.false. - if(ispfx.and.issfx) then - i=ichar(callsign0(islash-1:islash-1)) - if(i.ge.ichar('0') .and. i.le.ichar('9')) then - issfx=.false. - else - ispfx=.false. - endif - endif - endif - - if(invalid) then - k=-1 - else - if(ispfx) then - tpfx=lof(1:4) - k=nchar(tpfx(1:1)) - k=37*k + nchar(tpfx(2:2)) - k=37*k + nchar(tpfx(3:3)) - k=37*k + nchar(tpfx(4:4)) - nv2=4 - i=index(callsign0,'/') - callsign=callsign0(:i-1) - callsign=callsign0(i+1:) - endif - if(issfx) then - tsfx=rof(1:3) - k=nchar(tsfx(1:1)) - k=37*k + nchar(tsfx(2:2)) - k=37*k + nchar(tsfx(3:3)) - nv2=5 - i=index(callsign0,'/') - callsign=callsign0(:i-1) - endif - endif - endif - - return - end subroutine getpfx1 - - subroutine getpfx2(k0,callsign) - - character callsign*12 - include 'pfx.f90' - character addpfx*8 - common/pfxcom/addpfx - - k=k0 - if(k.gt.450) k=k-450 - if(k.ge.1 .and. k.le.NZ) then - iz=index(pfx(k),' ') - 1 - callsign=pfx(k)(1:iz)//'/'//callsign - else if(k.ge.401 .and. k.le.400+NZ2) then - iz=index(callsign,' ') - 1 - callsign=callsign(1:iz)//'/'//sfx(k-400) - else if(k.eq.449) then - iz=index(addpfx,' ') - 1 - if(iz.lt.1) iz=8 - callsign=addpfx(1:iz)//'/'//callsign - endif - - return - end subroutine getpfx2 - - subroutine grid2k(grid,k) +subroutine grid2k(grid, k) + use grid2deg_mod, only: grid2deg + implicit none + character(len=6), intent(in) :: grid + integer, intent(out) :: k - character*6 grid + real :: xlong, xlat + integer :: nlong, nlat - call grid2deg(grid,xlong,xlat) - nlong=nint(xlong) - nlat=nint(xlat) - k=0 - if(nlat.ge.85) k=5*(nlong+179)/2 + nlat-84 + call grid2deg(grid, xlong, xlat) + nlong = nint(xlong) + nlat = nint(xlat) + k = 0 + if (nlat .ge. 85) k = 5*(nlong + 179)/2 + nlat - 84 +end subroutine grid2k - return - end subroutine grid2k - - subroutine k2grid(k,grid) - character grid*6 - nlong=2*mod((k-1)/5,90)-179 - if(k.gt.450) nlong=nlong+180 - nlat=mod(k-1,5)+ 85 - dlat=nlat - dlong=nlong - call deg2grid(dlong,dlat,grid) - return - end subroutine k2grid +subroutine grid2n(grid, n) + implicit none + character(len=4), intent(in) :: grid + integer, intent(out) :: n - subroutine grid2n(grid,n) - character*4 grid + integer :: i1, i2, i i1=ichar(grid(1:1))-ichar('A') i2=ichar(grid(3:3))-ichar('0') @@ -868,8 +834,12 @@ subroutine packbits(dbits,nsymd,m0,sym) return end subroutine grid2n - subroutine n2grid(n,grid) - character*4 grid +subroutine n2grid(n, grid) + implicit none + integer, intent(in) :: n + character(len=4), intent(out) :: grid + + integer :: i, i1, i2 if(n.gt.-31 .or. n.lt.-70) stop 'Error in n2grid' i=-(n+31) !NB: 0 <= i <= 39 @@ -883,33 +853,15 @@ subroutine packbits(dbits,nsymd,m0,sym) return end subroutine n2grid - function nchar(c) - - ! Convert ascii number, letter, or space to 0-36 for callsign packing. - character c*1 - - n=0 !Silence compiler warning - if(c.ge.'0' .and. c.le.'9') then - n=ichar(c)-ichar('0') - else if(c.ge.'A' .and. c.le.'Z') then - n=ichar(c)-ichar('A') + 10 - else if(c.ge.'a' .and. c.le.'z') then - n=ichar(c)-ichar('a') + 10 - else if(c.ge.' ') then - n=36 - else - Print*,'Invalid character in callsign ',c,' ',ichar(c) - stop - endif - nchar=n - - return - end function nchar - subroutine pack50(n1,n2,dat) + subroutine pack50(n1, n2, dat) + use iso_fortran_env, only: int8 + implicit none + integer, intent(in) :: n1, n2 + integer(int8), intent(out):: dat(:) - integer*1 dat(:),i1 + integer(int8) :: i1 i1=iand(ishft(n1,-20),255) !8 bits dat(1)=i1 @@ -933,17 +885,21 @@ subroutine packbits(dbits,nsymd,m0,sym) return end subroutine pack50 -subroutine packpfx(call1,n1,ng,nadd) +subroutine packpfx(call1, n1, ng, nadd) + implicit none + character(len=12), intent(in) :: call1 + integer, intent(out) :: n1, ng, nadd - character*12 call1,call0 - character*3 pfx - logical text + character(len=12) :: call0 + character(len=3) :: pfx + logical :: text + integer :: i1, i, nc, n i1=index(call1,'/') if(call1(i1+2:i1+2).eq.' ') then ! Single-character add-on suffix (maybe also fourth suffix letter?) call0=call1(:i1-1) - call packcall(call0,n1,text) + call packcall(call0(1:6),n1,text) nadd=1 nc=ichar(call1(i1+1:i1+1)) if(nc.ge.48 .and. nc.le.57) then @@ -958,7 +914,7 @@ subroutine packpfx(call1,n1,ng,nadd) else if(call1(i1+3:i1+3).eq.' ') then ! Two-character numerical suffix, /10 to /99 call0=call1(:i1-1) - call packcall(call0,n1,text) + call packcall(call0(1:6),n1,text) nadd=1 n=10*(ichar(call1(i1+1:i1+1))-48) + ichar(call1(i1+2:i1+2)) - 48 nadd=1 @@ -969,7 +925,7 @@ subroutine packpfx(call1,n1,ng,nadd) if(pfx(3:3).eq.' ') pfx=' '//pfx(1:2) if(pfx(3:3).eq.' ') pfx=' '//pfx(1:2) call0=call1(i1+1:) - call packcall(call0,n1,text) + call packcall(call0(1:6),n1,text) ng=0 do i=1,3 diff --git a/map65/libm65/pctile.f90 b/map65/libm65/pctile.f90 new file mode 100644 index 00000000..c9cb8bf6 --- /dev/null +++ b/map65/libm65/pctile.f90 @@ -0,0 +1,38 @@ +module pctile_mod + implicit none +contains + +subroutine pctile(x, npts, npct, xpct) + use shell_mod + implicit none + + !==== Dummy arguments ===================================================== + integer, intent(in) :: npts, npct + real, intent(in) :: x(npts) + real, intent(out) :: xpct + + !==== Local variables ===================================================== + real, allocatable :: tmp(:) + integer :: j + + !==== Input validation ==================================================== + if (npts < 1 .or. npct < 0 .or. npct > 100) then + xpct = 1.0 + return + endif + + allocate(tmp(npts)) + tmp = x + + call shell(npts, tmp) + + j = nint(npts * 0.01 * npct) + if (j < 1) j = 1 + if (j > npts) j = npts + + xpct = tmp(j) + + deallocate(tmp) +end subroutine pctile + +end module pctile_mod diff --git a/map65/libm65/pfx.f90 b/map65/libm65/pfx.f90 index 724b0f8a..a2940c47 100644 --- a/map65/libm65/pfx.f90 +++ b/map65/libm65/pfx.f90 @@ -1,10 +1,9 @@ - parameter (NZ=339) !Total number of prefixes - parameter (NZ2=12) !Total number of suffixes - character*1 sfx(NZ2) - character*5 pfx(NZ) - - data sfx/'P','0','1','2','3','4','5','6','7','8','9','A'/ - data pfx/ & +module pfx_data_mod + implicit none + integer, parameter :: NZ=339 !Total number of prefixes + integer, parameter :: NZ2=12 !Total number of suffixes + character(len=1) :: sfx(NZ2) = ['P','0','1','2','3','4','5','6','7','8','9','A'] + character(len=5) :: pfx(NZ) = [ & '1A ','1S ','3A ','3B6 ','3B8 ','3B9 ','3C ','3C0 ', & '3D2 ','3D2C ','3D2R ','3DA ','3V ','3W ','3X ','3Y ', & '3YB ','3YP ','4J ','4L ','4S ','4U1I ','4U1U ','4W ', & @@ -47,4 +46,5 @@ 'YJ ','YK ','YL ','YN ','YO ','YS ','YU ','YV ', & 'YV0 ','Z2 ','Z3 ','ZA ','ZB ','ZC4 ','ZD7 ','ZD8 ', & 'ZD9 ','ZF ','ZK1N ','ZK1S ','ZK2 ','ZK3 ','ZL ','ZL7 ', & - 'ZL8 ','ZL9 ','ZP ','ZS ','ZS8 ','KC4 ','E5 '/ + 'ZL8 ','ZL9 ','ZP ','ZS ','ZS8 ','KC4 ','E5 '] +end module pfx_data_mod diff --git a/map65/libm65/pfx_mod.f90 b/map65/libm65/pfx_mod.f90 new file mode 100644 index 00000000..c18ceb8e --- /dev/null +++ b/map65/libm65/pfx_mod.f90 @@ -0,0 +1,7 @@ +module pfx_mod + + implicit none + + character(len=8) :: addpfx = ' ' + +end module pfx_mod
\ No newline at end of file diff --git a/map65/libm65/pfxdump.f90 b/map65/libm65/pfxdump.f90 index 7587dbf7..894c26ed 100644 --- a/map65/libm65/pfxdump.f90 +++ b/map65/libm65/pfxdump.f90 @@ -1,13 +1,17 @@ -subroutine pfxdump(fname) - character*(*) fname - include 'pfx.f90' - - open(11,file=fname,status='unknown') - write(11,1001) sfx -1001 format('Supported Suffixes:'/(11('/',a1,2x))) - write(11,1002) pfx -1002 format(/'Supported Add-On DXCC Prefixes:'/(15(a5,1x))) - close(11) - - return -end subroutine pfxdump +module pfxdump_mod + implicit none +contains + subroutine pfxdump(fname) + use pfx_data_mod + implicit none + character*(*), intent(in) :: fname + + open(11,file=fname,status='unknown') + write(11,1001) sfx + 1001 format('Supported Suffixes:'/(11('/',a1,2x))) + write(11,1002) pfx + 1002 format(/'Supported Add-On DXCC Prefixes:'/(15(a5,1x))) + close(11) + + end subroutine pfxdump +end module pfxdump_mod diff --git a/map65/libm65/polfit.f90 b/map65/libm65/polfit.f90 index 33e8d44e..f963aab4 100644 --- a/map65/libm65/polfit.f90 +++ b/map65/libm65/polfit.f90 @@ -1,87 +1,98 @@ -subroutine polfit(y,npts,a) - -! Input: y(npts) !Expect npts=4 -! Output: a(1) = baseline -! a(2) = amplitude -! a(3) = theta (deg) - - real y(npts) - real a(3) - real deltaa(3) - integer ipk(1) - save - -! Set starting values: - a(1)=minval(y) - a(2)=maxval(y)-a(1) - ipk=maxloc(y) - a(3)=(ipk(1)-1)*45.0 - - deltaa(1:2)=0.1*a(2) - deltaa(3)=10.0 - nterms=3 - -! Start the iteration - chisqr=0. - chisqr0=1.e6 - iters=10 - - do iter=1,iters - do j=1,nterms - chisq1=fchisq_pol(y,npts,a) - fn=0. - delta=deltaa(j) -10 a(j)=a(j)+delta - chisq2=fchisq_pol(y,npts,a) - if(chisq2.eq.chisq1) go to 10 - if(chisq2.gt.chisq1) then - delta=-delta !Reverse direction - a(j)=a(j)+delta - tmp=chisq1 - chisq1=chisq2 - chisq2=tmp - endif -20 fn=fn+1.0 - a(j)=a(j)+delta - chisq3=fchisq_pol(y,npts,a) - if(chisq3.lt.chisq2) then - chisq1=chisq2 - chisq2=chisq3 - go to 20 - endif - -! Find minimum of parabola defined by last three points - delta=delta*(1./(1.+(chisq1-chisq2)/(chisq3-chisq2))+0.5) - a(j)=a(j)-delta - deltaa(j)=deltaa(j)*fn/3. -! write(*,4000) iter,j,a,deltaa,chisq2 -!4000 format(2i2,2(2x,3f8.2),f12.5) - enddo ! j=1,nterms - chisqr=fchisq_pol(y,npts,a) -! write(*,4000) 0,0,a,chisqr - if(chisqr.lt.1.0) exit - if(deltaa(1).lt.0.01*(a(2)-a(1)) .and. deltaa(2).lt.0.01*(a(2)-a(1)) & - .and. deltaa(3).lt.1.0) exit - if(chisqr/chisqr0.gt.0.99) exit - chisqr0=chisqr - enddo ! iter - a(3)=mod(a(3)+360.0,180.0) - - return -end subroutine polfit - -real function fchisq_pol(y,npts,a) - - real y(npts),a(3) - data rad/57.2957795/ +module polfit_mod + implicit none +contains + subroutine polfit(y,npts,a) + implicit none - chisq = 0. - do i=1,npts - theta=(i-1)*45.0 - yfit=a(1) + a(2)*cos((theta-a(3))/rad)**2 - chisq=chisq + (y(i) - yfit)**2 - enddo - fchisq_pol=chisq - - return -end function fchisq_pol + ! Input: y(npts) !Expect npts=4 + ! Output: a(1) = baseline + ! a(2) = amplitude + ! a(3) = theta (deg) + + integer, intent(in) :: npts + real, intent(in) :: y(npts) + real, intent(out) :: a(3) + + real :: deltaa(3) + integer :: ipk(1) + integer :: nterms, iters, iter, j + real :: chisq1, fn, delta, chisq2, tmp, chisq3, chisqr, chisqr0 + save + + ! Set starting values: + a(1)=minval(y) + a(2)=maxval(y)-a(1) + ipk=maxloc(y) + a(3)=(ipk(1)-1)*45.0 + + deltaa(1:2)=0.1*a(2) + deltaa(3)=10.0 + nterms=3 + + ! Start the iteration + chisqr=0. + chisqr0=1.e6 + iters=10 + + do iter=1,iters + do j=1,nterms + chisq1=fchisq_pol(y,npts,a) + fn=0. + delta=deltaa(j) + 10 a(j)=a(j)+delta + chisq2=fchisq_pol(y,npts,a) + if(chisq2.eq.chisq1) go to 10 + if(chisq2.gt.chisq1) then + delta=-delta !Reverse direction + a(j)=a(j)+delta + tmp=chisq1 + chisq1=chisq2 + chisq2=tmp + endif + 20 fn=fn+1.0 + a(j)=a(j)+delta + chisq3=fchisq_pol(y,npts,a) + if(chisq3.lt.chisq2) then + chisq1=chisq2 + chisq2=chisq3 + go to 20 + endif + + ! Find minimum of parabola defined by last three points + delta=delta*(1./(1.+(chisq1-chisq2)/(chisq3-chisq2))+0.5) + a(j)=a(j)-delta + deltaa(j)=deltaa(j)*fn/3. + ! write(*,4000) iter,j,a,deltaa,chisq2 + !4000 format(2i2,2(2x,3f8.2),f12.5) + enddo ! j=1,nterms + chisqr=fchisq_pol(y,npts,a) + ! write(*,4000) 0,0,a,chisqr + if(chisqr.lt.1.0) exit + if(deltaa(1).lt.0.01*(a(2)-a(1)) .and. deltaa(2).lt.0.01*(a(2)-a(1)) & + .and. deltaa(3).lt.1.0) exit + if(chisqr/chisqr0.gt.0.99) exit + chisqr0=chisqr + enddo ! iter + a(3)=mod(a(3)+360.0,180.0) + + end subroutine polfit + + real function fchisq_pol(y,npts,a) + implicit none + integer, intent(in) :: npts + real, intent(in) :: y(npts),a(3) + real :: rad + data rad/57.2957795/ + integer :: i + real :: chisq, theta, yfit + + chisq = 0. + do i=1,npts + theta=(i-1)*45.0 + yfit=a(1) + a(2)*cos((theta-a(3))/rad)**2 + chisq=chisq + (y(i) - yfit)**2 + enddo + fchisq_pol=chisq + + end function fchisq_pol +end module polfit_mod diff --git a/map65/libm65/posix_event_shim.c b/map65/libm65/posix_event_shim.c new file mode 100644 index 00000000..e316ea7e --- /dev/null +++ b/map65/libm65/posix_event_shim.c @@ -0,0 +1,65 @@ +// posix_event_shim.c +#include <pthread.h> +#include <stdlib.h> + +typedef struct { + pthread_mutex_t mutex; + pthread_cond_t cond; + int signaled; // 0 = non-signaled, 1 = signaled +} posix_event_t; + +void* win_create_event(void) +{ + posix_event_t* ev = malloc(sizeof(posix_event_t)); + if (!ev) return NULL; + + pthread_mutex_init(&ev->mutex, NULL); + pthread_cond_init(&ev->cond, NULL); + ev->signaled = 0; + + return ev; +} + +int win_set_event(void* h) +{ + posix_event_t* ev = (posix_event_t*)h; + pthread_mutex_lock(&ev->mutex); + + ev->signaled = 1; + pthread_cond_signal(&ev->cond); // auto-reset: wake ONE waiter + + pthread_mutex_unlock(&ev->mutex); + return 1; +} + +int win_reset_event(void* h) +{ + posix_event_t* ev = (posix_event_t*)h; + pthread_mutex_lock(&ev->mutex); + ev->signaled = 0; + pthread_mutex_unlock(&ev->mutex); + return 1; +} + +int win_wait_for_single_object(void* h) +{ + posix_event_t* ev = (posix_event_t*)h; + pthread_mutex_lock(&ev->mutex); + + while (!ev->signaled) + pthread_cond_wait(&ev->cond, &ev->mutex); + + // Auto-reset: clear signaled state immediately + ev->signaled = 0; + + pthread_mutex_unlock(&ev->mutex); + return 0; +} + +void win_close_event(void* h) +{ + posix_event_t* ev = (posix_event_t*)h; + pthread_mutex_destroy(&ev->mutex); + pthread_cond_destroy(&ev->cond); + free(ev); +} diff --git a/map65/libm65/pr_mod.f90 b/map65/libm65/pr_mod.f90 new file mode 100644 index 00000000..4913875d --- /dev/null +++ b/map65/libm65/pr_mod.f90 @@ -0,0 +1,9 @@ +module pr_mod + use iso_fortran_env, only: real32 + + implicit none + + real(real32) :: pr(126) + integer :: mdat(126),mref(126,2),mdat2(126),mref2(126,2) + +end module pr_mod
\ No newline at end of file diff --git a/map65/libm65/ptt.c b/map65/libm65/ptt.c index 0f99d1be..b2c6cb48 100644 --- a/map65/libm65/ptt.c +++ b/map65/libm65/ptt.c @@ -5,7 +5,7 @@ int ptt_(int *nport, int *ntx, int *iptt) { static HANDLE hFile; static int open=0; - char s[10]; + char s[64]; int i3=0,i4=0,i5=0,i6=0,i9=0,i00=0; if(*nport==0) { @@ -14,13 +14,19 @@ int ptt_(int *nport, int *ntx, int *iptt) } if(*ntx && (!open)) { - sprintf(s,"COM%d",*nport); - hFile=CreateFile(TEXT(s),GENERIC_WRITE,0,NULL,OPEN_EXISTING, + if (*nport < 10) + snprintf(s, sizeof(s), "COM%d", *nport); + else + snprintf(s, sizeof(s), "\\\\.\\COM%d", *nport); + + hFile = CreateFileA(s, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,NULL); + if(hFile==INVALID_HANDLE_VALUE) { // printf("PTT: Cannot open COM port %d.\n",*nport); return 1; } + open=1; } diff --git a/map65/libm65/ptt_unix.c b/map65/libm65/ptt_unix.c index 1c583f64..0787308b 100644 --- a/map65/libm65/ptt_unix.c +++ b/map65/libm65/ptt_unix.c @@ -1,13 +1,6 @@ /* * WSJT is Copyright (c) 2001-2006 by Joseph H. Taylor, Jr., K1JT, * and is licensed under the GNU General Public License (GPL). - * - * Code used from cwdaemon for parallel port ptt only. - * - * cwdaemon - morse sounding daemon for the parallel or serial port - * Copyright (C) 2002 -2005 Joop Stakenborg <pg4i@amsat.org> - * and many authors, see the AUTHORS file. - * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or @@ -22,41 +15,13 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ -# if HAVE_STDIO_H # include <stdio.h> -#endif -#if STDC_HEADERS -# include <stdlib.h> -# include <stddef.h> -#else -# if HAVE_STDLIB_H # include <stdlib.h> -# endif -#endif -#if HAVE_UNISTD_H -# include <unistd.h> -#endif -#if HAVE_SYS_STAT_H -# include <sys/stat.h> -#endif -#if HAVE_SYS_IOCTL_H +# include <unistd.h> +#include <fcntl.h> # include <sys/ioctl.h> -#endif -#if HAVE_FCNTL_H -# include <fcntl.h> -#endif - -#ifdef HAVE_LINUX_PPDEV_H -# include <linux/ppdev.h> -# include <linux/parport.h> -#endif -#ifdef HAVE_DEV_PPBUS_PPI_H -# include <dev/ppbus/ppi.h> -# include <dev/ppbus/ppbconf.h> -#endif - -int lp_reset (int fd); -int lp_ptt (int fd, int onoff); +#include <errno.h> +#include <string.h> #ifdef HAVE_SYS_STAT_H # include <sys/stat.h> @@ -66,14 +31,9 @@ int lp_ptt (int fd, int onoff); #endif #include <string.h> -/* parport functions */ -int dev_is_parport(int fd); -int ptt_parallel(int fd, int *ntx, int *iptt); int ptt_serial(int fd, int *ntx, int *iptt); -int fd=-1; /* Used for both serial and parallel */ - /* * ptt_ * @@ -81,83 +41,61 @@ int fd=-1; /* Used for both serial and parallel */ * * Inputs * unused Unused, to satisfy old windows calling convention - * ptt_port device name serial or parallel + * ptt_port device name * ntx pointer to fortran command on or off * iptt pointer to fortran command status on or off * Returns - non 0 if error */ -/* Tiny state machine */ -#define STATE_PORT_CLOSED 0 -#define STATE_PORT_OPEN_PARALLEL 1 -#define STATE_PORT_OPEN_SERIAL 2 +static char ptt_override[256] = {0}; +static int ptt_override_valid = 0; + +void ptt_set_override(const char *path) +{ + if (path && *path) { + strncpy(ptt_override, path, sizeof(ptt_override)-1); + ptt_override_valid = 1; + } else { + ptt_override_valid = 0; + } +} + +static int fd = -1; -//int ptt_(int *unused, char *ptt_port, int *ntx, int *iptt) -int ptt_(int *unused, int *ntx, int *iptt) +int ptt_(int *nport, int *ntx, int *iptt) { - static int state=0; - char *p; + (void)nport; +// ptt_log("ptt_unix: entry nport=%d ntx=%d iptt=%d", *nport, *ntx, *iptt); -// ### Temporary: - char* ptt_port; - if(*unused != -99) { + // PTT disabled + if (!ptt_override_valid) { *iptt=*ntx; return 0; } -// ### - - /* In the very unlikely event of a NULL pointer, just return. - * Yes, I realise this should not be possible in WSJT. - */ - if (ptt_port == NULL) { - *iptt = *ntx; - return (0); - } - - switch (state) { - case STATE_PORT_CLOSED: - /* Remove trailing ' ' */ - if ((p = strchr(ptt_port, ' ')) != NULL) - *p = '\0'; + const char *ptt_port = ptt_override; - /* If all that is left is a '\0' then also just return */ - if (*ptt_port == '\0') { - *iptt = *ntx; - return(0); + // Open once, keep open + if (fd < 0) { + fd = open(ptt_port, O_RDWR | O_NONBLOCK); + if (fd < 0) { +// ptt_log("ptt_unix: open failed errno=%d (%s)", errno, strerror(errno)); + return 1; + } +// ptt_log("ptt_unix: open OK fd=%d", fd); + + // *** PATCH: Force RTS+DTR LOW immediately after open *** + int status = 0; + if (ioctl(fd, TIOCMGET, &status) == 0) { + status &= ~(TIOCM_RTS | TIOCM_DTR); + ioctl(fd, TIOCMSET, &status); +// ptt_log("ptt_unix: forced RTS/DTR LOW after open, status=0x%x", status); } - - if ((fd = open(ptt_port, O_RDWR|O_NONBLOCK)) < 0) { - fprintf(stderr, "Can't open %s.\n", ptt_port); - return (1); } - - if (dev_is_parport(fd)) { - state = STATE_PORT_OPEN_PARALLEL; - lp_reset(fd); - ptt_parallel(fd, ntx, iptt); - } else { - state = STATE_PORT_OPEN_SERIAL; ptt_serial(fd, ntx, iptt); + return 0; } - break; - - case STATE_PORT_OPEN_PARALLEL: - ptt_parallel(fd, ntx, iptt); - break; - case STATE_PORT_OPEN_SERIAL: - ptt_serial(fd, ntx, iptt); - break; - - default: - close(fd); - fd = -1; - state = STATE_PORT_CLOSED; - break; - } - return(0); -} /* * ptt_serial @@ -169,237 +107,40 @@ int ptt_(int *unused, int *ntx, int *iptt) * iptt - pointer to fortran command status on or off */ -int -ptt_serial(int fd, int *ntx, int *iptt) -{ - int control = TIOCM_RTS | TIOCM_DTR; - -#if defined (TIOCMBIS) && defined (TIOCMBIS) - if(*ntx) { - ioctl(fd, TIOCMBIS, &control); /* Set DTR and RTS */ - *iptt = 1; - } else { - ioctl(fd, TIOCMBIC, &control); - *iptt = 0; - } -#else - unsigned y; - ioctl(fd, TIOCMGET, &y); - if (*ntx) { - y |= control; - } else { - y &= ~control; - } - ioctl(fd, TIOCMSET, &y); -#endif - return(0); -} - - -/* parport functions */ - -/* - * dev_is_parport(fd): - * - * inputs - Already open fd - * output - 1 if parallel port, 0 if not - * side effects - Unfortunately, this is platform specific. - */ - -#if defined(HAVE_LINUX_PPDEV_H) /* Linux (ppdev) */ - -int -dev_is_parport(int fd) -{ - struct stat st; - int m; - - if ((fstat(fd, &st) == -1) || - ((st.st_mode & S_IFMT) != S_IFCHR) || - (ioctl(fd, PPGETMODE, &m) == -1)) - return(0); - - return(1); -} - -#elif defined(HAVE_DEV_PPBUS_PPI_H) /* FreeBSD (ppbus/ppi) */ int -dev_is_parport(int fd) -{ - struct stat st; - unsigned char c; - - if ((fstat(fd, &st) == -1) || - ((st.st_mode & S_IFMT) != S_IFCHR) || - (ioctl(fd, PPISSTATUS, &c) == -1)) - return(0); - - return(1); -} - -#else /* Fallback (nothing) */ - -int -dev_is_parport(int fd) -{ - return(0); -} - -#endif -/* Linux wrapper around PPFCONTROL */ -#ifdef HAVE_LINUX_PPDEV_H -static void -parport_control (int fd, unsigned char controlbits, int values) +ptt_serial(int fd, int *ntx, int *iptt) { - struct ppdev_frob_struct frob; - frob.mask = controlbits; - frob.val = values; +int status; - if (ioctl (fd, PPFCONTROL, &frob) == -1) - { - fprintf(stderr, "Parallel port PPFCONTROL"); - exit (1); - } +if (ioctl(fd, TIOCMGET, &status) < 0) { +// ptt_log("TIOCMGET failed errno=%d (%s)", errno, strerror(errno)); + return 1; } -#endif - -/* FreeBSD wrapper around PPISCTRL */ -#ifdef HAVE_DEV_PPBUS_PPI_H -static void -parport_control (int fd, unsigned char controlbits, int values) -{ - unsigned char val; - - if (ioctl (fd, PPIGCTRL, &val) == -1) - { - fprintf(stderr, "Parallel port PPIGCTRL"); - exit (1); - } - val &= ~controlbits; - val |= values; - - if (ioctl (fd, PPISCTRL, &val) == -1) - { - fprintf(stderr, "Parallel port PPISCTRL"); - exit (1); - } + if(*ntx) { + status |= (TIOCM_RTS | TIOCM_DTR); // PTT ON + } else { + status &= ~(TIOCM_RTS | TIOCM_DTR); // PTT OFF } -#endif - -/* Initialise a parallel port, given open fd */ -int -lp_init (int fd) -{ -#ifdef HAVE_LINUX_PPDEV_H - int mode; -#endif - -#ifdef HAVE_LINUX_PPDEV_H - mode = PARPORT_MODE_PCSPP; - if (ioctl (fd, PPSETMODE, &mode) == -1) - { - fprintf(stderr, "Setting parallel port mode"); - close (fd); - return(-1); - } - - if (ioctl (fd, PPEXCL, NULL) == -1) - { - fprintf(stderr, "Parallel port is already in use.\n"); - close (fd); - return(-1); - } - if (ioctl (fd, PPCLAIM, NULL) == -1) - { - fprintf(stderr, "Claiming parallel port.\n"); - fprintf(stderr, "HINT: did you unload the lp kernel module?"); - close (fd); - return(-1); - } - - /* Enable CW & PTT - /STROBE bit (pin 1) */ - parport_control (fd, PARPORT_CONTROL_STROBE, PARPORT_CONTROL_STROBE); -#endif -#ifdef HAVE_DEV_PPBUS_PPI_H - parport_control (fd, STROBE, STROBE); -#endif - lp_reset (fd); - return(0); +if (ioctl(fd, TIOCMSET, &status) < 0) { +// ptt_log("TIOCMSET failed errno=%d (%s)", errno, strerror(errno)); + return 1; } -/* release ppdev and close port */ -int -lp_free (int fd) -{ -#ifdef HAVE_LINUX_PPDEV_H - lp_reset (fd); - - /* Disable CW & PTT - /STROBE bit (pin 1) */ - parport_control (fd, PARPORT_CONTROL_STROBE, 0); - - ioctl (fd, PPRELEASE); -#endif -#ifdef HAVE_DEV_PPBUS_PPI_H - /* Disable CW & PTT - /STROBE bit (pin 1) */ - parport_control (fd, STROBE, 0); -#endif - close (fd); - return(0); -} +//ptt_log("TIOCMSET OK status=0x%x", status); +*iptt = *ntx; +return 0; -/* set to a known state */ -int -lp_reset (int fd) -{ -#if defined (HAVE_LINUX_PPDEV_H) || defined (HAVE_DEV_PPBUS_PPI_H) - lp_ptt (fd, 0); -#endif - return(0); } -/* SSB PTT keying - /INIT bit (pin 16) (inverted) */ -int -lp_ptt (int fd, int onoff) +void ptt_close(void) { -#ifdef HAVE_LINUX_PPDEV_H - if (onoff == 1) - parport_control (fd, PARPORT_CONTROL_INIT, - PARPORT_CONTROL_INIT); - else - parport_control (fd, PARPORT_CONTROL_INIT, 0); -#endif -#ifdef HAVE_DEV_PPBUS_PPI_H - if (onoff == 1) - parport_control (fd, nINIT, - nINIT); - else - parport_control (fd, nINIT, 0); -#endif - return(0); + if (fd >= 0) { + close(fd); + fd = -1; +// ptt_log("ptt_unix: closed fd"); + } } -/* - * ptt_parallel - * - * generic parallel unix PTT routine called indirectly from Fortran - * - * fd - already opened file descriptor - * ntx - pointer to fortran command on or off - * iptt - pointer to fortran command status on or off - */ - -int -ptt_parallel(int fd, int *ntx, int *iptt) -{ - if(*ntx) { - lp_ptt(fd, 1); - *iptt=1; - } else { - lp_ptt(fd, 0); - *iptt=0; - } - return(0); -} diff --git a/map65/libm65/q65b.F90 b/map65/libm65/q65b.F90 new file mode 100644 index 00000000..7f28f0f3 --- /dev/null +++ b/map65/libm65/q65b.F90 @@ -0,0 +1,437 @@ +! This routine provides an interface between MAP65 and the Q65 decoder +! in WSJT-X. All arguments are input data obtained from the MAP65 GUI. +! Raw Rx data are available as the 96 kHz complex spectrum ca(MAXFFT1) +! in cacb_mod. If xpol is true, we also have cb(MAXFFT1) for the +! orthogonal polarization. Decoded messages are sent back to the GUI +! on stdout. + + module q65b_mod + implicit none + contains + + subroutine write_wav_header(unit, nsamp, fs) + integer, intent(in) :: unit, nsamp, fs + integer :: datasize, file_size + + datasize = nsamp * 2 ! 16-bit samples + file_size = 36 + datasize + + write(unit) 'RIFF' + write(unit) file_size + write(unit) 'WAVE' + write(unit) 'fmt ' + write(unit) 16 ! PCM header size + write(unit) 1 ! PCM format + write(unit) 1 ! mono + write(unit) fs ! sample rate + write(unit) fs*2 ! byte rate + write(unit) 2 ! block align + write(unit) 16 ! bits per sample + write(unit) 'data' + write(unit) datasize + end subroutine write_wav_header + + subroutine q65b(nutc, nqd, nxant, fcenter, nfcal, nfsample, ikhz, mousedf, ntol, xpol, configured_dphi_deg, & + mycall0, mygrid, hiscall0, hisgrid, mode_q65, f0, fqso, newdat, nagain, & + max_drift, ndop00, idec, cursor_fallback) + + use iso_c_binding + use q65_decode + use wideband_sync + use timer_module, only: timer + use debug_log + use stdout_channel_mod, only: write_stdout + use decodes_mod, only: ldecoded, ndecodes + use cacb_mod + use four2a_mod + use txpol_mod + use iso_fortran_env, only: real64, int16 + use map65_mmdec_mod + use npar_ptrs_mod, only: nrate_active, nfft_big_active, nfft_active, t_start, abort_decode, & + manualDecodeFlag, ndepth + use sec_midn_mod, only: sec_midn + + implicit none + + !==== Dummy arguments ===================================================== + integer, intent(in) :: nutc + integer, intent(in) :: nqd + integer, intent(in) :: nxant + real(real64), intent(in) :: fcenter + integer, intent(in) :: nfcal + integer, intent(in) :: nfsample + integer, intent(in) :: ikhz + integer, intent(in) :: mousedf + integer, intent(in) :: ntol + logical, intent(in) :: xpol + integer, intent(in) :: configured_dphi_deg + character(len=12), intent(in) :: mycall0 + character(len=6), intent(in) :: mygrid + character(len=12), intent(in) :: hiscall0 + character(len=6), intent(in) :: hisgrid + integer, intent(in) :: mode_q65 + real(real64), intent(in) :: f0 + real, intent(in) :: fqso + integer, intent(in) :: newdat + integer, intent(in) :: nagain + integer, intent(in) :: max_drift + integer, intent(in) :: ndop00 + integer, intent(out) :: idec + logical, optional, intent(in) :: cursor_fallback + + !==== Local parameters ==================================================== + ! MAXFFT1/2 are *max* sizes; actual runtime sizes are derived below. + ! MAXFFT1 must be = nfft_big_active; MAXFFT2 must be = the + ! downsampled-FFT length at the highest supported rate. + integer, parameter :: MAXFFT1 = 56*192000 + integer, parameter :: MAXFFT2 = 336000*2 + integer, parameter :: NMAX = 60*12000 + real(real64), parameter :: RAD = 57.2957795 + + !==== Local variables ===================================================== + integer(int16) :: iwave(300*12000) + complex :: cx(0:MAXFFT2-1), cy(0:MAXFFT2-1), cz(0:MAXFFT2) + integer :: ipk1(1) + ! Small, fixed bin radius for the automatic-candidate ipk search (see + ! the note below at "for a wideband candidate"). Deliberately + ! independent of the GUI's Ftol (ntol) -- this only needs to absorb + ! wb_sync's own low-SNR bin-selection noise, not accommodate arbitrary + ! user-configured search widths. + integer, parameter :: IPK_LOCAL_BINS = 5 + integer :: i, ia, ib, ifreq, ikhz1, ipk, ipol + integer :: j, ja, jb, k0, mhz, ndf, nfft1, nfft2 + integer :: npol, nq65df, nsubmode, ntxpol, nutc00, nh + integer :: nfa, nfb + integer :: k0_click, mousedf_gate + real :: df, df3, dphi, f_ipk, f_mouse, fac + real :: combine_poldeg, freq1_00, frx, fsked, poldeg, r, snr1 + real(real64) :: freq0, freq1 + character(len=12) :: mycall, hiscall + character(len=4) :: grid4 + character(len=28) :: msg00 + character(len=1) :: cp + character(len=2) :: cmode + character(len=256) :: linenew + + integer :: t_now, t_rate + logical :: search_cursor + + ! From q65_decode / wideband_sync / globals: + ! real :: xdt0 + ! integer :: nsnr0, nfreq0, nkhz_center + ! character(len=3) :: cq0 + ! character(len=28) :: msg0 + ! type(sync_type) :: sync(:) + ! These are assumed to be provided by the used modules. + + data nutc00 /-1/ + data msg00 /' '/ + save + + idec = -1 + nsnr0 = -99 + msg0 = ' ' + cq0 = ' ' + xdt0 = 0.0 + nfreq0 = 0 + search_cursor = manualDecodeFlag .ne. 0 + if (present(cursor_fallback)) search_cursor = search_cursor .or. cursor_fallback + + call system_clock(t_now, t_rate) + if (real(t_now - t_start)/real(t_rate) > 40.0) then + abort_decode = .true. + return + endif + + ! ca/cb storage is sized at MAXFFT1 in cacb_mod; the *active* big FFT + ! length is nfft_big_active, set from C++ via set_runtime_params_(). + call init_cacb(MAXFFT1) + + ! wideband_sync expects the active symspec FFT length + call init_wideband_sync() + + + if (mycall0(1:1) .ne. ' ') mycall = mycall0 + if (hiscall0(1:1) .ne. ' ') hiscall = hiscall0 + if (hisgrid(1:4) .ne. ' ') grid4 = hisgrid(1:4) + +! Find best frequency and ipol from sync_dat, the "orange sync curve". + ! df3 is the bin width of the symspec FFT (savg), based on the + ! active runtime rate and FFT length. + df3 = real(nrate_active)/real(nfft_active) + ifreq = nint((1000.0*f0)/df3) + + ! Candidate frequencies need only local bin refinement. Cursor + ! targets, including the no-candidate fallback, need the selected Ftol. + ! Bin-quantized weak-signal candidates can miss the true sync peak; + ! retain the local five-bin search rather than testing one exact bin. + if (search_cursor) then + ia = nint(ifreq - ntol/df3) + ib = nint(ifreq + ntol/df3) + if (ia >= 1 .and. ia <= nfft_active .and. ib >= 1 .and. ib <= nfft_active) then + ipk1 = maxloc(sync(ia:ib)%ccfmax) + else + go to 901 + endif + ipk = ia + ipk1(1) - 1 + else + ia = max(1, ifreq - IPK_LOCAL_BINS) + ib = min(nfft_active, ifreq + IPK_LOCAL_BINS) + if (ifreq >= 1 .and. ifreq <= nfft_active .and. ib >= ia) then + ipk1 = maxloc(sync(ia:ib)%ccfmax) + ipk = ia + ipk1(1) - 1 + else + go to 901 + endif + endif + snr1 = sync(ipk)%ccfmax + + ! TEMP diagnostic 2026-09-09 for the two-close-Q65-signals investigation. + call dbg('q65b: ipk check at t=' // rtoa(sec_midn()) // & + ' nqd=' // itoa(nqd) // ' f0=' // rtoa(real(f0)) // ' ntol=' // itoa(ntol) // & + ' ifreq=' // itoa(ifreq) // ' ipk=' // itoa(ipk) // & + ' ldecoded(ipk)=' // itoa(merge(1,0,ldecoded(ipk))) // & + ' manualDecodeFlag=' // itoa(manualDecodeFlag) // ' nagain=' // itoa(nagain)) + ! ldecoded(ipk) exists to keep the wideband scan from repeatedly + ! re-decoding a bin it already got a result from. A manual click is a + ! deliberate, targeted request to decode at this exact bin, so it must + ! not be skipped just because an earlier wideband pass happened to + ! visit the same bin first. + if (ldecoded(ipk) .and. manualDecodeFlag .eq. 0) then + call dbg('q65b: SKIPPED (ldecoded already set) at t=' // rtoa(sec_midn()) // & + ' ipk=' // itoa(ipk)) + go to 900 + endif + snr1 = sync(ipk)%ccfmax + ! ipol was never declared and its value is never used + ipol = 1 + if (xpol) ipol = sync(ipk)%ipol + + ! Runtime big-FFT length: nfft_big_active is 56 * nrate_active, + ! set from C++ at startup. Clamp to MAXFFT1 for safety. + nfft1 = min(nfft_big_active, MAXFFT1) + + ! Use a fixed small-FFT length that matches the legacy 96 kHz + ! geometry and stays within MAXFFT2 at all supported rates. + nfft2 = min(336000, MAXFFT2) + + ! Preserve the legacy 95238 special case; if you still use it, + ! override the derived sizes with the historical ones. + if (nfsample .eq. 95238) then + nfft1 = min(5120000, MAXFFT1) + nfft2 = min(322560, MAXFFT2) + endif + + ! Bin width of the big FFT: use the active runtime rate instead + ! of a hardcoded 96000. The 95238 special case is preserved. + df = real(nrate_active)/real(nfft1) + if (nfsample .eq. 95238) df = 96000.0/real(nfft1) + + nh = nfft2/2 + f_mouse = 1000.0*(fqso + real(nrate_active/2000.0)) + mousedf + f_ipk = ipk*df3 + ! k0 used to come from f_ipk (ipk*df3), i.e. re-derived from the coarse, + ! JT65-oriented "orange sync curve" bin (df3 ~ 2.9 Hz resolution) rather + ! than from the candidate's own already-refined frequency. For a + ! wideband Q65 candidate, f0 (set by the caller from cand()%f, which + ! wb_sync already computed with sub-bin precision) is a strictly better + ! estimate of the true signal frequency than re-quantizing through ipk + ! -- and the difference matters here because the actual decode below + ! only searches a tight +/-10 Hz window (nfa=990..1010) around k0. + ! Use f0 directly, same as the manual-click/nagain path already does + ! via f_mouse below. + k0 = nint((1000.0*f0 - 1000.0)/df) + ! ipk (and therefore f_ipk) comes from maxloc'ing the JT65-oriented + ! "orange sync curve" over the whole +/-ntol window -- fine for a + ! wideband scan, but if a strong JT65 signal happens to sit anywhere + ! in that window it will always win, even over an equal-strength Q65 + ! signal, because that curve doesn't score Q65 signals the same way. + ! A manual click already tells us exactly where to look, so center + ! the analysis window on the actual clicked frequency (f_mouse, which + ! properly includes mousedf) instead of trusting that curve. + ! nagain=1 (Decode button / Find Delta Phi repeat) runs the same + ! per-candidate loop over real, precise wb_sync candidates that + ! automatic decoding does -- f0 is not an imprecise mousefqso click + ! there, so forcing k0 to f_mouse would make every candidate in that + ! loop decode the same narrow window near the cursor instead of its + ! own frequency. The one nagain=1 case where f0 genuinely comes from + ! mousefqso (the "no candidate found" fallback in map65a.f90) already + ! sets f0 = mousefqso + mousedf directly, so the default k0 below + ! lands on the same point anyway. + if (manualDecodeFlag .ne. 0) k0 = nint((f_mouse - 1000.0)/df) + + if (k0 .lt. nh .or. k0 .gt. nfft1 - nfft2 + 1) then + if (manualDecodeFlag .ne. 0) & + call dbg('q65b manual: NOT ATTEMPTED, k0=' // itoa(k0) // ' outside ' // & + itoa(nh) // '..' // itoa(nfft1 - nfft2 + 1)) + go to 900 + endif + ! Likewise, snr1 is the sync-curve strength at ipk, which for a manual + ! click may be the wrong bin entirely (see above) -- don't let it gate + ! a manual decode attempt. Let q65_decode's own Q65-native search + ! (below) determine success or failure instead. + if (snr1 .lt. 1.5 .and. manualDecodeFlag .eq. 0) go to 900 !### Threshold needs work? ### + + fac = 1.0/nfft2 + cx(0:nfft2 - 1) = ca(k0:k0 + nfft2 - 1) + cx = fac*cx + if (xpol) then + cy(0:nfft2 - 1) = cb(k0:k0 + nfft2 - 1) + cy = fac*cy + if (configured_dphi_deg .ne. 0) then + dphi = configured_dphi_deg/RAD + ! The sync weights describe the phase-corrected basis from symspec. + cy(0:nfft2 - 1) = cmplx(cos(dphi), sin(dphi))*cy(0:nfft2 - 1) + endif + endif + +! Here cx and cy (if xpol) are frequency-domain data around the selected +! QSO frequency, taken from the full-length FFT computed in filbig(). +! Values for fsample, nfft1, nfft2, df, and the downsampled data rate +! are as follows: + +! fSample nfft1 df nfft2 fDownSampled +! (Hz) (Hz) (Hz) +!---------------------------------------------------- +! 96000 5376000 0.017857143 336000 6000.000 +! 95238 5120000 0.018601172 322560 5999.994 + + poldeg = 0. + if (xpol) then + ! NB: still uses the (possibly wrong-bin, see k0 above) ipk for + ! manual clicks in xpol mode -- not exercised by current testing, + ! but worth revisiting if xpol manual decode misbehaves similarly. + poldeg = sync(ipk)%pol + combine_poldeg = sync(ipk)%combine_pol + cz(0:MAXFFT2 - 1) = cos(combine_poldeg/RAD)*cx + sin(combine_poldeg/RAD)*cy + else + cz(0:MAXFFT2 - 1) = cx + endif + + cz(MAXFFT2) = 0. +! Roll off below 500 Hz and above 2500 Hz. + ja = nint(500.0/df) + jb = nint(2500.0/df) + do i = 0, ja + r = 0.5*(1.0 + cos(i*3.14159/ja)) + cz(ja - i) = r*cz(ja - i) + cz(jb + i) = r*cz(jb + i) + enddo + cz(ja + jb + 1:) = 0. + +!Transform to time domain (real), fsample=12000 Hz + call four2a(cz, 2*nfft2, 1, 1, -1) + do i = 0, nfft2 - 1 + j = nfft2 - 1 - i + iwave(2*i + 2) = int(max(-32768, min(32767, nint(real(cz(j))))), kind=2) + iwave(2*i + 1) = int(max(-32768, min(32767, nint(aimag(cz(j))))), kind=2) + enddo + + iwave(2*nfft2 + 1:) = 0 + + nsubmode = mode_q65 - 1 + nfa = 990 !Tight limits around ipk for the wideband decode + nfb = 1010 + if (search_cursor) then + nfa = max(100, 1000 - ntol) + nfb = min(2500, 1000 + ntol) + endif + +! NB: Frequency of ipk is now shifted to 1000 Hz. + + ! ndepth comes from npar_ptrs_mod, set from the GUI's Decode Depth + ! menu (see MainWindow::decode() -> setNdepth()). This used to be a + ! local variable "ndpth" hardwired to 3 here, which was never + ! connected to the GUI at all -- Q65 always ran at depth 3 + ! regardless of what the user selected. + call map65_mmdec(nutc, iwave, nqd, 60, nsubmode, nfa, nfb, 1000, ntol, & + newdat, nagain, max_drift, ndepth, mycall, hiscall0, hisgrid) + + MHz = fcenter + freq0 = MHz + 0.001d0*ikhz + + call dbg('q65b: map65_mmdec result at t=' // rtoa(sec_midn()) // & + ' nqd=' // itoa(nqd) // ' f0=' // rtoa(real(f0)) // ' ipk=' // itoa(ipk) // & + ' nsnr0=' // itoa(nsnr0)) + + if (nsnr0 .gt. -99) then + ldecoded(ipk) = .true. + nq65df = nint(1000*( 0.001*k0*df + nkhz_center - real(nrate_active)/2000.0 + 1.000 - 1.27046 - ikhz )) - nfcal + nq65df = nq65df + nfreq0 - 1000 + ! Gate comparison target, expressed in the same ikhz-relative frame + ! as nq65df above -- computed from f0 (the unambiguous target + ! frequency for this call, for both a manual click and a wideband + ! candidate) via the same k0/nq65df formula, rather than from raw + ! mousedf, which is relative to mousefqso and only matches ikhz's + ! frame when the target happens to already be sub-kHz. mousedf + ! itself is left untouched -- f_mouse/k0 above still need it in its + ! original, unmodified form. + k0_click = nint((1000.0*f0 - 1000.0)/df) + mousedf_gate = nint(1000*( 0.001*k0_click*df + nkhz_center - real(nrate_active)/2000.0 + & + 1.000 - 1.27046 - ikhz )) - nfcal + npol = nint(poldeg) + if (nxant .ne. 0) then + npol = npol - 45 + if (npol .lt. 0) npol = npol + 180 + endif + call txpol(xpol, msg0(1:28), mygrid, npol, nxant, ntxpol, cp) ! was 1:22 + ikhz1 = ikhz + ndf = nq65df + if (ndf .gt. 500) ikhz1 = ikhz + (nq65df + 500)/1000 + if (ndf .lt. -500) ikhz1 = ikhz + (nq65df - 500)/1000 + ndf = nq65df - 1000*(ikhz1 - ikhz) + + if (manualDecodeFlag .ne. 0) & + call dbg('q65b manual: decoded nq65df=' // itoa(nq65df) // ' mousedf_gate=' // & + itoa(mousedf_gate) // ' ntol=' // itoa(ntol) // ' nqd=' // itoa(nqd) // & + ' display gate ' // merge('PASSED', 'FAILED', & + nqd .eq. 1 .and. abs(nq65df - mousedf_gate) .lt. ntol)) + + if (nqd .eq. 1 .and. abs(nq65df - mousedf_gate) .lt. ntol) then + + write (linenew, '("!",I3.3,I5,I4,I6.4,F5.1,I5," : ",A28,A3,I4,1X,A1)') & + ikhz1, ndf, npol, nutc, xdt0, nsnr0, msg0(1:28), cq0, ntxpol, cp + call write_stdout(trim(linenew)//new_line('a')) + endif + +! Write to lu 26, for Messages and Band Map windows + cmode = ': ' + cmode(2:2) = char(ichar('A') + mode_q65 - 1) + freq1 = freq0 + 0.001d0*(ikhz1 - ikhz) + write (26, 1014) freq1, ndf, 0, 0, 0, xdt0, npol, 0, nsnr0, nutc, msg0(1:28), & + ':', cp, cmode ! was 1:22 +1014 format(f8.3, i5, 3i3, f5.1, i4, i3, i4, i5.4, 4x, a28, 1x, 2a1, 2x, a2) ! was a22 + +! Suppress writing duplicates (same time, decoded message, and frequency) +! to map65_rx.log + if (nutc .ne. nutc00 .or. msg0(1:28) .ne. msg00 .or. freq1 .ne. freq1_00) then +! Write to file map65_rx.log: + ndecodes = ndecodes + 1 + write (21, 1110) freq1, ndf, xdt0, npol, nsnr0, nutc, msg0(1:28), & + cmode(2:2), cq0 +1110 format(f8.3, i5, f5.1, 2i4, i5.4, 2x, a28, ': ', a1, 2x, a3) + nutc00 = nutc + msg00 = msg0(1:28) + freq1_00 = freq1 + frx = 0.001*k0*df + nkhz_center - real(nrate_active/2000.0) + 1.0 - 0.001*nfcal + fsked = frx - 0.001*ndop00/2.0 - 1.5 + write (12, 1120) nutc, fsked, xdt0, nsnr0, trim(msg0) +1120 format(i4.4, f9.3, f7.2, i5, 2x, a, i6) + endif + endif + +900 close (13) + close (17) + idec = -1 + ! cq0 is blank unless this call's own decode attempt set it (see the + ! reset at subroutine entry); only parse it when there's really a + ! digit there, otherwise there's nothing for READ to find. + if (cq0(2:2) .ne. ' ') read (cq0(2:2), *) idec + return +901 close (13) + close (17) + idec = -1 + return + end subroutine q65b + +end module q65b_mod diff --git a/map65/libm65/q65b.f90 b/map65/libm65/q65b.f90 deleted file mode 100644 index 77367b8f..00000000 --- a/map65/libm65/q65b.f90 +++ /dev/null @@ -1,205 +0,0 @@ -subroutine q65b(nutc,nqd,nxant,fcenter,nfcal,nfsample,ikhz,mousedf,ntol,xpol, & - mycall0,mygrid,hiscall0,hisgrid,mode_q65,f0,fqso,newdat,nagain, & - max_drift,nhsym,ndop00,idec) - -! This routine provides an interface between MAP65 and the Q65 decoder -! in WSJT-X. All arguments are input data obtained from the MAP65 GUI. -! Raw Rx data are available as the 96 kHz complex spectrum ca(MAXFFT1) -! in common/cacb. If xpol is true, we also have cb(MAXFFT1) for the -! orthogonal polarization. Decoded messages are sent back to the GUI -! on stdout. - -! use wavhdr - use q65_decode - use wideband_sync - use timer_module, only: timer - - parameter (MAXFFT1=5376000) !56*96000 - parameter (MAXFFT2=336000) !56*6000 (downsampled by 1/16) - parameter (NMAX=60*12000) - parameter (RAD=57.2957795) -! type(hdr) h !Header for the .wav file - integer*2 iwave(60*12000) - complex ca(MAXFFT1),cb(MAXFFT1) !FFTs of raw x,y data - complex cx(0:MAXFFT2-1),cy(0:MAXFFT2-1),cz(0:MAXFFT2) - logical xpol,ldecoded - integer ipk1(1) - real*8 fcenter,freq0,freq1 - character*12 mycall0,hiscall0 - character*12 mycall,hiscall - character*6 mygrid,hisgrid - character*4 grid4 - character*28 msg00 - character*80 line - character*80 wsjtx_dir - character*1 cp,cmode*2 - common/cacb/ca,cb - common/early/nhsym1,nhsym2,ldecoded(32768) - common/decodes/ndecodes - data nutc00/-1/,msg00/' '/ - save - - if(newdat.eq.1) nutc00=-1 - open(9,file='wsjtx_dir.txt',status='old') - read(9,'(a)') wsjtx_dir !Establish the working directory - close(9) - - if(mycall0(1:1).ne.' ') mycall=mycall0 - if(hiscall0(1:1).ne.' ') hiscall=hiscall0 - if(hisgrid(1:4).ne.' ') grid4=hisgrid(1:4) - -! Find best frequency and ipol from sync_dat, the "orange sync curve". - df3=96000.0/32768.0 - ifreq=nint((1000.0*f0)/df3) - ia=nint(ifreq-ntol/df3) - ib=nint(ifreq+ntol/df3) - ipk1=maxloc(sync(ia:ib)%ccfmax) - ipk=ia+ipk1(1)-1 - if(ldecoded(ipk)) go to 900 - snr1=sync(ipk)%ccfmax - ipol=1 - if(xpol) ipol=sync(ipk)%ipol - - nfft1=MAXFFT1 - nfft2=MAXFFT2 - df=96000.0/NFFT1 - if(nfsample.eq.95238) then - nfft1=5120000 - nfft2=322560 - df=96000.0/nfft1 - endif - nh=nfft2/2 - f_mouse=1000.0*(fqso+48.0) + mousedf - f_ipk=ipk*df3 - k0=nint((ipk*df3-1000.0)/df) - if(nagain.eq.1) k0=nint((f_mouse-1000.0)/df) - - if(k0.lt.nh .or. k0.gt.MAXFFT1-nfft2+1) go to 900 - if(snr1.lt.1.5) go to 900 !### Threshold needs work? ### - - fac=1.0/nfft2 - cx(0:nfft2-1)=ca(k0:k0+nfft2-1) - cx=fac*cx - if(xpol) then - cy(0:nfft2-1)=cb(k0:k0+nfft2-1) - cy=fac*cy - endif - -! Here cx and cy (if xpol) are frequency-domain data around the selected -! QSO frequency, taken from the full-length FFT computed in filbig(). -! Values for fsample, nfft1, nfft2, df, and the downsampled data rate -! are as follows: - -! fSample nfft1 df nfft2 fDownSampled -! (Hz) (Hz) (Hz) -!---------------------------------------------------- -! 96000 5376000 0.017857143 336000 6000.000 -! 95238 5120000 0.018601172 322560 5999.994 - - poldeg=0. - if(xpol) then - poldeg=sync(ipk)%pol - cz(0:MAXFFT2-1)=cos(poldeg/RAD)*cx + sin(poldeg/RAD)*cy - else - cz(0:MAXFFT2-1)=cx - endif - - cz(MAXFFT2)=0. -! Roll off below 500 Hz and above 2500 Hz. - ja=nint(500.0/df) - jb=nint(2500.0/df) - do i=0,ja - r=0.5*(1.0+cos(i*3.14159/ja)) - cz(ja-i)=r*cz(ja-i) - cz(jb+i)=r*cz(jb+i) - enddo - cz(ja+jb+1:)=0. - -!Transform to time domain (real), fsample=12000 Hz - call four2a(cz,2*nfft2,1,1,-1) - do i=0,nfft2-1 - j=nfft2-1-i - iwave(2*i+2)=nint(real(cz(j))) !Note the reversed order! - iwave(2*i+1)=nint(aimag(cz(j))) - enddo - iwave(2*nfft2+1:)=0 - -! open(30,file='000000_0001.wav',status='unknown',access='stream') -! h=default_header(12000,NMAX) -! write(30) h,iwave -! close(30) - - nsubmode=mode_q65-1 - nfa=990 !Tight limits around ipk for the wideband decode - nfb=1010 - if(nagain.eq.1) then !For nagain=1, use limits of +/- ntol - nfa=max(100,1000-ntol) - nfb=min(2500,1000+ntol) - endif - nsnr0=-99 !Default snr for no decode - ndpth=3 - -! NB: Frequency of ipk is now shifted to 1000 Hz. - call map65_mmdec(nutc,iwave,nqd,60,nsubmode,nfa,nfb,1000,ntol, & - newdat,nagain,max_drift,ndepth,mycall,hiscall0,hisgrid) - - MHz=fcenter - freq0=MHz + 0.001d0*ikhz - - if(nsnr0.gt.-99) then - ldecoded(ipk)=.true. - nq65df=nint(1000*(0.001*k0*df+nkhz_center-48.0+1.000-1.27046-ikhz))-nfcal - nq65df=nq65df + nfreq0 - 1000 - npol=nint(poldeg) - if(nxant.ne.0) then - npol=npol-45 - if(npol.lt.0) npol=npol+180 - endif - call txpol(xpol,msg0(1:28),mygrid,npol,nxant,ntxpol,cp) ! was 1:22 - ikhz1=ikhz - ndf=nq65df - if(ndf.gt.500) ikhz1=ikhz + (nq65df+500)/1000 - if(ndf.lt.-500) ikhz1=ikhz + (nq65df-500)/1000 - ndf=nq65df - 1000*(ikhz1-ikhz) - if(nqd.eq.1 .and. abs(nq65df-mousedf).lt.ntol) then - write(line,1020) ikhz1,ndf,npol,nutc,xdt0,nsnr0,msg0(1:28),cq0, & - ntxpol,cp -1020 format('!',i3.3,i5,i4,i6.4,f5.1,i5,' : ',a28,a3,i4,1x,a1) - write(*,1100) trim(line) -1100 format(a) - endif - -! Write to lu 26, for Messages and Band Map windows - cmode=': ' - cmode(2:2)=char(ichar('A') + mode_q65-1) - freq1=freq0 + 0.001d0*(ikhz1-ikhz) - write(26,1014) freq1,ndf,0,0,0,xdt0,npol,0,nsnr0,nutc,msg0(1:28), & - ':',cp,cmode ! was 1:22 -1014 format(f8.3,i5,3i3,f5.1,i4,i3,i4,i5.4,4x,a28,1x,2a1,2x,a2) ! was a22 - -! Suppress writing duplicates (same time, decoded message, and frequency) -! to map65_rx.log - if(nutc.ne.nutc00 .or. msg0(1:28).ne.msg00 .or. freq1.ne.freq1_00) then -! Write to file map65_rx.log: - ndecodes=ndecodes+1 - write(21,1110) freq1,ndf,xdt0,npol,nsnr0,nutc,msg0(1:28), & - cmode(2:2),cq0 -1110 format(f8.3,i5,f5.1,2i4,i5.4,2x,a28,': ',a1,2x,a3) - nutc00=nutc - msg00=msg0(1:28) - freq1_00=freq1 - frx=0.001*k0*df+nkhz_center-48.0+1.0 - 0.001*nfcal - fsked=frx - 0.001*ndop00/2.0 - 1.5 - write(12,1120) nutc,fsked,xdt0,nsnr0,trim(msg0) -1120 format(i4.4,f9.3,f7.2,i5,2x,a,i6) - endif - endif - -900 close(13) - close(17) - call flush(6) - idec=-1 - read(cq0(2:2),*) idec - - return -end subroutine q65b diff --git a/map65/libm65/q65b_for_Linux.f90 b/map65/libm65/q65b_for_Linux.f90 deleted file mode 100644 index 0e5ae27c..00000000 --- a/map65/libm65/q65b_for_Linux.f90 +++ /dev/null @@ -1,205 +0,0 @@ -subroutine q65b(nutc,nqd,nxant,fcenter,nfcal,nfsample,ikhz,mousedf,ntol,xpol, & - mycall0,mygrid,hiscall0,hisgrid,mode_q65,f0,fqso,newdat,nagain, & - max_drift,nhsym,ndop00,idec) - -! This routine provides an interface between MAP65 and the Q65 decoder -! in WSJT-X. All arguments are input data obtained from the MAP65 GUI. -! Raw Rx data are available as the 96 kHz complex spectrum ca(MAXFFT1) -! in common/cacb. If xpol is true, we also have cb(MAXFFT1) for the -! orthogonal polarization. Decoded messages are sent back to the GUI -! on stdout. - -! use wavhdr - use q65_decode - use wideband_sync - use timer_module, only: timer - - parameter (MAXFFT1=5376000) !56*96000 - parameter (MAXFFT2=336000) !56*6000 (downsampled by 1/16) - parameter (NMAX=60*12000) - parameter (RAD=57.2957795) -! type(hdr) h !Header for the .wav file - integer*2 iwave(60*12000) - complex ca(MAXFFT1),cb(MAXFFT1) !FFTs of raw x,y data - complex cx(0:MAXFFT2-1),cy(0:MAXFFT2-1),cz(0:MAXFFT2) - logical xpol,ldecoded - integer ipk1(1) - real*8 fcenter,freq0,freq1 - character*12 mycall0,hiscall0 - character*12 mycall,hiscall - character*6 mygrid,hisgrid - character*4 grid4 - character*28 msg00 - character*80 line - character*80 wsjtx_dir - character*1 cp,cmode*2 - common/cacb/ca,cb - common/early/nhsym1,nhsym2,ldecoded(32768) - common/decodes/ndecodes - data nutc00/-1/,msg00/' '/ - save - - if(newdat.eq.1) nutc00=-1 -! open(9,file='wsjtx_dir.txt',status='old') -! read(9,'(a)') wsjtx_dir !Establish the working directory -! close(9) - - if(mycall0(1:1).ne.' ') mycall=mycall0 - if(hiscall0(1:1).ne.' ') hiscall=hiscall0 - if(hisgrid(1:4).ne.' ') grid4=hisgrid(1:4) - -! Find best frequency and ipol from sync_dat, the "orange sync curve". - df3=96000.0/32768.0 - ifreq=nint((1000.0*f0)/df3) - ia=nint(ifreq-ntol/df3) - ib=nint(ifreq+ntol/df3) - ipk1=maxloc(sync(ia:ib)%ccfmax) - ipk=ia+ipk1(1)-1 - if(ldecoded(ipk)) go to 900 - snr1=sync(ipk)%ccfmax - ipol=1 - if(xpol) ipol=sync(ipk)%ipol - - nfft1=MAXFFT1 - nfft2=MAXFFT2 - df=96000.0/NFFT1 - if(nfsample.eq.95238) then - nfft1=5120000 - nfft2=322560 - df=96000.0/nfft1 - endif - nh=nfft2/2 - f_mouse=1000.0*(fqso+48.0) + mousedf - f_ipk=ipk*df3 - k0=nint((ipk*df3-1000.0)/df) - if(nagain.eq.1) k0=nint((f_mouse-1000.0)/df) - - if(k0.lt.nh .or. k0.gt.MAXFFT1-nfft2+1) go to 900 - if(snr1.lt.1.5) go to 900 !### Threshold needs work? ### - - fac=1.0/nfft2 - cx(0:nfft2-1)=ca(k0:k0+nfft2-1) - cx=fac*cx - if(xpol) then - cy(0:nfft2-1)=cb(k0:k0+nfft2-1) - cy=fac*cy - endif - -! Here cx and cy (if xpol) are frequency-domain data around the selected -! QSO frequency, taken from the full-length FFT computed in filbig(). -! Values for fsample, nfft1, nfft2, df, and the downsampled data rate -! are as follows: - -! fSample nfft1 df nfft2 fDownSampled -! (Hz) (Hz) (Hz) -!---------------------------------------------------- -! 96000 5376000 0.017857143 336000 6000.000 -! 95238 5120000 0.018601172 322560 5999.994 - - poldeg=0. - if(xpol) then - poldeg=sync(ipk)%pol - cz(0:MAXFFT2-1)=cos(poldeg/RAD)*cx + sin(poldeg/RAD)*cy - else - cz(0:MAXFFT2-1)=cx - endif - - cz(MAXFFT2)=0. -! Roll off below 500 Hz and above 2500 Hz. - ja=nint(500.0/df) - jb=nint(2500.0/df) - do i=0,ja - r=0.5*(1.0+cos(i*3.14159/ja)) - cz(ja-i)=r*cz(ja-i) - cz(jb+i)=r*cz(jb+i) - enddo - cz(ja+jb+1:)=0. - -!Transform to time domain (real), fsample=12000 Hz - call four2a(cz,2*nfft2,1,1,-1) - do i=0,nfft2-1 - j=nfft2-1-i - iwave(2*i+2)=nint(real(cz(j))) !Note the reversed order! - iwave(2*i+1)=nint(aimag(cz(j))) - enddo - iwave(2*nfft2+1:)=0 - -! open(30,file='000000_0001.wav',status='unknown',access='stream') -! h=default_header(12000,NMAX) -! write(30) h,iwave -! close(30) - - nsubmode=mode_q65-1 - nfa=990 !Tight limits around ipk for the wideband decode - nfb=1010 - if(nagain.eq.1) then !For nagain=1, use limits of +/- ntol - nfa=max(100,1000-ntol) - nfb=min(2500,1000+ntol) - endif - nsnr0=-99 !Default snr for no decode - ndpth=3 - -! NB: Frequency of ipk is now shifted to 1000 Hz. - call map65_mmdec(nutc,iwave,nqd,nsubmode,nfa,nfb,1000,ntol, & - newdat,nagain,max_drift,ndepth,mycall,hiscall0,hisgrid) - - MHz=fcenter - freq0=MHz + 0.001d0*ikhz - - if(nsnr0.gt.-99) then - ldecoded(ipk)=.true. - nq65df=nint(1000*(0.001*k0*df+nkhz_center-48.0+1.000-1.27046-ikhz))-nfcal - nq65df=nq65df + nfreq0 - 1000 - npol=nint(poldeg) - if(nxant.ne.0) then - npol=npol-45 - if(npol.lt.0) npol=npol+180 - endif - call txpol(xpol,msg0(1:28),mygrid,npol,nxant,ntxpol,cp) - ikhz1=ikhz - ndf=nq65df - if(ndf.gt.500) ikhz1=ikhz + (nq65df+500)/1000 - if(ndf.lt.-500) ikhz1=ikhz + (nq65df-500)/1000 - ndf=nq65df - 1000*(ikhz1-ikhz) - if(nqd.eq.1 .and. abs(nq65df-mousedf).lt.ntol) then - write(line,1020) ikhz1,ndf,npol,nutc,xdt0,nsnr0,msg0(1:28),cq0, & - ntxpol,cp -1020 format('!',i3.3,i5,i4,i6.4,f5.1,i5,' : ',a28,a3,i4,1x,a1) - write(*,1100) trim(line) -1100 format(a) - endif - -! Write to lu 26, for Messages and Band Map windows - cmode=': ' - cmode(2:2)=char(ichar('A') + mode_q65-1) - freq1=freq0 + 0.001d0*(ikhz1-ikhz) - write(26,1014) freq1,ndf,0,0,0,xdt0,npol,0,nsnr0,nutc,msg0(1:28), & - ':',cp,cmode ! was 1:22 -1014 format(f8.3,i5,3i3,f5.1,i4,i3,i4,i5.4,4x,a28,1x,2a1,2x,a2) ! was a22 - -! Suppress writing duplicates (same time, decoded message, and frequency) -! to map65_rx.log - if(nutc.ne.nutc00 .or. msg0(1:28).ne.msg00 .or. freq1.ne.freq1_00) then -! Write to file map65_rx.log: - ndecodes=ndecodes+1 - write(21,1110) freq1,ndf,xdt0,npol,nsnr0,nutc,msg0(1:28), & - cmode(2:2),cq0 -1110 format(f8.3,i5,f5.1,2i4,i5.4,2x,a28,': ',a1,2x,a3) - nutc00=nutc - msg00=msg0(1:28) - freq1_00=freq1 - frx=0.001*k0*df+nkhz_center-48.0+1.0 - 0.001*nfcal - fsked=frx - 0.001*ndop00/2.0 - 1.5 - write(12,1120) nutc,fsked,xdt0,nsnr0,trim(msg0) -1120 format(i4.4,f9.3,f7.2,i5,2x,a,i6) - endif - endif - -900 close(13) - close(17) - call flush(6) - idec=-1 - read(cq0(2:2),*) idec - - return -end subroutine q65b diff --git a/map65/libm65/recvpkt.f90 b/map65/libm65/recvpkt.f90 index 88d51cc5..32900835 100644 --- a/map65/libm65/recvpkt.f90 +++ b/map65/libm65/recvpkt.f90 @@ -1,73 +1,115 @@ -subroutine recvpkt(nsam,nblock2,userx_no,k,buf4,buf8,buf16) - -! Reformat timf2 data from Linrad and stuff data into r*4 array dd(). - - include 'njunk.f90' - parameter (NSMAX=60*96000) !Total sample intervals per minute - parameter (NFFT=32768) - integer*1 userx_no - real*4 d4,buf4(*) !(348) - real*8 d8,buf8(*) !(174) - complex*16 c16,buf16(*) !(87) - integer*2 jd(4),kd(2),nblock2 - real*4 xd(4),yd(2) - real*8 fcenter - common/datcom/dd(4,5760000),ss(4,322,NFFT),savg(4,NFFT),fcenter,nutc, & - junk(NJUNK) - equivalence (kd,d4) - equivalence (jd,d8,yd) - equivalence (xd,c16) - - if(nblock2.eq.-9999) nblock2=-9998 !Silence a compiler warning - if(nsam.eq.-1) then -! Move data from the UDP packet buffer into array dd(). - if(userx_no.eq.-1) then - do i=1,174 !One RF channel, r*4 data - k=k+1 - d8=buf8(i) - dd(1,k)=yd(1) - dd(2,k)=yd(2) - enddo - else if(userx_no.eq.1) then - do i=1,348 !One RF channel, i*2 data - k=k+1 - d4=buf4(i) - dd(1,k)=kd(1) - dd(2,k)=kd(2) - enddo - else if(userx_no.eq.-2) then - do i=1,87 !Two RF channels, r*4 data - k=k+1 - c16=buf16(i) - dd(1,k)=xd(1) - dd(2,k)=xd(2) - dd(3,k)=xd(3) - dd(4,k)=xd(4) - enddo - else if(userx_no.eq.2) then - do i=1,174 !Two RF channels, i*2 data - k=k+1 - d8=buf8(i) - dd(1,k)=jd(1) - dd(2,k)=jd(2) - dd(3,k)=jd(3) - dd(4,k)=jd(4) - enddo - endif - else - if(userx_no.eq.1) then - do i=1,nsam !One RF channel, r*4 data - k=k+1 - d4=buf4(i) - dd(1,k)=kd(1) - dd(2,k)=kd(2) - - k=k+1 - dd(1,k)=kd(1) - dd(2,k)=kd(2) - enddo - endif - endif - - return -end subroutine recvpkt +module recvpkt_mod + use datcom_ptrs_mod ! for dd + use iso_fortran_env, only: real64, real32, int16 + implicit none +contains + +subroutine recvpkt(nsam, nblock2, userx_no, k, buf4, buf8, buf16) & + bind(C, name="recvpkt_") + + use iso_c_binding + + integer(c_int), intent(in) :: nsam + integer(c_int16_t), intent(inout) :: nblock2 + integer(c_int8_t), intent(in) :: userx_no + integer(c_int), intent(inout) :: k + + real(c_float), intent(in) :: buf4(*) + real(c_double), intent(in) :: buf8(*) + complex(c_double_complex), intent(in) :: buf16(*) + + ! ===== Locals ===== + integer :: i + + ! Silence unused warning + if (nblock2 .eq. -9999) nblock2 = -9998 + + if (nsam .eq. -1) then + ! Move data from UDP/PortAudio buffer into dd() + + select case (userx_no) + + case (-1) + do i = 1, 174 + k = k + 1 + call unpack_r8_to_r4(buf8(i), dd(1,k), dd(2,k)) + end do + + case (1) + do i = 1, 348 + k = k + 1 + call unpack_r4_to_i2_as_r4(buf4(i), dd(1,k), dd(2,k)) + end do + + case (-2) + do i = 1, 87 + k = k + 1 + call unpack_c16_to_r4(buf16(i), dd(1,k), dd(2,k), dd(3,k), dd(4,k)) + end do + + case (2) + do i = 1, 174 + k = k + 1 + call unpack_r8_to_i2_as_r4(buf8(i), dd(1,k), dd(2,k), dd(3,k), dd(4,k)) + end do + end select + + else + ! nsam >= 0: special case for one RF channel, r*4 data + if (userx_no .eq. 1) then + do i = 1, nsam + k = k + 1 + call unpack_r4_to_i2_as_r4(buf4(i), dd(1,k), dd(2,k)) + + k = k + 1 + dd(1,k) = dd(1,k-1) + dd(2,k) = dd(2,k-1) + end do + end if + end if + + end subroutine recvpkt + + ! ===== Helper routines (unchanged ABI, now module-scoped) ===== + + subroutine unpack_r8_to_r4(x, a, b) + real(real64), intent(in) :: x + real(real32), intent(out) :: a, b + real(real32) :: tmp(2) + tmp = transfer(x, tmp) + a = tmp(1) + b = tmp(2) + end subroutine unpack_r8_to_r4 + + subroutine unpack_r4_to_i2_as_r4(x, a, b) + real(real32), intent(in) :: x + real(real32), intent(out) :: a, b + integer(int16) :: tmp(2) + tmp = transfer(x, tmp) + a = real(tmp(1)) + b = real(tmp(2)) + end subroutine unpack_r4_to_i2_as_r4 + + subroutine unpack_c16_to_r4(x, a1, a2, a3, a4) + complex(real64), intent(in) :: x + real(real32), intent(out) :: a1, a2, a3, a4 + real(real32) :: tmp(4) + tmp = transfer(x, tmp, size(tmp)) + a1 = tmp(1) + a2 = tmp(2) + a3 = tmp(3) + a4 = tmp(4) + end subroutine unpack_c16_to_r4 + + subroutine unpack_r8_to_i2_as_r4(x, a1, a2, a3, a4) + real(real64), intent(in) :: x + real(real32), intent(out) :: a1, a2, a3, a4 + integer(int16) :: tmp(4) + tmp = transfer(x, tmp) + a1 = real(tmp(1)) + a2 = real(tmp(2)) + a3 = real(tmp(3)) + a4 = real(tmp(4)) + end subroutine unpack_r8_to_i2_as_r4 + +end module recvpkt_mod diff --git a/map65/libm65/rfile3a.f90 b/map65/libm65/rfile3a.f90 index 7e226651..96f14b0c 100644 --- a/map65/libm65/rfile3a.f90 +++ b/map65/libm65/rfile3a.f90 @@ -1,14 +1,33 @@ -subroutine rfile3a(infile,ibuf,n,fcenter,ierr) - - character*(*) infile - integer*8 ibuf(n) - real*8 fcenter - - open(10,file=infile,access='stream',status='old',err=998) - read(10,end=998) (ibuf(i),i=1,n/8),fcenter - ierr=0 - go to 999 -998 ierr=1002 -999 close(10) - return -end subroutine rfile3a +module rfile3a_mod + implicit none +contains + subroutine rfile3a(infile,ibuf,n,fcenter,ierr) + use iso_c_binding + use iso_fortran_env, only: real64, int64 + implicit none + character*(*), intent(in) :: infile + integer, intent(in) :: n + ! integer*8, intent(out) :: ibuf(n/8) ! ibuf(n) in original but read (ibuf(i),i=1,n/8). So ibuf must be n/8 size if int*8? + ! Wait, original: integer*8 ibuf(n). read (ibuf(i),i=1,n/8). + ! So it writes to the first n/8 elements. + ! But if n is byte count, and ibuf is 8 bytes, then n/8 is 64-bit word count. + ! So ibuf is integer*8 array of size at least n/8. + ! The declaration integer*8 ibuf(n) implies size n. + ! I will keep it as ibuf(n) or ibuf(*). + integer(int64), intent(out) :: ibuf(n) + real(real64), intent(out) :: fcenter + integer, intent(out) :: ierr + + integer :: i + + open(10,file=infile,access='stream',status='old',err=998) + read(10,end=998) (ibuf(i),i=1,n/8),fcenter + ierr=0 + close(10) + return + + 998 ierr=1002 + close(10) + return + end subroutine rfile3a +end module rfile3a_mod diff --git a/map65/libm65/rs_mod.f90 b/map65/libm65/rs_mod.f90 new file mode 100644 index 00000000..d7244a32 --- /dev/null +++ b/map65/libm65/rs_mod.f90 @@ -0,0 +1,23 @@ +module rs_mod + use iso_c_binding + implicit none + interface + subroutine rs_encode_(dgen, sent) bind(C, name="rs_encode_") + use iso_c_binding + implicit none + integer(c_int), intent(in) :: dgen(12) + integer(c_int), intent(out) :: sent(63) + end subroutine rs_encode_ + + subroutine rs_decode_(recd0, era0, numera0, decoded, nerr) bind(C, name="rs_decode_") + use iso_c_binding + implicit none + integer(c_int), intent(in) :: recd0(63) + integer(c_int), intent(in) :: era0(*) ! size = numera0 + integer(c_int), intent(in) :: numera0 + integer(c_int), intent(out) :: decoded(12) + integer(c_int), intent(out) :: nerr + end subroutine rs_decode_ +end interface + +end module rs_mod diff --git a/map65/libm65/run_m65.f90 b/map65/libm65/run_m65.f90 new file mode 100644 index 00000000..cc0ffe73 --- /dev/null +++ b/map65/libm65/run_m65.f90 @@ -0,0 +1,101 @@ +module run_m65_mod + use iso_c_binding + implicit none +contains + +subroutine run_m65(pol, sample_rate_96000) bind(C, name='run_m65_') + use iso_c_binding + use timer_module, only: timer + use timer_impl, only: init_timer, fini_timer + use debug_log + use m65a_mod + use npar_ptrs_mod, only: t_start, nhsym, mycall, hiscall, hisgrid, neme, & + initialize_decode_parameters, claim_decode_request, get_stop_m65, & + active_request_id, active_request_expired + use stdout_channel_mod, only: write_stdout + use decodes_mod, only: nhsym1,nhsym2 + use deep65_mod, only: build_call3_candidates + use sleep_msec_mod + use sec_midn_mod, only: sec_midn + + implicit none + + integer(c_int), intent(in) :: pol, sample_rate_96000 + + ! Local variables + integer :: sample_rate + character(len=128) :: line + integer :: t_rate + integer :: t_now + + nhsym1=280 + nhsym2=302 + + dbg_enabled = .false. ! flip to .true. to enable dbg() logging to w3sz_debug.log + + if (sample_rate_96000 /=0) then + sample_rate = 96000 + else + sample_rate = 95238 ! 96000 / 1.008, legacy WSJT slow-96k correction + endif + call write_stdout('STARTING RUN_M65'//new_line('a')) + + ! and one of the others, e.g. + write (line, '(A, I0)') ' ********** IN RUN_M65 sample_rate is: ', sample_rate + call write_stdout(trim(line)//new_line('a')) + +! if (.not. associated(savg)) then + ! print *, 'ERROR:RUN_M65 savg is not associated!' +! else + ! print *, 'RUN_M65 savg is associated. Shape =', shape(savg), " loc:", loc(savg) +! end if + +! if (.not. associated(dd)) then + ! print *, 'ERROR: RUN_M65 dd is not associated!' +! else + ! print *, 'RUN_M65 dd is associated. Shape =', shape(dd), " loc:", loc(dd) +! end if + +! if (.not. associated(ss)) then + ! print *, 'ERROR: RUN_M65 ss is not associated!' +! else + ! print *, 'RUN_M65 ss is associated. Shape =', shape(ss), " loc:", loc(ss) +! end if + +! print *, ' ********** IN RUN_M65 sample_rate_96000 is: ', sample_rate +! flush (6) +! print *, ' ********** IN RUN_M65 pol is: ', pol +! flush (6) + + !print *, 'IN RUN_M65, initial stop_m65 =', stop_m65 + !flush(6) + + call init_timer() + call initialize_decode_parameters() + + ! Encode the CALL3.TXT candidates before the first decode's time budget starts. + ! deep65 rebuilds them when calls, grids, the EME filter, or CALL3.TXT change. + call dbg('run_m65: eager build_call3_candidates() STARTING at t=' // rtoa(sec_midn())) + call build_call3_candidates(mycall, hiscall, hisgrid, neme) + call dbg('run_m65: eager build_call3_candidates() DONE at t=' // rtoa(sec_midn())) + + do while (get_stop_m65() == 0) + if (claim_decode_request()) then + if (active_request_expired) then + write(line, '(A,1X,I0)') '<DecodeSkipped>', active_request_id + call write_stdout(trim(line)//new_line('a')) + else + call system_clock(t_start, t_rate) + call m65a() + call system_clock(t_now) + call dbg('run_m65: request completed, elapsed=' // rtoa(real(t_now - t_start)/real(t_rate))) + endif + endif + call sleep_msec(50) + end do + + call fini_timer() + close(21) + +end subroutine run_m65 +end module run_m65_mod diff --git a/map65/libm65/s3avg.f90 b/map65/libm65/s3avg.f90 index 9d76637c..5a21c31f 100644 --- a/map65/libm65/s3avg.f90 +++ b/map65/libm65/s3avg.f90 @@ -1,30 +1,48 @@ -subroutine s3avg(nsave,mode65,nutc,nhz,xdt,npol,ntol,s3,nsum,nkv,decoded) +module s3avg_mod + implicit none +contains + +subroutine s3avg(nsave, mode65, nutc, nhz, xdt, npol, nflip, ntol, s3, nsum, nkv, decoded) + use extract_mod + implicit none ! Save the current synchronized spectra, s3(64,63), for possible ! decoding of average. - real s3(64,63) !Synchronized spectra for 63 symbols + integer, intent(inout) :: nsave + integer, intent(in) :: mode65, nutc, nhz, npol, nflip, ntol + real, intent(in) :: xdt + real, intent(in) :: s3(64,63) !Synchronized spectra for 63 symbols + integer, intent(out) :: nsum, nkv + character(len=22), intent(out) :: decoded + real s3a(64,63,64) !Saved spectra real s3b(64,63) !Average spectra - integer iutc(64),ihz(64),ipol(64) + integer iutc(64),ihz(64),ipol(64),iflip(64) + integer :: i,ihzdiff,nadd,ncount,nhist + integer :: mrs(63), mrs2(63) !Dummy arguments for extract + real, parameter :: dtdiff=0.2 real dt(64) - character*22 decoded logical ltext,first data first/.true./ - save + save first,iutc,ihz,ipol,iflip,s3a,dt + + nsum=0 + nkv=0 + decoded=' ' + ihzdiff=min(100,ntol) if(first) then iutc=-1 ihz=0 ipol=0 + iflip=0 first=.false. - ihzdiff=min(100,ntol) - dtdiff=0.2 endif do i=1,64 - if(nutc.eq.iutc(i) .and. abs(nhz-ihz(i)).lt.ihzdiff) then - nsave=mod(nsave-1+64,64)+1 + if(nutc.eq.iutc(i) .and. abs(nhz-ihz(i)).le.ihzdiff) then + nsave=mod(nsave-2+64,64)+1 go to 10 endif enddo @@ -32,6 +50,7 @@ subroutine s3avg(nsave,mode65,nutc,nhz,xdt,npol,ntol,s3,nsum,nkv,decoded) iutc(nsave)=nutc !Save UTC ihz(nsave)=nhz !Save freq in Hz ipol(nsave)=npol !Save pol + iflip(nsave)=nflip dt(nsave)=xdt !Save DT s3a(1:64,1:63,nsave)=s3 !Save the spectra @@ -41,14 +60,16 @@ subroutine s3avg(nsave,mode65,nutc,nhz,xdt,npol,ntol,s3,nsum,nkv,decoded) if(mod(iutc(i),2).ne.mod(nutc,2)) cycle !Use only same sequence if(abs(nhz-ihz(i)).gt.ihzdiff) cycle !Freq must match if(abs(xdt-dt(i)).gt.dtdiff) cycle !DT must match + ! Opposite sync polarities map s3 columns to complementary symbol positions. + if(iflip(i).eq.0) cycle + if(nflip.ne.iflip(i)) cycle s3b=s3b + s3a(1:64,1:63,i) nsum=nsum+1 enddo - decoded=' ' if(nsum.ge.2) then !Try decoding the sverage nadd=mode65*nsum - call extract(s3b,nadd,ncount,nhist,decoded,ltext) !Extract the message + call extract(s3b,nadd,ncount,nhist,decoded,ltext,mrs,mrs2) !Extract the message nkv=nsum if(ncount.lt.0) then nkv=0 @@ -58,3 +79,5 @@ subroutine s3avg(nsave,mode65,nutc,nhz,xdt,npol,ntol,s3,nsum,nkv,decoded) return end subroutine s3avg + +end module s3avg_mod diff --git a/map65/libm65/sec0_mod.f90 b/map65/libm65/sec0_mod.f90 new file mode 100644 index 00000000..1495a285 --- /dev/null +++ b/map65/libm65/sec0_mod.f90 @@ -0,0 +1,19 @@ +module sec0_mod + use sec_midn_mod + implicit none +contains + + subroutine sec0(mode, t) + integer, intent(in) :: mode + real, intent(out) :: t + real, save :: t0 = 0.0 + + if (mode == 1) then + t0 = sec_midn() + t = t0 + else + t = sec_midn() - t0 + end if + end subroutine sec0 + +end module sec0_mod diff --git a/map65/libm65/sec_midn.f90 b/map65/libm65/sec_midn.f90 index 0bbe62c2..86dfe2e4 100644 --- a/map65/libm65/sec_midn.f90 +++ b/map65/libm65/sec_midn.f90 @@ -1,11 +1,20 @@ -real function sec_midn() - sec_midn=secnds(0.0) - return -end function sec_midn +module sec_midn_mod + implicit none +contains -subroutine sleep_msec(n) + real function sec_midn() + implicit none + integer :: values(8) - call usleep(1000*n) + call date_and_time(values=values) + + ! values(5) = hour + ! values(6) = minute + ! values(7) = second + ! values(8) = milliseconds + + sec_midn = values(5)*3600.0 + values(6)*60.0 + values(7) + values(8)/1000.0 + end function sec_midn + +end module sec_midn_mod - return -end subroutine sleep_msec diff --git a/map65/libm65/set.f90 b/map65/libm65/set.f90 index ff767988..4bf3a30f 100644 --- a/map65/libm65/set.f90 +++ b/map65/libm65/set.f90 @@ -1,31 +1,16 @@ -subroutine set(a,y,n) - real y(n) - do i=1,n - y(i)=a - enddo - return -end subroutine set - -subroutine move(x,y,n) - real x(n),y(n) - do i=1,n - y(i)=x(i) - enddo - return -end subroutine move - -subroutine zero(x,n) - real x(n) - do i=1,n - x(i)=0.0 - enddo - return -end subroutine zero - -subroutine add(a,b,c,n) - real a(n),b(n),c(n) - do i=1,n - c(i)=a(i)+b(i) - enddo - return -end subroutine add +module set_mod + implicit none +contains + + subroutine move(x,y,n) + implicit none + integer, intent(in) :: n + integer, intent(in) :: x(n) + integer, intent(out) :: y(n) + integer :: i + do i=1,n + y(i)=x(i) + enddo + end subroutine move + +end module set_mod diff --git a/map65/libm65/setup65.f90 b/map65/libm65/setup65.f90 index b1a867d1..3e83487a 100644 --- a/map65/libm65/setup65.f90 +++ b/map65/libm65/setup65.f90 @@ -1,10 +1,17 @@ +module setup65_mod + implicit none +contains + subroutine setup65 ! Defines arrays related to the JT65 pseudo-random synchronizing pattern. ! Executed at program start. - integer nprc(126) - common/prcom/pr(126),mdat(126),mref(126,2),mdat2(126),mref2(126,2) + use pr_mod + implicit none + + integer :: nprc(126) + integer :: i,k,m,mr2,n,nsig,nsym,mr1 ! JT65 data nprc/ & @@ -94,3 +101,5 @@ subroutine setup65 return end subroutine setup65 + +end module setup65_mod diff --git a/map65/libm65/shell.f90 b/map65/libm65/shell.f90 index d7365bfc..110e5a1e 100644 --- a/map65/libm65/shell.f90 +++ b/map65/libm65/shell.f90 @@ -1,27 +1,31 @@ -subroutine shell(n,a) - integer n - real a(n) - integer i,j,inc - real v - - inc=1 -1 inc=3*inc+1 - if(inc.le.n) go to 1 -2 inc=inc/3 - - do i=inc+1,n - v=a(i) - j=i -3 if(a(j-inc).gt.v) then - a(j)=a(j-inc) - j=j-inc - if(j.le.inc) go to 4 - go to 3 - endif -4 a(j)=v - enddo - - if(inc.gt.1) go to 2 - - return -end subroutine shell +module shell_mod + implicit none +contains + subroutine shell(n,a) + implicit none + integer, intent(in) :: n + real, intent(inout) :: a(n) + integer :: i,j,inc + real :: v + + inc=1 + 1 inc=3*inc+1 + if(inc.le.n) go to 1 + 2 inc=inc/3 + + do i=inc+1,n + v=a(i) + j=i + 3 if(a(j-inc).gt.v) then + a(j)=a(j-inc) + j=j-inc + if(j.le.inc) go to 4 + go to 3 + endif + 4 a(j)=v + enddo + + if(inc.gt.1) go to 2 + + end subroutine shell +end module shell_mod diff --git a/map65/libm65/sleep_msec.f90 b/map65/libm65/sleep_msec.f90 index 1a8dbe4f..1e21ab27 100644 --- a/map65/libm65/sleep_msec.f90 +++ b/map65/libm65/sleep_msec.f90 @@ -1,4 +1,22 @@ -subroutine sleep_msec(n) - call usleep(n*1000) - return -end subroutine sleep_msec +module sleep_msec_mod + implicit none + + interface + subroutine usleep(usec) + ! Fortran-only interface to the C function usleep_ + integer(kind=8), intent(in) :: usec + end subroutine usleep + end interface + +contains + + subroutine sleep_msec(n) + integer, intent(in) :: n + integer(kind=8) :: usec + + usec = int(n, kind=8) * 1000_8 + call usleep(usec) + end subroutine sleep_msec + +end module sleep_msec_mod + diff --git a/map65/libm65/smo.f90 b/map65/libm65/smo.f90 index c42de7c6..194a7455 100644 --- a/map65/libm65/smo.f90 +++ b/map65/libm65/smo.f90 @@ -1,19 +1,25 @@ -subroutine smo(x,npts,y,nadd) - - real x(npts) - real y(npts) - - nh=nadd/2 - do i=1+nh,npts-nh - sum=0. - do j=-nh,nh - sum=sum + x(i+j) - enddo - y(i)=sum - enddo - x=y - x(:nh)=0. - x(npts-nh+1:)=0. - - return -end subroutine smo +module smo_mod + implicit none +contains + subroutine smo(x,npts,y,nadd) + implicit none + integer, intent(in) :: npts, nadd + real, intent(inout) :: x(npts) + real, intent(out) :: y(npts) + integer :: nh, i, j + real :: sum + + nh=nadd/2 + do i=1+nh,npts-nh + sum=0. + do j=-nh,nh + sum=sum + x(i+j) + enddo + y(i)=sum + enddo + x=y + x(:nh)=0. + x(npts-nh+1:)=0. + + end subroutine smo +end module smo_mod diff --git a/map65/libm65/sort.f90 b/map65/libm65/sort.f90 index 8a05da28..022422c2 100644 --- a/map65/libm65/sort.f90 +++ b/map65/libm65/sort.f90 @@ -1,6 +1,16 @@ -subroutine sort(n,arr) - - call ssort(arr,tmp,n,1) - - return -end subroutine sort +module sort_mod + implicit none +contains + subroutine sort(n,arr) + implicit none + integer, intent(in) :: n + real, intent(inout) :: arr(n) + real :: tmp(n) ! tmp is likely used by ssort as workspace? + ! Original call: call ssort(arr,tmp,n,1) + ! ssort usually needs a workspace or index array. + ! Assuming external ssort. + + call ssort(arr,tmp,n,1) + + end subroutine sort +end module sort_mod diff --git a/map65/libm65/ssort.f b/map65/libm65/ssort.f index fa508ace..e07a0b09 100644 --- a/map65/libm65/ssort.f +++ b/map65/libm65/ssort.f @@ -35,8 +35,8 @@ c = -2 means sort x in decreasing order and carry y along. c kk = abs(kflag) if (kk.ne.1 .and. kk.ne.2) then - print *, - + 'the sort control parameter, k, is not 2, 1, -1, or -2.' + ! print *, + ! + 'the sort control parameter, k, is not 2, 1, -1, or -2.' return endif c diff --git a/map65/libm65/stdout_channel_mod.f90 b/map65/libm65/stdout_channel_mod.f90 new file mode 100644 index 00000000..2dffdb95 --- /dev/null +++ b/map65/libm65/stdout_channel_mod.f90 @@ -0,0 +1,141 @@ +module stdout_channel_mod + use iso_c_binding + implicit none + + !=============================== + ! Types matching the C++ layout + !=============================== + type, bind(C) :: StdoutSharedHeader + integer(c_int32_t) :: version + integer(c_int32_t) :: writeIndex + integer(c_int32_t) :: readIndex + integer(c_int32_t) :: seq + end type StdoutSharedHeader + + !=============================== + ! Internal state + !=============================== + type(c_ptr) :: g_buf_ptr = c_null_ptr + type(c_ptr) :: g_hdr_ptr = c_null_ptr + integer(c_int32_t) :: g_buf_size = 0 + integer(c_intptr_t) :: g_event_handle = 0 + + type(StdoutSharedHeader), pointer :: hdr => null() + character(kind=c_char), dimension(:), pointer :: buf => null() + + logical :: initialized = .false. + + !=============================== + ! Win32 SetEvent + !=============================== + interface + function win_set_event(hEvent) bind(C, name="win_set_event") + use iso_c_binding + implicit none + type(c_ptr), value :: hEvent + integer(c_int) :: win_set_event + end function win_set_event + end interface + +contains + + !========================================================= + ! Called from C++ before run_m65_ starts + !========================================================= +subroutine set_stdout_channel(buf_ptr, hdr_ptr, buf_size, event_handle) & + bind(C, name="set_stdout_channel") + + use iso_c_binding + implicit none + + !==== Dummy arguments ===================================================== + type(c_ptr), value, intent(in) :: buf_ptr + type(c_ptr), value, intent(in) :: hdr_ptr + integer(c_int32_t), value, intent(in) :: buf_size + integer(c_intptr_t),value, intent(in) :: event_handle + + !==== Body ================================================================ + if (c_associated(buf_ptr) .and. c_associated(hdr_ptr) .and. buf_size > 0) then + g_buf_ptr = buf_ptr + g_hdr_ptr = hdr_ptr + g_buf_size = buf_size + g_event_handle = event_handle + + call c_f_pointer(hdr_ptr, hdr) + call c_f_pointer(buf_ptr, buf, [buf_size]) + + initialized = .true. + else + initialized = .false. + end if +end subroutine set_stdout_channel + + !========================================================= + ! Safe write into shared memory + event signal + !========================================================= +subroutine write_stdout(msg) + use iso_c_binding + use sleep_msec_mod, only: sleep_msec + implicit none + + !==== Dummy argument ===================================================== + character(len=*), intent(in) :: msg + + !==== Local variables ==================================================== + integer(c_int32_t) :: n, i, rc + integer(c_int32_t) :: w, idx, r, occupied, free_bytes + integer :: nwait + integer, parameter :: MAX_WAIT_ITERS = 2000 ! ~2 s at 1 ms/iter + character(kind=c_char) :: ch + + if (.not. initialized) return + if (.not. associated(hdr)) return + if (.not. associated(buf)) return + + ! Length of the message (assumed to include newline) + n = len_trim(msg) + if (n <= 0) return + + ! Avoid filling the entire buffer + if (n >= g_buf_size) n = g_buf_size - 1 + + ! Snapshot current write index (0..g_buf_size-1) + w = hdr%writeIndex + if (w < 0 .or. w >= g_buf_size) w = 0 + + ! Wait for the reader to make room rather than overwriting unread + ! data. One byte of the buffer is always kept empty so a full ring + ! can be told apart from an empty one. If the reader stalls for a + ! couple of seconds we give up waiting and write anyway, so a dead + ! or stuck reader can never hang the decoder. + do nwait = 1, MAX_WAIT_ITERS + r = hdr%readIndex + if (r < 0 .or. r >= g_buf_size) r = 0 + occupied = w - r + if (occupied < 0) occupied = occupied + g_buf_size + free_bytes = g_buf_size - 1 - occupied + if (free_bytes >= n) exit + call sleep_msec(1) + end do + + ! Write bytes with wraparound, using 0-based idx and 1-based buf + do i = 0, n - 1 + idx = w + i + if (idx >= g_buf_size) idx = idx - g_buf_size + ch = msg(i+1:i+1) + buf(idx+1) = ch ! buf is 1-based; idx is 0-based + end do + + ! Advance writeIndex to first free slot after the data + w = w + n + if (w >= g_buf_size) w = w - g_buf_size + hdr%writeIndex = w + + ! Optional: bump seq + hdr%seq = hdr%seq + 1 + + rc = win_set_event(transfer(g_event_handle, c_null_ptr)) +end subroutine write_stdout + +end module stdout_channel_mod + diff --git a/map65/libm65/stdout_shared_layout.h b/map65/libm65/stdout_shared_layout.h new file mode 100644 index 00000000..4564678e --- /dev/null +++ b/map65/libm65/stdout_shared_layout.h @@ -0,0 +1,23 @@ +// stdout_shared_layout.h +#pragma once +#include <cstdint> + +#pragma pack(push, 1) +struct StdoutSharedHeader +{ + std::uint32_t version; // For compatibility + std::uint32_t writeIndex; // Next write position in buffer + std::uint32_t readIndex; // Last position consumed by the reader thread; + // the writer uses this to compute free space + // and apply backpressure instead of + // overwriting unread data. + std::uint32_t seq; // Incremented each write (helps detect missed events) +}; + +struct StdoutSharedRegion +{ + StdoutSharedHeader header; + // Text buffer, size chosen at creation (e.g. 8 KB / 32 KB). + std::uint8_t buffer[1]; +}; +#pragma pack(pop)
\ No newline at end of file diff --git a/map65/libm65/stdout_shared_memory.cpp b/map65/libm65/stdout_shared_memory.cpp new file mode 100644 index 00000000..946ea187 --- /dev/null +++ b/map65/libm65/stdout_shared_memory.cpp @@ -0,0 +1,214 @@ +// stdout_shared_memory.cpp +#include "stdout_shared_memory.h" +#include <cstring> +#include <string> + + +#ifdef _WIN32 + #include <windows.h> +#else + #include <sys/mman.h> + #include <sys/stat.h> + #include <fcntl.h> + #include <unistd.h> + #include <errno.h> +#ifdef __APPLE__ + #include <sys/resource.h> +#endif + #include <codecvt> + #include <QString> + #include <QByteArray> +#endif + +namespace { + +#ifndef _WIN32 +std::string posixErrorMessage(const char* operation, int err) +{ + return std::string(operation) + " failed, errno=" + std::to_string(err) + + " (" + std::strerror(err) + ")"; +} + +#ifdef __APPLE__ +std::string rlimToString(rlim_t value) +{ + if (value == RLIM_INFINITY) return "infinity"; + return std::to_string(value); +} + +std::string nofileLimitMessage() +{ + struct rlimit limit; + if (getrlimit(RLIMIT_NOFILE, &limit) != 0) { + return ", RLIMIT_NOFILE unavailable"; + } + + return ", RLIMIT_NOFILE soft=" + rlimToString(limit.rlim_cur) + + " hard=" + rlimToString(limit.rlim_max); +} + +bool raiseFileDescriptorLimit() +{ + struct rlimit limit; + if (getrlimit(RLIMIT_NOFILE, &limit) != 0) return false; + + constexpr rlim_t target = 65536; + if (limit.rlim_cur >= target) return false; + + rlim_t newSoftLimit = target; + if (limit.rlim_max != RLIM_INFINITY && newSoftLimit > limit.rlim_max) { + newSoftLimit = limit.rlim_max; + } + if (newSoftLimit <= limit.rlim_cur) return false; + + limit.rlim_cur = newSoftLimit; + return setrlimit(RLIMIT_NOFILE, &limit) == 0; +} +#endif +#endif + +} + +StdoutSharedMemory::StdoutSharedMemory(const std::wstring &mappingName, + std::size_t totalBytes) + : handle_(nullptr), view_(nullptr), sizeBytes_(totalBytes) +{ +#ifdef _WIN32 + ULONGLONG size64 = static_cast<ULONGLONG>(totalBytes); + + HANDLE hMap = ::CreateFileMappingW( + INVALID_HANDLE_VALUE, + nullptr, + PAGE_READWRITE, + static_cast<DWORD>(size64 >> 32), + static_cast<DWORD>(size64 & 0xFFFFFFFFULL), + mappingName.c_str() + ); + + if (!hMap) + throw std::runtime_error("CreateFileMappingW failed"); + + void* view = ::MapViewOfFile( + hMap, + FILE_MAP_ALL_ACCESS, + 0, 0, + static_cast<SIZE_T>(totalBytes) + ); + + if (!view) { + ::CloseHandle(hMap); + throw std::runtime_error("MapViewOfFile failed"); + } + + handle_ = hMap; + view_ = view; + +#else + // Convert wide string to UTF‑8 for shm_open + QString qname = QString::fromStdWString(mappingName); + std::string name = "/" + qname.toUtf8().toStdString(); + + // Best-effort cleanup of any stale mapping from a previous run. + // If it doesn't exist, this just fails harmlessly. + shm_unlink(name.c_str()); + + int fd = shm_open(name.c_str(), O_CREAT | O_RDWR, 0600); + if (fd < 0) { + int err = errno; +#ifdef __APPLE__ + if ((err == EMFILE || err == ENFILE) && raiseFileDescriptorLimit()) { + fd = shm_open(name.c_str(), O_CREAT | O_RDWR, 0600); + if (fd >= 0) { + err = 0; + } else { + err = errno; + } + } +#endif + if (fd < 0) { + std::string message = posixErrorMessage("shm_open", err); +#ifdef __APPLE__ + message += nofileLimitMessage(); +#endif + throw std::runtime_error(message); + } + } + + if (ftruncate(fd, totalBytes) != 0) { + int err = errno; + close(fd); + shm_unlink(name.c_str()); + throw std::runtime_error(posixErrorMessage("ftruncate", err)); + } + + void* view = mmap(nullptr, totalBytes, + PROT_READ | PROT_WRITE, + MAP_SHARED, fd, 0); + + if (view == MAP_FAILED) { + int err = errno; + close(fd); + shm_unlink(name.c_str()); + throw std::runtime_error(posixErrorMessage("mmap", err)); + } + + close(fd); + shm_unlink(name.c_str()); + handle_ = nullptr; + view_ = view; +#endif + + + // Initialize header + auto* region = getRegion(); + region->header.version = 1; + region->header.writeIndex = 0; + region->header.readIndex = 0; + region->header.seq = 0; +} + +StdoutSharedMemory::~StdoutSharedMemory() +{ +#ifdef _WIN32 + if (view_) { + ::UnmapViewOfFile(view_); + view_ = nullptr; + } + if (handle_) { + ::CloseHandle((HANDLE)handle_); + handle_ = nullptr; + } +#else + if (view_) { + munmap(view_, sizeBytes_); + view_ = nullptr; + } + if (handle_) { + int fd = static_cast<int>(reinterpret_cast<intptr_t>(handle_)); + close(fd); + handle_ = nullptr; + } +#endif +} + +StdoutSharedMemory::StdoutSharedMemory(StdoutSharedMemory&& other) noexcept + : handle_(other.handle_), view_(other.view_), sizeBytes_(other.sizeBytes_) +{ + other.handle_ = nullptr; + other.view_ = nullptr; + other.sizeBytes_ = 0; +} + +StdoutSharedMemory& StdoutSharedMemory::operator=(StdoutSharedMemory&& other) noexcept +{ + if (this != &other) { + this->~StdoutSharedMemory(); + handle_ = other.handle_; + view_ = other.view_; + sizeBytes_ = other.sizeBytes_; + other.handle_ = nullptr; + other.view_ = nullptr; + other.sizeBytes_ = 0; + } + return *this; +} diff --git a/map65/libm65/stdout_shared_memory.h b/map65/libm65/stdout_shared_memory.h new file mode 100644 index 00000000..e1e50b2d --- /dev/null +++ b/map65/libm65/stdout_shared_memory.h @@ -0,0 +1,48 @@ +// stdout_shared_memory.h +#pragma once +#include "stdout_shared_layout.h" +#include <string> +#include <stdexcept> +#include <cstddef> + +class StdoutSharedMemory +{ +public: + StdoutSharedMemory(const std::wstring &mappingName, + std::size_t totalBytes); + + ~StdoutSharedMemory(); + + StdoutSharedMemory(const StdoutSharedMemory&) = delete; + StdoutSharedMemory& operator=(const StdoutSharedMemory&) = delete; + + StdoutSharedMemory(StdoutSharedMemory&& other) noexcept; + StdoutSharedMemory& operator=(StdoutSharedMemory&& other) noexcept; + + StdoutSharedRegion* getRegion() + { + return static_cast<StdoutSharedRegion*>(view_); + } + + const StdoutSharedRegion* getRegion() const + { + return static_cast<const StdoutSharedRegion*>(view_); + } + + void* getBufferPtr() + { + return getRegion()->buffer; + } + + std::size_t getBufferSize() const + { + return sizeBytes_ - sizeof(StdoutSharedHeader); + } + + void* getHandle() const { return handle_; } + +private: + void* handle_; // HANDLE on Windows, fd on Linux + void* view_; // mapped region + std::size_t sizeBytes_; +}; diff --git a/map65/libm65/sun.f90 b/map65/libm65/sun.f90 index ec011b66..3f3d3c82 100644 --- a/map65/libm65/sun.f90 +++ b/map65/libm65/sun.f90 @@ -1,88 +1,90 @@ -subroutine sun(y,m,DD,UT,lon,lat,RA,Dec,LST,Az,El,mjd,day) - +module sun_mod implicit none - - integer y !Year - integer m !Month - integer DD !Day - integer mjd !Modified Julian Date - real UT !UTC in hours - real RA,Dec !RA and Dec of sun - -! NB: Double caps here are single caps in the writeup. - -! Orbital elements of the Sun (also N=0, i=0, a=1): - real w !Argument of perihelion - real e !Eccentricity - real MM !Mean anomaly - real Ls !Mean longitude - -! Other standard variables: - real v !True anomaly - real EE !Eccentric anomaly - real ecl !Obliquity of the ecliptic - real d !Ephemeris time argument in days - real r !Distance to sun, AU - real xv,yv !x and y coords in ecliptic - real lonsun !Ecliptic long and lat of sun -! Ecliptic coords of sun (geocentric) - real xs,ys -! Equatorial coords of sun (geocentric) - real xe,ye,ze - real lon,lat - real GMST0,LST,HA - real xx,yy,zz - real xhor,yhor,zhor - real Az,El - - real day - real rad - data rad/57.2957795/ - -! Time in days, with Jan 0, 2000 equal to 0.0: - d=367*y - 7*(y+(m+9)/12)/4 + 275*m/9 + DD - 730530 + UT/24.0 - mjd=d + 51543 - ecl = 23.4393 - 3.563e-7 * d - -! Compute updated orbital elements for Sun: - w = 282.9404 + 4.70935e-5 * d - e = 0.016709 - 1.151e-9 * d - MM = mod(356.0470d0 + 0.9856002585d0 * d + 360000.d0,360.d0) - Ls = mod(w+MM+720.0,360.0) - - EE = MM + e*rad*sin(MM/rad) * (1.0 + e*cos(M/rad)) - EE = EE - (EE - e*rad*sin(EE/rad)-MM) / (1.0 - e*cos(EE/rad)) - - xv = cos(EE/rad) - e - yv = sqrt(1.0-e*e) * sin(EE/rad) - v = rad*atan2(yv,xv) - r = sqrt(xv*xv + yv*yv) - lonsun = mod(v + w + 720.0,360.0) -! Ecliptic coordinates of sun (rectangular): - xs = r * cos(lonsun/rad) - ys = r * sin(lonsun/rad) - -! Equatorial coordinates of sun (rectangular): - xe = xs - ye = ys * cos(ecl/rad) - ze = ys * sin(ecl/rad) - -! RA and Dec in degrees: - RA = rad*atan2(ye,xe) - Dec = rad*atan2(ze,sqrt(xe*xe + ye*ye)) - - GMST0 = (Ls + 180.0)/15.0 - LST = mod(GMST0+UT+lon/15.0+48.0,24.0) !LST in hours - HA = 15.0*LST - RA !HA in degrees - xx = cos(HA/rad)*cos(Dec/rad) - yy = sin(HA/rad)*cos(Dec/rad) - zz = sin(Dec/rad) - xhor = xx*sin(lat/rad) - zz*cos(lat/rad) - yhor = yy - zhor = xx*cos(lat/rad) + zz*sin(lat/rad) - Az = mod(rad*atan2(yhor,xhor) + 180.0 + 360.0,360.0) - El = rad*asin(zhor) - day=d-1.5 - - return -end subroutine sun +contains + subroutine sun(y,m,DD,UT,lon,lat,RA,Dec,LST,Az,El,mjd,day) + + implicit none + + integer, intent(in) :: y !Year + integer, intent(in) :: m !Month + integer, intent(in) :: DD !Day + integer, intent(out) :: mjd !Modified Julian Date + real, intent(in) :: UT !UTC in hours + real, intent(out) :: RA,Dec !RA and Dec of sun + real, intent(in) :: lon,lat + real, intent(out) :: LST,Az,El,day + + ! NB: Double caps here are single caps in the writeup. + + ! Orbital elements of the Sun (also N=0, i=0, a=1): + real w !Argument of perihelion + real e !Eccentricity + real MM !Mean anomaly + real Ls !Mean longitude + + ! Other standard variables: + real v !True anomaly + real EE !Eccentric anomaly + real ecl !Obliquity of the ecliptic + real d !Ephemeris time argument in days + real r !Distance to sun, AU + real xv,yv !x and y coords in ecliptic + real lonsun !Ecliptic long and lat of sun + ! Ecliptic coords of sun (geocentric) + real xs,ys + ! Equatorial coords of sun (geocentric) + real xe,ye,ze + real GMST0,HA + real xx,yy,zz + real xhor,yhor,zhor + + real rad + data rad/57.2957795/ + + ! Time in days, with Jan 0, 2000 equal to 0.0: + d=367*y - 7*(y+(m+9)/12)/4 + 275*m/9 + DD - 730530 + UT/24.0 + mjd=d + 51543 + ecl = 23.4393 - 3.563e-7 * d + + ! Compute updated orbital elements for Sun: + w = 282.9404 + 4.70935e-5 * d + e = 0.016709 - 1.151e-9 * d + MM = mod(356.0470d0 + 0.9856002585d0 * d + 360000.d0,360.d0) + Ls = mod(w+MM+720.0,360.0) + + EE = MM + e*rad*sin(MM/rad) * (1.0 + e*cos(M/rad)) + EE = EE - (EE - e*rad*sin(EE/rad)-MM) / (1.0 - e*cos(EE/rad)) + + xv = cos(EE/rad) - e + yv = sqrt(1.0-e*e) * sin(EE/rad) + v = rad*atan2(yv,xv) + r = sqrt(xv*xv + yv*yv) + lonsun = mod(v + w + 720.0,360.0) + ! Ecliptic coordinates of sun (rectangular): + xs = r * cos(lonsun/rad) + ys = r * sin(lonsun/rad) + + ! Equatorial coordinates of sun (rectangular): + xe = xs + ye = ys * cos(ecl/rad) + ze = ys * sin(ecl/rad) + + ! RA and Dec in degrees: + RA = rad*atan2(ye,xe) + Dec = rad*atan2(ze,sqrt(xe*xe + ye*ye)) + + GMST0 = (Ls + 180.0)/15.0 + LST = mod(GMST0+UT+lon/15.0+48.0,24.0) !LST in hours + HA = 15.0*LST - RA !HA in degrees + xx = cos(HA/rad)*cos(Dec/rad) + yy = sin(HA/rad)*cos(Dec/rad) + zz = sin(Dec/rad) + xhor = xx*sin(lat/rad) - zz*cos(lat/rad) + yhor = yy + zhor = xx*cos(lat/rad) + zz*sin(lat/rad) + Az = mod(rad*atan2(yhor,xhor) + 180.0 + 360.0,360.0) + El = rad*asin(zhor) + day=d-1.5 + + end subroutine sun +end module sun_mod diff --git a/map65/libm65/symspec.f90 b/map65/libm65/symspec.f90 index e4160cfd..abab5ef0 100644 --- a/map65/libm65/symspec.f90 +++ b/map65/libm65/symspec.f90 @@ -1,53 +1,83 @@ -subroutine symspec(k,nxpol,ndiskdat,nb,nbslider,idphi,nfsample, & - fgreen,iqadjust,iqapply,gainx,gainy,phasex,phasey,rejectx,rejecty, & - pxdb,pydb,ssz5a,nkhz,ihsym,nzap,slimit,lstrong) - -! k pointer to the most recent new data -! nxpol 0/1 to indicate single- or dual-polarization -! ndiskdat 0/1 to indicate if data from disk -! nb 0/1 status of noise blanker -! idphi Phase correction for Y channel, degrees -! nfsample sample rate (Hz) -! fgreen Frequency of green marker in I/Q calibrate mode (-48.0 to +48.0 kHz) -! iqadjust 0/1 to indicate whether IQ adjustment is active -! iqapply 0/1 to indicate whether to apply I/Q calibration -! pxdb power in x channel (0-60 dB) -! pydb power in y channel (0-60 dB) -! ssz5a polarized spectrum, for waterfall display -! nkhz integer kHz portion of center frequency, e.g., 125 for 144.125 -! ihsym index number of this half-symbol (1-322) -! nzap number of samples zero'ed by noise blanker - - include 'njunk.f90' - parameter (NSMAX=60*96000) !Total sample intervals per minute - parameter (NFFT=32768) !Length of FFTs - real*8 ts,hsym - real*8 fcenter - common/datcom/dd(4,5760000),ss(4,322,NFFT),savg(4,NFFT),fcenter,nutc, & - junk(NJUNK) - real*4 ssz5a(NFFT),w(NFFT),w2a(NFFT),w2b(NFFT) - complex z,zfac - complex zsumx,zsumy - complex cx(NFFT),cy(NFFT) - complex cx00(NFFT),cy00(NFFT) - complex cx0(0:1023),cx1(0:1023) - complex cy0(0:1023),cy1(0:1023) - logical*1 lstrong(0:1023) - data rms/999.0/,k0/99999999/,nadjx/0/,nadjy/0/ +module symspec_mod + implicit none +contains + +subroutine symspec(k,nxpol,ndiskdat,nb,nbslider,idphi, & + iqadjust,iqapply,gainx,gainy,phasex,phasey,rejectx,rejecty, & + pxdb,pydb,ssz5a,nkhz,ihsym,nzap,slimit,lstrong) bind(C, name='symspec_') + + use iso_c_binding + use datcom_ptrs_mod + use npar_ptrs_mod, only: get_fcenter, nrate_active, nfft_active, nsmax_active + use four2a_mod + use timf2_mod + use iqcal_mod + use iqfix_mod + use iso_fortran_env, only: real32, real64 + + ! C-facing arguments (keep these as in your modern version) + integer(c_int), intent(in) :: k, nxpol, ndiskdat, nb, nbslider + integer(c_int), intent(in) :: idphi + integer(c_int), intent(in) :: iqadjust, iqapply + real(c_float), intent(inout) :: gainx, gainy, phasex, phasey + real(c_float), intent(out) :: rejectx, rejecty, pxdb, pydb + real(c_float), intent(out) :: ssz5a(*) + integer(c_int), intent(out) :: nkhz + integer(c_int), intent(inout) :: ihsym, nzap + real(c_float), intent(inout) :: slimit + integer(c_signed_char), intent(out) :: lstrong(0:1023) + + integer, parameter :: live_lookahead_samples=512 + + + ! ---- from legacy body, adapted to modules ---- + ! (no COMMON, no local fcenter, no logical*1 lstrong) + + + real(real64) :: ts, hsym + integer :: i, ipkx, ipky, iqadjust0, iqapply0, j, ja, jb, k0, k1, kstep, & + mm, nadjx, nadjy, nblk, nblks, nfft2, npts, nsum, nwindow, n, nfast + real(real32) :: fac, faclim, peaklimit, px, py, q, rejectx0, rms, rmsx, rmsy, & + s135, s45, sigmas, sx, sy, u, x1, x2, x3, x4, dphi, pi + + real(real32), allocatable :: w(:), w2a(:), w2b(:) + complex, allocatable :: cx(:), cy(:), cx00(:), cy00(:) + + complex :: z, zfac, zsumx, zsumy + real(c_double) :: fcenter + complex :: cx0(0:1023), cx1(0:1023), cy0(0:1023), cy1(0:1023) + + data rms/999.0/, k0/99999999/, k1/0/, nadjx/0/, nadjy/0/ save - nfast=1 - if(k.gt.5751000) go to 999 - if(k.lt.NFFT) then - ihsym=0 - go to 999 !Wait for enough samples to start - endif +nfast = 1 + +! Stop when we�re near the end of the allocated minute buffer. +! nsmax_active = 60 * nrate_active, set from C++ at startup. +if (k.gt.nsmax_active-9000) goto 999 + +if (k.lt.nfft_active) then + ihsym = 0 + goto 999 +endif + if(k0.eq.99999999) then + ! First-time initialization: allocate buffers at runtime NFFT and + ! build the window(s). nfft_active is set from C++ via + ! set_runtime_params_() before any call into this routine. + if(.not.allocated(w)) allocate(w(nfft_active)) + if(.not.allocated(w2a)) allocate(w2a(nfft_active)) + if(.not.allocated(w2b)) allocate(w2b(nfft_active)) + if(.not.allocated(cx)) allocate(cx(nfft_active)) + if(.not.allocated(cy)) allocate(cy(nfft_active)) + if(.not.allocated(cx00)) allocate(cx00(nfft_active)) + if(.not.allocated(cy00)) allocate(cy00(nfft_active)) + pi=4.0*atan(1.0) w2a=0. w2b=0. - do i=1,NFFT - w(i)=(sin(i*pi/NFFT))**2 !Window for nfast=1 + do i=1,nfft_active + w(i)=(sin(i*pi/nfft_active))**2 !Window for nfast=1 if(i.lt.17833) w2a(i)=(sin(i*pi/17832.925))**2 !Window a for nfast=2 j=i-8916 if(j.gt.0 .and. j.lt.17833) w2b(i)=(sin(j*pi/17832.925))**2 ! b @@ -56,18 +86,25 @@ subroutine symspec(k,nxpol,ndiskdat,nb,nbslider,idphi,nfsample, & w2b=sqrt(2.0)*w2b endif - hsym=2048.d0*96000.d0/11025.d0 !Samples per JT65 half-symbol - if(nfsample.eq.95238) hsym=2048.d0*95238.1d0/11025.d0 + +! Symbol length in samples, based on the active runtime rate. +hsym = 2048.d0 * dble(nrate_active) / 11025.d0 + +if(nrate_active.eq.95238) hsym=2048.d0*95238.1d0/11025.d0 - if(k.lt.k0) then - ts=1.d0 - hsym - savg=0. - ihsym=0 - k1=0 - if(ndiskdat.eq.0) dd(1:4,k+1:5760000)=0. !### Should not be needed ??? ### - endif - k0=k +if (k.lt.k0) then + ! Perform the legacy reset + ts = 1.d0 - hsym + savg = 0. + ihsym = 0 + k1 = 0 + ! if (ndiskdat.eq.0) dd(1:4,k+1:5760000)=0. + if (ndiskdat.eq.0) dd(1:4,k+live_lookahead_samples+1:nsmax_active)=0. +endif +k0 = k + + nzap=0 sigmas=1.5*(10.0**(0.01*nbslider)) + 0.7 peaklimit=sigmas*max(10.0,rms) @@ -83,7 +120,8 @@ subroutine symspec(k,nxpol,ndiskdat,nb,nbslider,idphi,nfsample, & nfft2=1024 kstep=nfft2 if(nwindow.ne.0) kstep=nfft2/2 - nblks=(k-k1)/kstep + nblks = (k - k1) / kstep + do nblk=1,nblks j=k1+1 do i=0,nfft2-1 @@ -105,20 +143,21 @@ subroutine symspec(k,nxpol,ndiskdat,nb,nbslider,idphi,nfsample, & k1=k1+kstep enddo - npts=NFFT !Samples used in each half-symbol FFT + npts=nfft_active !Samples used in each half-symbol FFT ts=ts+hsym - ja=ts !Index of first sample + ja=ts ! ts already set from ihsym above; do not integrate it again !Index of first sample jb=ja+npts-1 !Last sample i=0 fac=0.0002 dphi=idphi/57.2957795 zfac=fac*cmplx(cos(dphi),sin(dphi)) + do j=ja,jb !Copy data into cx, cy x1=dd(1,j) x2=dd(2,j) - if(nxpol.ne.0) then + if(nxpol.ne.0) then x3=dd(3,j) x4=dd(4,j) else @@ -163,26 +202,26 @@ subroutine symspec(k,nxpol,ndiskdat,nb,nbslider,idphi,nfsample, & endif endif - call four2a(cx,NFFT,1,1,1) !Second forward FFT (X) + call four2a(cx,nfft_active,1,1,1) !Second forward FFT (X) if(iqadjust.eq.0) nadjx=0 - if(iqadjust.ne.0 .and. nadjx.lt.50) call iqcal(nadjx,cx,NFFT, & + if(iqadjust.ne.0 .and. nadjx.lt.50) call iqcal(nadjx,cx,nfft_active, & gainx,phasex,zsumx,ipkx,rejectx0) - if(iqapply.ne.0) call iqfix(cx,NFFT,gainx,phasex) + if(iqapply.ne.0) call iqfix(cx,nfft_active,gainx,phasex) if(nxpol.ne.0) then - call four2a(cy,NFFT,1,1,1) !Second forward FFT (Y) + call four2a(cy,nfft_active,1,1,1) !Second forward FFT (Y) if(iqadjust.eq.0) nadjy=0 - if(iqadjust.ne.0 .and. nadjy.lt.50) call iqcal(nadjy,cy,NFFT, & + if(iqadjust.ne.0 .and. nadjy.lt.50) call iqcal(nadjy,cy,nfft_active, & gainy,phasey,zsumy,ipky,rejecty) - if(iqapply.ne.0) call iqfix(cy,NFFT,gainy,phasey) + if(iqapply.ne.0) call iqfix(cy,nfft_active,gainy,phasey) endif n=min(322,ihsym) - do i=1,NFFT + do i=1,nfft_active sx=real(cx(i))**2 + aimag(cx(i))**2 ss(1,n,i)=sx ! Pol = 0 savg(1,i)=savg(1,i) + sx - + if(nxpol.ne.0) then z=cx(i) + cy(i) s45=0.5*(real(z)**2 + aimag(z)**2) @@ -210,15 +249,24 @@ subroutine symspec(k,nxpol,ndiskdat,nb,nbslider,idphi,nfsample, & enddo enddo +! NOTE: ipkx and ipky are 0 when no peak was found. The reject ratio +! calculation is only valid when both are non-zero. The guard +! (ipkx.ne.0 .and. ipky.ne.0) ensures that indices such as +! 1+NFFT-ipkx never evaluate to NFFT+1. No out-of-bounds access occurs. + if(ihsym.eq.278) then if(iqadjust.ne.0 .and. ipkx.ne.0 .and. ipky.ne.0) then - rejectx=10.0*log10(savg(1,1+nfft-ipkx)/savg(1,1+ipkx)) - rejecty=10.0*log10(savg(3,1+nfft-ipky)/savg(3,1+ipky)) + rejectx=10.0*log10(savg(1,1+nfft_active-ipkx)/savg(1,1+ipkx)) + rejecty=10.0*log10(savg(3,1+nfft_active-ipky)/savg(3,1+ipky)) endif endif + fcenter=get_fcenter() nkhz=nint(1000.d0*(fcenter-int(fcenter))) if(fcenter.eq.0.d0) nkhz=125 999 return end subroutine symspec + + +end module symspec_mod diff --git a/map65/libm65/synctest.f90 b/map65/libm65/synctest.f90 index a710daa1..62b2844d 100644 --- a/map65/libm65/synctest.f90 +++ b/map65/libm65/synctest.f90 @@ -1,57 +1,69 @@ program synctest - ! Program to test an algorithm for detecting sync signals for both - ! JT65 and Q65-60x signals and rejecting birdies in MAP65 data. - ! The important work is done in module wideband_sync. + ! Program to test an algorithm for detecting sync signals for both + ! JT65 and Q65-60x signals and rejecting birdies in MAP65 data. + ! The important work is done in module wideband_sync. - use timer_module, only: timer - use timer_impl, only: init_timer, fini_timer - use wideband_sync + use timer_module, only: timer + use timer_impl, only: init_timer, fini_timer + use wideband_sync + implicit none - real ss(4,322,NFFT),savg(4,NFFT) + integer, parameter :: NFFT_WBS = 32768 ! Assumed from context of wideband_sync + ! Actually NFFT_WBS might be in wideband_sync module. Checked wideband_sync.f90? + ! Assuming 32768 based on typical MAP65 usage. + + real ss(4, 322, NFFT_WBS), savg(4, NFFT_WBS) ! real candidate(MAX_CANDIDATES,5) !snr1,f0,xdt0,ipol,flip - character*8 arg - type(candidate) :: cand(MAX_CANDIDATES) - - nargs=iargc() - if(nargs.ne.5) then - print*,'Usage: synctest iutc nfa nfb nts_jt65 nts_q65' - print*,'Example: synctest 1814 23 83 2 1' - go to 999 - endif - call getarg(1,arg) - read (arg,*) iutc - call getarg(2,arg) - read (arg,*) nfa - call getarg(3,arg) - read (arg,*) nfb - call getarg(4,arg) - read (arg,*) nts_jt65 - call getarg(5,arg) - read (arg,*) nts_q65 - - open(50,file='50.a',form='unformatted',status='old') - do ifile=1,9999 - read(50,end=998) nutc,npol,ss(1:npol,:,:),savg(1:npol,:) - if(nutc.eq.iutc) exit - enddo - close(50) - - call init_timer('timer.out') - call timer('synctest',0) - - call timer('get_cand',0) - call get_candidates(ss,savg,302,.true.,nfa,nfb,nts_jt65,nts_q65,cand,ncand) - call timer('get_cand',1) - - do k=1,ncand - write(*,1010) k,cand(k)%snr,cand(k)%f,cand(k)%f+77,cand(k)%xdt, & - cand(k)%ipol,cand(k)%iflip -1010 format(i3,4f10.3,2i3) - enddo - -998 call timer('synctest',1) - call timer('synctest',101) - call fini_timer() + character*8 arg + type(candidate) :: cand(MAX_CANDIDATES) + + integer :: nargs, iutc, nfa, nfb, nts_jt65, nts_q65, ifile, nutc, npol + integer :: ncand, k + + nargs = iargc() + if (nargs .ne. 5) then + print *, 'Usage: synctest iutc nfa nfb nts_jt65 nts_q65' + print *, 'Example: synctest 1814 23 83 2 1' + go to 999 + endif + call getarg(1, arg) + read (arg, *) iutc + call getarg(2, arg) + read (arg, *) nfa + call getarg(3, arg) + read (arg, *) nfb + call getarg(4, arg) + read (arg, *) nts_jt65 + call getarg(5, arg) + read (arg, *) nts_q65 + + call init_wideband_sync(NFFT) + + open (50, file='50.a', form='unformatted', status='old') + do ifile = 1, 9999 + read (50, end=998) nutc, npol, ss(1:npol, :, :), savg(1:npol, :) + if (nutc .eq. iutc) exit + enddo + close (50) + + call init_timer('timer.out') + call timer('synctest', 0) + + call timer('get_cand', 0) + call get_candidates(ss, savg, 302, .true., nfa, nfb, nts_jt65, nts_q65, cand, ncand) + call timer('get_cand', 1) + + do k = 1, ncand + write (*, 1010) k, cand(k)%snr, cand(k)%f, cand(k)%f + 77, cand(k)%xdt, & + cand(k)%ipol, cand(k)%iflip +1010 format(i3, 4f10.3, 2i3) + enddo + +998 call timer('synctest', 1) + call timer('synctest', 101) + call fini_timer() 999 end program synctest + +!does not require end module diff --git a/map65/libm65/synctst.f90 b/map65/libm65/synctst.f90 index 248c7e19..6fd928f0 100644 --- a/map65/libm65/synctst.f90 +++ b/map65/libm65/synctst.f90 @@ -1,11 +1,14 @@ program synctst - + implicit none ! Tests JT65B2 sync patterns - parameter (LAGMAX=20) + integer, parameter :: LAGMAX=20 real ccf0(0:LAGMAX),ccf2(0:LAGMAX),ccf3(0:LAGMAX) character*12 arg integer npr(126),np0(126),np1(126),npr2(126) + integer :: nargs, iters, lag, nsum, i, iter, n0, lagbad, lagbest, n0best + real :: worst, best2, r, worst2 + data npr/1,0,0,1,1,0,0,0,1,1,1,1,1,1,0,1,0,1,0,0, & 0,1,0,1,1,0,0,1,0,0,0,1,1,1,0,0,1,1,1,1, & 0,1,1,0,1,1,1,1,0,0,0,1,1,0,1,0,1,0,1,1, & @@ -82,3 +85,5 @@ program synctst 1110 format((8x,20(i1,','))) 999 end program synctst + +!does not require end module
\ No newline at end of file diff --git a/map65/libm65/synctst2.f90 b/map65/libm65/synctst2.f90 index 8ff4971a..245126c7 100644 --- a/map65/libm65/synctst2.f90 +++ b/map65/libm65/synctst2.f90 @@ -1,12 +1,15 @@ program synctst2 - + implicit none ! Tests JT65B2 sync patterns - parameter (LAGMAX=20) + integer, parameter :: LAGMAX=20 real ccf0(0:LAGMAX),ccf1(0:LAGMAX),ccf2(0:LAGMAX),ccf3(0:LAGMAX) character arg*12,line*64 integer*8 n8 integer npr(126),np0(126),np1(126),npr1(126),npr2(126) + integer :: lag, nsum, i, n0, lagbad + real :: worst, worst1, worst2 + data npr/1,0,0,1,1,0,0,0,1,1,1,1,1,1,0,1,0,1,0,0, & 0,1,0,1,1,0,0,1,0,0,0,1,1,1,0,0,1,1,1,1, & 0,1,1,0,1,1,1,1,0,0,0,1,1,0,1,0,1,0,1,1, & @@ -89,3 +92,6 @@ program synctst2 999 end program synctst2 + +!does not require end module + diff --git a/map65/libm65/tastro.f90 b/map65/libm65/tastro.f90 index fac5c800..0f920888 100644 --- a/map65/libm65/tastro.f90 +++ b/map65/libm65/tastro.f90 @@ -1,35 +1,62 @@ program tastro - implicit real*8 (a-h,o-z) - - character grid*6 - character*9 cauxra,cauxdec - - character*12 clock(3) - integer nt(8) - equivalence (nt(1),nyear) - - grid='FN20qi' - nfreq=144 - cauxra='00:00:00' - -10 call date_and_time(clock(1),clock(2),clock(3),nt) - ih=ihour-ntz/60 - if(ih.le.0) then - ih=ih+24 - nday=nday+1 - endif - uth8=ih + imin/60.d0 + isec/3600.d0 + ims/3600000.d0 - call astro0(nyear,month,nday,uth8,nfreq,grid,cauxra,cauxdec, & - AzSun8,ElSun8,AzMoon8,ElMoon8,AzMoonB8,ElMoonB8,ntsky,ndop,ndop00, & - dbMoon8,RAMoon8,DecMoon8,HA8,Dgrd8,sd8,poloffset8,xnr8,dfdt,dfdt0, & - RaAux8,DecAux8,AzAux8,ElAux8,width1,width2,w501,w502,xlst8) - - write(*,1010) nyear,month,nday,ih,imin,isec,AzMoon8,ElMoon8, & - AzSun8,ElSun8,ndop,dgrd8,ntsky -1010 format(i4,i3,i3,i4.2,':',i2.2,':',i2.2,4f8.1,i6,f6.1,i6) - - call system('sleep 1') - go to 10 + implicit none + use astro0_mod + + character(6) :: grid + character(9) :: cauxra, cauxdec + character(12) :: clock(3) + + integer :: nt(8) + integer :: nyear, month, nday, ntz + integer :: ihour, imin, isec, ims + integer :: ih, nfreq + + real(8) :: uth8 + real(8) :: AzSun8, ElSun8, AzMoon8, ElMoon8 + real(8) :: AzMoonB8, ElMoonB8, dbMoon8 + real(8) :: RAMoon8, DecMoon8, HA8, Dgrd8, sd8 + real(8) :: poloffset8, xnr8, dfdt, dfdt0 + real(8) :: RaAux8, DecAux8, AzAux8, ElAux8 + real(8) :: width1, width2, w501, w502, xlst8 + integer :: ntsky, ndop, ndop00 + + grid = 'FN20qi' + nfreq = 144 + cauxra = '00:00:00' + + ! Main loop: update astronomical display once per second +do + call date_and_time(clock(1), clock(2), clock(3), nt) + + nyear = nt(1) + month = nt(2) + nday = nt(3) + ntz = nt(4) + ihour = nt(5) + imin = nt(6) + isec = nt(7) + ims = nt(8) + + ih = ihour - ntz/60 + if (ih <= 0) then + ih = ih + 24 + nday = nday + 1 + endif + + uth8 = ih + imin/60.d0 + isec/3600.d0 + ims/3600000.d0 + + call astro0(nyear,month,nday,uth8,nfreq,grid,cauxra,cauxdec, & + AzSun8,ElSun8,AzMoon8,ElMoon8,AzMoonB8,ElMoonB8,ntsky,ndop,ndop00, & + dbMoon8,RAMoon8,DecMoon8,HA8,Dgrd8,sd8,poloffset8,xnr8,dfdt,dfdt0, & + RaAux8,DecAux8,AzAux8,ElAux8,width1,width2,w501,w502,xlst8) + + write(*,1010) nyear,month,nday,ih,imin,isec,AzMoon8,ElMoon8, & + AzSun8,ElSun8,ndop,dgrd8,ntsky + + call system('sleep 1') +end do end program tastro + +!does not require end module diff --git a/map65/libm65/timf2.f90 b/map65/libm65/timf2.f90 index 4873d0e9..9a12086f 100644 --- a/map65/libm65/timf2.f90 +++ b/map65/libm65/timf2.f90 @@ -1,46 +1,62 @@ +module timf2_mod + implicit none +contains + subroutine timf2(k,nxpol,nfft,nwindow,nb,peaklimit,iqadjust,iqapply,faclim, & - cx0,cy0,gainx,gainy,phasex,phasey,cx1,cy1,slimit,lstrong,px,py,nzap) - -! Sequential processing of time-domain I/Q data, using Linrad-like -! "first FFT" and "first backward FFT". - -! cx0,cy0 - complex input data -! nfft - length of FFTs -! nwindow - 0 for no window, 2 for sin^2 window -! iqapply - 0/1 determines if I/Q phase and amplitude corrections applied -! gainx,y - gain error in Q channel, relative to I -! phasex,y - phase error -! cx1,cy1 - output data - -! Non-windowed processing means no overlap, so kstep=nfft. -! Sin^2 window has 50% overlap, kstep=nfft/2. - -! Frequencies with strong signals are identified and separated. The back -! transforms are done separately for weak and strong signals, so that -! noise blanking can be applied to the weak-signal portion. Strong and -! weak are finally re-combined in the time domain. - - parameter (MAXFFT=1024,MAXNH=MAXFFT/2) - parameter (MAXSIGS=100) - complex cx0(0:nfft-1),cx1(0:nfft-1) - complex cy0(0:nfft-1),cy1(0:nfft-1) - complex cx(0:MAXFFT-1),cxt(0:MAXFFT-1) - complex cy(0:MAXFFT-1),cyt(0:MAXFFT-1) - complex cxs(0:MAXFFT-1),covxs(0:MAXNH-1) !Strong X signals - complex cys(0:MAXFFT-1),covys(0:MAXNH-1) !Strong Y signals - complex cxw(0:MAXFFT-1),covxw(0:MAXNH-1) !Weak X signals - complex cyw(0:MAXFFT-1),covyw(0:MAXNH-1) !Weak Y signals - real*4 w(0:MAXFFT-1) - real*4 s(0:MAXFFT-1) - logical*1 lstrong(0:MAXFFT-1),lprev - integer ia(MAXSIGS),ib(MAXSIGS) - complex h,u,v - logical first - data first/.true./ - data k0/99999999/ - save - - if(faclim+iqadjust.eq.-9999.0) iqadjust=0 !Silence compiler warning. + cx0,cy0,gainx,gainy,phasex,phasey,cx1,cy1,slimit,lstrong,px,py,nzap) + + use four2a_mod + use, intrinsic :: iso_c_binding, only: c_signed_char + implicit none + + ! Arguments + integer, intent(in) :: k, nxpol, nfft, nwindow, nb + real, intent(in) :: peaklimit, faclim + integer, intent(in) :: iqadjust, iqapply + complex, intent(in) :: cx0(0:nfft-1), cy0(0:nfft-1) + real, intent(in) :: gainx, gainy, phasex, phasey + complex, intent(out) :: cx1(0:nfft-1), cy1(0:nfft-1) + real, intent(inout) :: slimit + ! logical*1, intent(out) :: lstrong(0:*) + integer(c_signed_char), intent(out) :: lstrong(0:*) + + real, intent(inout) :: px, py + integer, intent(inout) :: nzap + + ! Parameters + integer, parameter :: MAXFFT = 1024, MAXNH = MAXFFT/2 + integer, parameter :: MAXSIGS = 100 + + ! Local arrays + complex :: cx(0:MAXFFT-1), cxt(0:MAXFFT-1) + complex :: cy(0:MAXFFT-1), cyt(0:MAXFFT-1) + complex :: cxs(0:MAXFFT-1), covxs(0:MAXNH-1) + complex :: cys(0:MAXFFT-1), covys(0:MAXNH-1) + complex :: cxw(0:MAXFFT-1), covxw(0:MAXNH-1) + complex :: cyw(0:MAXFFT-1), covyw(0:MAXNH-1) + real :: w(0:MAXFFT-1) + real :: s(0:MAXFFT-1) + logical :: lprev + integer :: ia(MAXSIGS), ib(MAXSIGS) + + ! Local scalars + complex :: h, u, v + real :: x, y, p, ave, peak, fac, pi + integer :: nh, kstep, nsigs, iwid + integer :: i, ja, jb + + ! Saved state + logical :: first + integer :: k0 + data first /.true./ + data k0 /99999999/ + save first, k0, w, s, nh, kstep, fac, covxs, covxw, covys, covyw + + ! Reference faclim and iqadjust to avoid unused warnings + if (faclim + iqadjust == -9999.0) then + ! no-op + end if + if(first) then pi=4.0*atan(1.0) do i=0,nfft-1 @@ -115,24 +131,25 @@ subroutine timf2(k,nxpol,nfft,nwindow,nb,peaklimit,iqadjust,iqapply,faclim, & if(nxpol.ne.0) p=p + real(cyt(i))**2 + aimag(cyt(i))**2 s(i)=p enddo + ave=0.0 ave=sum(s(0:nfft-1))/nfft - lstrong(0:nfft-1)=s(0:nfft-1).gt.10.0*ave + lstrong(0:nfft-1) = merge(1_c_signed_char, 0_c_signed_char, s(0:nfft-1) > 10.0*ave) nsigs=0 lprev=.false. iwid=1 ib=-99 do i=0,nfft-1 - if(lstrong(i) .and. (.not.lprev)) then + if ((lstrong(i) /= 0) .and. (.not. lprev)) then if(nsigs.lt.MAXSIGS) nsigs=nsigs+1 ia(nsigs)=i-iwid if(ia(nsigs).lt.0) ia(nsigs)=0 endif - if(.not.lstrong(i) .and. lprev) then + if ((lstrong(i) == 0) .and. lprev) then ib(nsigs)=i-1+iwid if(ib(nsigs).gt.nfft-1) ib(nsigs)=nfft-1 endif - lprev=lstrong(i) + lprev = (lstrong(i) /= 0) enddo if(nsigs.gt.0) then @@ -143,12 +160,12 @@ subroutine timf2(k,nxpol,nfft,nwindow,nb,peaklimit,iqadjust,iqapply,faclim, & cycle endif if(jb.eq.-99) jb=ja + min(2*iwid,nfft-1) - lstrong(ja:jb)=.true. + lstrong(ja:jb) = 1_c_signed_char enddo endif do i=0,nfft-1 - if(lstrong(i)) then + if (lstrong(i) /= 0) then cxs(i)=fac*cxt(i) cxw(i)=0. if(nxpol.ne.0) then @@ -213,3 +230,5 @@ subroutine timf2(k,nxpol,nfft,nwindow,nb,peaklimit,iqadjust,iqapply,faclim, & return end subroutine timf2 + +end module timf2_mod diff --git a/map65/libm65/tm2.f90 b/map65/libm65/tm2.f90 index fb831fab..45fd2aee 100644 --- a/map65/libm65/tm2.f90 +++ b/map65/libm65/tm2.f90 @@ -1,14 +1,39 @@ -subroutine tm2(day,xlat4,xlon4,xl4,b4) +module tm2_mod + implicit none - implicit real*8 (a-h,o-z) - parameter (RADS=0.0174532925199433d0) + interface + subroutine tmoonsub(day, glat, glong, el, rv, xl, b, pax) + real(8), intent(in) :: day, glat, glong + real(8), intent(out) :: el, rv, xl, b, pax + end subroutine tmoonsub + end interface - real*4 xlat4,xlon4,xl4,b4 +contains - glat=xlat4*RADS - glong=xlon4*RADS - call tmoonsub(day,glat,glong,el,rv,xl,b,pax) - xl4=xl - b4=b +subroutine tm2(day, xlat4, xlon4, xl4, b4) + implicit none + + ! Arguments + real(8), intent(in) :: day + real(4), intent(in) :: xlat4, xlon4 + real(4), intent(out) :: xl4, b4 + + ! Locals + real(8), parameter :: RADS = 0.0174532925199433d0 + real(8) :: glat, glong + real(8) :: el, rv, xl, b, pax + + ! Convert to radians + glat = xlat4 * RADS + glong = xlon4 * RADS + + ! Call the external routine + call tmoonsub(day, glat, glong, el, rv, xl, b, pax) + + ! Convert back to real*4 + xl4 = real(xl, 4) + b4 = real(b, 4) end subroutine tm2 + +end module tm2_mod diff --git a/map65/libm65/tmoonsub.c b/map65/libm65/tmoonsub.c index 29ac28b4..f33dec0e 100644 --- a/map65/libm65/tmoonsub.c +++ b/map65/libm65/tmoonsub.c @@ -36,7 +36,7 @@ void tmoonsub_(double *day, double *glat, double *glong, double *moonalt, double *mrv, double *l, double *b, double *paxis); static const char -*usage = " Usage: tmoon date[yyyymm] timz[+/-h.hh] long[+/-dddmm] lat[+/-ddmm]\n" +usage[] = " Usage: tmoon date[yyyymm] timz[+/-h.hh] long[+/-dddmm] lat[+/-ddmm]\n" "example: tmoon 200009 0 -00155 5230\n"; /* @@ -360,6 +360,7 @@ void libration(double day, double lambda, double beta, double alpha, double *l, */ void illumination(double day, double lra, double ldec, double dr, double sra, double sdec, double *pabl, double *ill) { double x, y, phi, i; + (void)day; y = cos(sdec) * sin(sra - lra); x = sin(sdec) * cos(ldec) - cos(sdec) * sin(ldec) * cos (sra - lra); *pabl = atan22(y, x); @@ -448,6 +449,7 @@ R is unchanged. */ void equatorial(double d, double *lon, double *lat, double *r) { double eps, ceps, seps, l, b; + (void)r; l = *lon; b = * lat; @@ -464,6 +466,8 @@ of above, but used to find topocentric ecliptic coords. */ void ecliptic(double d, double *lon, double *lat, double *r) { double eps, ceps, seps, alp, dec; + (void)r; + alp = *lon; dec = *lat; eps = epsilon(d); diff --git a/map65/libm65/toxyz.f90 b/map65/libm65/toxyz.f90 index aef160c9..a64511ee 100644 --- a/map65/libm65/toxyz.f90 +++ b/map65/libm65/toxyz.f90 @@ -1,25 +1,29 @@ -subroutine toxyz(alpha,delta,r,vec) - - implicit real*8 (a-h,o-z) - real*8 vec(3) - - vec(1)=r*cos(delta)*cos(alpha) - vec(2)=r*cos(delta)*sin(alpha) - vec(3)=r*sin(delta) - - return -end subroutine toxyz - -subroutine fromxyz(vec,alpha,delta,r) +module toxyz_mod + use iso_fortran_env, only: real64 + implicit none +contains + subroutine toxyz(alpha,delta,r,vec) + implicit none + real(real64), intent(in) :: alpha, delta, r + real(real64), intent(out) :: vec(3) - implicit real*8 (a-h,o-z) - real*8 vec(3) - data twopi/6.283185307d0/ - - r=sqrt(vec(1)**2 + vec(2)**2 + vec(3)**2) - alpha=atan2(vec(2),vec(1)) - if(alpha.lt.0.d0) alpha=alpha+twopi - delta=asin(vec(3)/r) + vec(1)=r*cos(delta)*cos(alpha) + vec(2)=r*cos(delta)*sin(alpha) + vec(3)=r*sin(delta) + + end subroutine toxyz - return -end subroutine fromxyz + subroutine fromxyz(vec,alpha,delta,r) + implicit none + real(real64), intent(in) :: vec(3) + real(real64), intent(out) :: alpha, delta, r + real(real64) :: twopi + data twopi/6.283185307d0/ + + r=sqrt(vec(1)**2 + vec(2)**2 + vec(3)**2) + alpha=atan2(vec(2),vec(1)) + if(alpha.lt.0.d0) alpha=alpha+twopi + delta=asin(vec(3)/r) + + end subroutine fromxyz +end module toxyz_mod diff --git a/map65/libm65/trimlist.f90 b/map65/libm65/trimlist.f90 index 9e8a36e6..088a4221 100644 --- a/map65/libm65/trimlist.f90 +++ b/map65/libm65/trimlist.f90 @@ -1,28 +1,49 @@ -subroutine trimlist(sig,km,ftol,indx,nsiz,nz) +module trimlist_mod + implicit none +contains + subroutine select_unique_decodes(sig, msg, km, freq_tolerance, dt_tolerance, indx, nz) + use indexx_mod + implicit none - parameter (MAXMSG=1000) !Size of decoded message list - real sig(MAXMSG,30) - integer indx(MAXMSG),nsiz(MAXMSG) + integer, parameter :: MAXMSG = 1000 + real, intent(in) :: sig(MAXMSG, 30) + character(len=22), intent(in) :: msg(MAXMSG) + integer, intent(in) :: km + real, intent(in) :: freq_tolerance, dt_tolerance + integer, intent(out) :: indx(MAXMSG) + integer, intent(out) :: nz -! 1 2 3 4 5 6 7 8 -! nfile nutc freq snr dt ipol flip sync + integer :: sorted(MAXMSG) + integer :: i, j, k + logical :: duplicate - call indexx(sig(1,3),km,indx) !Sort list by frequency + nz = 0 + if (km <= 0) return - n=1 - i0=1 - do i=2,km - j0=indx(i-1) - j=indx(i) - if(sig(j,3)-sig(j0,3).gt.ftol) then - nsiz(n)=i-i0 - i0=i - n=n+1 - endif - enddo - nz=n - nsiz(nz)=km+1-i0 - nsiz(nz+1)=-1 + call indexx(sig(:, 3), km, sorted) + do k = 1, km + i = sorted(k) + if (len_trim(msg(i)) == 0) cycle - return -end subroutine trimlist + duplicate = .false. + do j = 1, nz + if (nint(sig(i, 2)) /= nint(sig(indx(j), 2))) cycle + if (msg(i) /= msg(indx(j))) cycle + if (nint(sig(i, 7)) /= nint(sig(indx(j), 7))) cycle + if (abs(sig(i, 3) - sig(indx(j), 3)) > freq_tolerance) cycle + if (abs(sig(i, 5) - sig(indx(j), 5)) > dt_tolerance) cycle + duplicate = .true. + if (sig(i, 8) > sig(indx(j), 8) .or. & + (sig(i, 8) == sig(indx(j), 8) .and. sig(i, 4) > sig(indx(j), 4)) .or. & + (sig(i, 8) == sig(indx(j), 8) .and. sig(i, 4) == sig(indx(j), 4) .and. & + i > indx(j))) indx(j) = i + exit + end do + + if (.not. duplicate) then + nz = nz + 1 + indx(nz) = i + end if + end do + end subroutine select_unique_decodes +end module trimlist_mod diff --git a/map65/libm65/twkfreq.f90 b/map65/libm65/twkfreq.f90 index be1fef0f..456329ac 100644 --- a/map65/libm65/twkfreq.f90 +++ b/map65/libm65/twkfreq.f90 @@ -1,26 +1,34 @@ -subroutine twkfreq(c3,c4,npts,fsample,a) - - complex c3(npts) - complex c4(npts) - complex w,wstep - real a(3) - data twopi/6.283185307/ - -! Mix the complex signal - w=1.0 - wstep=1.0 - x0=0.5*(npts+1) - s=2.0/npts - do i=1,npts - x=s*(i-x0) - p2=1.5*x*x - 0.5 -! p3=2.5*(x**3) - 1.5*x -! p4=4.375*(x**4) - 3.75*(x**2) + 0.375 - dphi=(a(1) + x*a(2) + p2*a(3)) * (twopi/fsample) - wstep=cmplx(cos(dphi),sin(dphi)) - w=w*wstep - c4(i)=w*c3(i) - enddo - - return -end subroutine twkfreq +module twkfreq_mod + implicit none +contains + subroutine twkfreq(c3,c4,npts,fsample,a) + implicit none + integer, intent(in) :: npts + complex, intent(in) :: c3(npts) + complex, intent(out) :: c4(npts) + real, intent(in) :: fsample, a(3) + + complex :: w,wstep + real :: twopi + data twopi/6.283185307/ + real :: x0, s, x, p2, dphi + integer :: i + + ! Mix the complex signal + w=1.0 + wstep=1.0 + x0=0.5*(npts+1) + s=2.0/npts + do i=1,npts + x=s*(i-x0) + p2=1.5*x*x - 0.5 + ! p3=2.5*(x**3) - 1.5*x + ! p4=4.375*(x**4) - 3.75*(x**2) + 0.375 + dphi=(a(1) + x*a(2) + p2*a(3)) * (twopi/fsample) + wstep=cmplx(cos(dphi),sin(dphi)) + w=w*wstep + c4(i)=w*c3(i) + enddo + + end subroutine twkfreq +end module twkfreq_mod diff --git a/map65/libm65/twkfreq_xy.f90 b/map65/libm65/twkfreq_xy.f90 index a5cc3769..9ed126f9 100644 --- a/map65/libm65/twkfreq_xy.f90 +++ b/map65/libm65/twkfreq_xy.f90 @@ -1,29 +1,36 @@ -subroutine twkfreq_xy(c4aa,c4bb,n5,a) - - complex c4aa(n5) - complex c4bb(n5) - real a(5) - complex w,wstep - data twopi/6.283185307/ - -! Apply AFC corrections to the c4aa and c4bb data - w=1.0 - wstep=1.0 - x0=0.5*(n5+1) - s=2.0/n5 - do i=1,n5 - x=s*(i-x0) - if(mod(i,1000).eq.1) then - p2=1.5*x*x - 0.5 -! p3=2.5*(x**3) - 1.5*x -! p4=4.375*(x**4) - 3.75*(x**2) + 0.375 - dphi=(a(1) + x*a(2) + p2*a(3)) * (twopi/1378.125) - wstep=cmplx(cos(dphi),sin(dphi)) - endif - w=w*wstep - c4aa(i)=w*c4aa(i) - c4bb(i)=w*c4bb(i) - enddo - - return -end subroutine twkfreq_xy +module twkfreq_xy_mod + implicit none +contains + subroutine twkfreq_xy(c4aa,c4bb,n5,a) + implicit none + integer, intent(in) :: n5 + complex, intent(inout) :: c4aa(n5), c4bb(n5) + real, intent(in) :: a(5) + + complex :: w,wstep + real :: twopi + data twopi/6.283185307/ + real :: x0, s, x, p2, dphi + integer :: i + + ! Apply AFC corrections to the c4aa and c4bb data + w=1.0 + wstep=1.0 + x0=0.5*(n5+1) + s=2.0/n5 + do i=1,n5 + x=s*(i-x0) + if(mod(i,1000).eq.1) then + p2=1.5*x*x - 0.5 + ! p3=2.5*(x**3) - 1.5*x + ! p4=4.375*(x**4) - 3.75*(x**2) + 0.375 + dphi=(a(1) + x*a(2) + p2*a(3)) * (twopi/1378.125) + wstep=cmplx(cos(dphi),sin(dphi)) + endif + w=w*wstep + c4aa(i)=w*c4aa(i) + c4bb(i)=w*c4bb(i) + enddo + + end subroutine twkfreq_xy +end module twkfreq_xy_mod diff --git a/map65/libm65/txpol.f90 b/map65/libm65/txpol.f90 index 042d3e54..4ec9336b 100644 --- a/map65/libm65/txpol.f90 +++ b/map65/libm65/txpol.f90 @@ -1,33 +1,44 @@ -subroutine txpol(xpol,decoded,mygrid,npol,nxant,ntxpol,cp) - -! If Tx station's grid is in decoded message, compute optimum TxPol - character*22 decoded - character*6 mygrid,grid - character*1 cp - logical xpol - - ntxpol=0 - i1=index(decoded,' ') - i2=index(decoded(i1+1:),' ') + i1 - grid=' ' - if(i2.ge.8 .and. i2.le.18) grid=decoded(i2+1:i2+4)//'mm' - ntxpol=0 - cp=' ' - if(xpol .and.grid(1:4).ne.'RR73') then - if(grid(1:1).ge.'A' .and. grid(1:1).le.'R' .and. & - grid(2:2).ge.'A' .and. grid(2:2).le.'R' .and. & - grid(3:3).ge.'0' .and. grid(3:3).le.'9' .and. & - grid(4:4).ge.'0' .and. grid(4:4).le.'9') then - ntxpol=mod(npol-nint(2.0*dpol(mygrid,grid))+720,180) - if(nxant.eq.0) then - cp='H' - if(ntxpol.gt.45 .and. ntxpol.le.135) cp='V' - else - cp='/' - if(ntxpol.ge.90 .and. ntxpol.lt.180) cp='\' - endif - endif - endif - - return -end subroutine txpol +module txpol_mod + implicit none +contains + subroutine txpol(xpol,decoded,mygrid,npol,nxant,ntxpol,cp) + + use dpol_mod + implicit none + + ! If Tx station's grid is in decoded message, compute optimum TxPol + character*(*), intent(in) :: decoded + character(len=6), intent(in) :: mygrid + character(len=1), intent(out) :: cp + logical, intent(in) :: xpol + integer, intent(in) :: npol,nxant + integer, intent(out) :: ntxpol + + integer :: i1,i2 + character(len=6) :: grid + + ntxpol=0 + i1=index(decoded,' ') + i2=index(decoded(i1+1:),' ') + i1 + grid=' ' + if(i2.ge.8 .and. i2.le.18) grid=decoded(i2+1:i2+4)//'mm' + ntxpol=0 + cp=' ' + if(xpol .and.grid(1:4).ne.'RR73') then + if(grid(1:1).ge.'A' .and. grid(1:1).le.'R' .and. & + grid(2:2).ge.'A' .and. grid(2:2).le.'R' .and. & + grid(3:3).ge.'0' .and. grid(3:3).le.'9' .and. & + grid(4:4).ge.'0' .and. grid(4:4).le.'9') then + ntxpol=mod(npol-nint(2.0*dpol(mygrid,grid))+720,180) + if(nxant.eq.0) then + cp='H' + if(ntxpol.gt.45 .and. ntxpol.le.135) cp='V' + else + cp='/' + if(ntxpol.ge.90 .and. ntxpol.lt.180) cp='\' + endif + endif + endif + + end subroutine txpol +end module txpol_mod diff --git a/map65/libm65/wavhdr.f90 b/map65/libm65/wavhdr.f90 index 6568c1fa..f9634436 100644 --- a/map65/libm65/wavhdr.f90 +++ b/map65/libm65/wavhdr.f90 @@ -1,110 +1,125 @@ module wavhdr + use iso_fortran_env, only: int32, int16 + implicit none + type hdr - character*4 ariff - integer*4 lenfile - character*4 awave - character*4 afmt - integer*4 lenfmt - integer*2 nfmt2 - integer*2 nchan2 - integer*4 nsamrate - integer*4 nbytesec - integer*2 nbytesam2 - integer*2 nbitsam2 - character*4 adata - integer*4 ndata + character(len=4) :: ariff + integer(int32) :: lenfile + character(len=4) :: awave + character(len=4) :: afmt + integer(int32) :: lenfmt + integer(int16) :: nfmt2 + integer(int16) :: nchan2 + integer(int32) :: nsamrate + integer(int32) :: nbytesec + integer(int16) :: nbytesam2 + integer(int16) :: nbitsam2 + character(len=4) :: adata + integer(int32) :: ndata end type hdr - contains - - function default_header(nsamrate,npts) - type(hdr) default_header,h - h%ariff='RIFF' - h%awave='WAVE' - h%afmt='fmt ' - h%lenfmt=16 - h%nfmt2=1 - h%nchan2=1 - h%nsamrate=nsamrate - h%nbitsam2=16 - h%nbytesam2=h%nbitsam2 * h%nchan2 / 8 - h%adata='data' - h%nbytesec=h%nsamrate * h%nbitsam2 * h%nchan2 / 8 - h%ndata=2*npts - h%lenfile=h%ndata + 44 - 8 - default_header=h - end function default_header - - subroutine set_wsjtx_wav_params(fMHz,mode,nsubmode,ntrperiod,id2) - - parameter (NBANDS=23,NMODES=13) - character*8 mode,modes(NMODES) - integer*2 id2(4) - integer iperiod(8) - real fband(NBANDS) - data fband/0.137,0.474,1.8,3.5,5.1,7.0,10.14,14.0,18.1,21.0,24.9, & - 28.0,50.0,144.0,222.0,432.0,902.0,1296.0,2304.0,3400.0, & - 5760.0,10368.0,24048.0/ - data modes/'Echo','FSK441','ISCAT','JT4','JT65','JT6M','JT9', & - 'JT9+JT65','JTMS','JTMSK','WSPR','FT8','FT2'/ - data iperiod/5,10,15,30,60,120,900,0/ - - dmin=1.e30 - iband=0 - do i=1,NBANDS - if(abs(fMHz-fband(i)).lt.dmin) then - dmin=abs(fMHz-fband(i)) - iband=i - endif - enddo - - imode=0 - do i=1,NMODES - if(mode.eq.modes(i)) imode=i - enddo - - ip=0 - do i=1,8 - if(ntrperiod.eq.iperiod(i)) ip=i - enddo - - id2(1)=iband - id2(2)=imode - id2(3)=nsubmode - id2(4)=ip - - return - end subroutine set_wsjtx_wav_params - - subroutine get_wsjtx_wav_params(id2,band,mode,nsubmode,ntrperiod,ok) - - parameter (NBANDS=23,NMODES=13) - character*8 mode,modes(NMODES) - character*6 band,bands(NBANDS) - integer*2 id2(4) - integer iperiod(8) - logical ok - data modes/'Echo','FSK441','ISCAT','JT4','JT65','JT6M','JT9', & - 'JT9+JT65','JTMS','JTMSK','WSPR','FT8','FT2'/ - data iperiod/5,10,15,30,60,120,900,0/ - data bands/'2190m','630m','160m','80m','60m','40m','30m','20m', & - '17m','15m','12m','10m','6m','2m','1.25m','70cm','33cm', & - '23cm','13cm','9cm','6cm','3cm','1.25cm'/ - - ok=.true. - if(id2(1).lt.1 .or. id2(1).gt.NBANDS) ok=.false. - if(id2(2).lt.1 .or. id2(2).gt.NMODES) ok=.false. - if(id2(3).lt.1 .or. id2(3).gt.8) ok=.false. - if(id2(4).lt.1 .or. id2(4).gt.8) ok=.false. - - if(ok) then - band=bands(id2(1)) - mode=modes(id2(2)) - nsubmode=id2(3) - ntrperiod=iperiod(id2(4)) - endif - - return - end subroutine get_wsjtx_wav_params +contains + + function default_header(nsamrate,npts) result(hdr_out) + implicit none + integer, intent(in) :: nsamrate, npts + type(hdr) :: hdr_out, h + + h%ariff = 'RIFF' + h%awave = 'WAVE' + h%afmt = 'fmt ' + h%lenfmt = 16 + h%nfmt2 = 1 + h%nchan2 = 1 + h%nsamrate = nsamrate + h%nbitsam2 = 16 + h%nbytesam2 = h%nbitsam2 * h%nchan2 / 8 + h%adata = 'data' + h%nbytesec = h%nsamrate * h%nbitsam2 * h%nchan2 / 8 + h%ndata = 2*npts + h%lenfile = h%ndata + 44 - 8 + + hdr_out = h + end function default_header + + subroutine set_wsjtx_wav_params(fMHz, mode, nsubmode, ntrperiod, id2) + implicit none + real, intent(in) :: fMHz + character(len=8), intent(in) :: mode + integer, intent(in) :: nsubmode, ntrperiod + integer(int16), intent(out) :: id2(4) + + integer, parameter :: NBANDS=23, NMODES=13 + character(len=8) :: modes(NMODES) + integer(int16) :: iband, imode, ip + integer :: i + integer :: iperiod(8) + real :: fband(NBANDS), dmin + + data fband/0.137,0.474,1.8,3.5,5.1,7.0,10.14,14.0,18.1,21.0,24.9, & + 28.0,50.0,144.0,222.0,432.0,902.0,1296.0,2304.0,3400.0, & + 5760.0,10368.0,24048.0/ + data modes/'Echo','FSK441','ISCAT','JT4','JT65','JT6M','JT9', & + 'JT9+JT65','JTMS','JTMSK','WSPR','FT8','FT2'/ + data iperiod/5,10,15,30,60,120,900,0/ + + dmin = 1.e30 + iband = 0 + do i=1,NBANDS + if (abs(fMHz-fband(i)) < dmin) then + dmin = abs(fMHz-fband(i)) + iband = i + end if + end do + + imode = 0 + do i=1,NMODES + if (mode == modes(i)) imode = i + end do + + ip = 0 + do i=1,8 + if (ntrperiod == iperiod(i)) ip = i + end do + + id2(1) = iband + id2(2) = imode + id2(3) = nsubmode + id2(4) = ip + end subroutine set_wsjtx_wav_params + + subroutine get_wsjtx_wav_params(id2, band, mode, nsubmode, ntrperiod, ok) + implicit none + integer(int16), intent(in) :: id2(4) + character(len=6), intent(out) :: band + character(len=8), intent(out) :: mode + integer, intent(out) :: nsubmode, ntrperiod + logical, intent(out) :: ok + + integer, parameter :: NBANDS=23, NMODES=13 + character(len=8) :: modes(NMODES) + character(len=6) :: bands(NBANDS) + integer :: iperiod(8) + + data modes/'Echo','FSK441','ISCAT','JT4','JT65','JT6M','JT9', & + 'JT9+JT65','JTMS','JTMSK','WSPR','FT8','FT2'/ + data iperiod/5,10,15,30,60,120,900,0/ + data bands/'2190m','630m','160m','80m','60m','40m','30m','20m', & + '17m','15m','12m','10m','6m','2m','1.25m','70cm','33cm', & + '23cm','13cm','9cm','6cm','3cm','1.25cm'/ + + ok = .true. + if (id2(1) < 1 .or. id2(1) > NBANDS) ok = .false. + if (id2(2) < 1 .or. id2(2) > NMODES) ok = .false. + if (id2(3) < 1 .or. id2(3) > 8) ok = .false. + if (id2(4) < 1 .or. id2(4) > 8) ok = .false. + + if (ok) then + band = bands(id2(1)) + mode = modes(id2(2)) + nsubmode = id2(3) + ntrperiod = iperiod(id2(4)) + end if + end subroutine get_wsjtx_wav_params end module wavhdr diff --git a/map65/libm65/wideband_sync.f90 b/map65/libm65/wideband_sync.f90 index 31a96d2c..a8ae8a68 100644 --- a/map65/libm65/wideband_sync.f90 +++ b/map65/libm65/wideband_sync.f90 @@ -1,273 +1,436 @@ module wideband_sync - type candidate - real :: snr !Relative S/N of sync detection - real :: f !Freq of sync tone, 0 to 96000 Hz - real :: xdt !DT of matching sync pattern, -1.0 to +4.0 s - real :: pol !Polarization angle, degrees - integer :: ipol !Polarization angle, 1 to 4 ==> 0, 45, 90, 135 deg - integer :: iflip !Sync type: JT65 = +/- 1, Q65 = 0 - integer :: indx - end type candidate - type sync_dat - real :: ccfmax - real :: xdt - real :: pol - integer :: ipol - integer :: iflip - logical :: birdie - end type sync_dat - - parameter (NFFT=32768) - parameter (MAX_CANDIDATES=50) - parameter (SNR1_THRESHOLD=4.5) - type(sync_dat) :: sync(NFFT) - integer nkhz_center - - contains - -subroutine get_candidates(ss,savg,xpol,jz,nfa,nfb,nts_jt65,nts_q65,cand,ncand) + use iso_fortran_env, only: real32 + + type candidate + real :: snr !Relative S/N of sync detection + real :: f !Freq of sync tone, 0 to 96000 Hz + real :: xdt !DT of matching sync pattern, -1.0 to +4.6 s + real :: pol !Polarization angle, degrees + integer :: ipol !Polarization angle, 1 to 4 ==> 0, 45, 90, 135 deg + integer :: iflip !Sync type: JT65 = +/- 1, Q65 = 0 + integer :: indx + end type candidate + type sync_dat + real :: ccfmax + real :: xdt + real :: pol + real :: combine_pol + integer :: ipol + integer :: iflip + logical :: birdie + end type sync_dat + + integer, parameter :: MAX_CANDIDATES = 50 + real(real32), parameter :: SNR1_THRESHOLD = 4.5 + type(sync_dat), allocatable :: sync(:) !NFFT + type(sync_dat), allocatable :: q65_generalized_sync(:) + integer nkhz_center + +contains + + subroutine get_candidates(ss, savg, xpol, jz, nfa, nfb, nts_jt65, nts_q65, cand, ncand) + use iso_c_binding + use debug_log, only: dbg, itoa, rtoa + use indexx_mod, only: indexx + use iso_fortran_env, only: real64 + use npar_ptrs_mod, only: nrate_active, nfft_active + + implicit none + + !==== Dummy arguments ===================================================== + real, intent(in) :: ss(4,322,nfft_active) + real, intent(in) :: savg(4,nfft_active) + logical, intent(in) :: xpol + integer, intent(in) :: jz, nfa, nfb + integer, intent(in) :: nts_jt65, nts_q65 + type(candidate), intent(out) :: cand(MAX_CANDIDATES) + integer, intent(out) :: ncand + ! Search symbol spectra ss() over frequency range nfa to nfb (in kHz) for -! JT65 and Q65 sync patterns. The nts_* variables are the submode tone -! spacings: 1 2 4 8 16 for A B C D E. Birdies are detected and -! excised. Candidates are returned in the structure array cand(). - - parameter (MAX_PEAKS=100) - real ss(4,322,NFFT),savg(4,NFFT) - real pavg(-20:20) - integer indx(NFFT) - logical xpol,skip,ldecoded - type(candidate) :: cand(MAX_CANDIDATES) - common/early/nhsym1,nhsym2,ldecoded(32768) - - call wb_sync(ss,savg,xpol,jz,nfa,nfb) !Output to sync() array - - tstep=2048.0/11025.0 !0.185760 s: 0.5*tsym_jt65, 0.3096*tsym_q65 - df3=96000.0/NFFT - ia=nint(1000*nfa/df3) + 1 - ib=nint(1000*nfb/df3) + 1 - if(ia.lt.1) ia=1 - if(ib.gt.NFFT-1) ib=NFFT-1 - iz=ib-ia+1 - - call indexx(sync(ia:ib)%ccfmax,iz,indx) !Sort by relative snr - - k=0 - do i=1,MAX_PEAKS - n=indx(iz+1-i) + ia - 1 - f0=0.001*(n-1)*df3 - snr1=sync(n)%ccfmax - if(snr1.lt.SNR1_THRESHOLD) exit - flip=sync(n)%iflip - if(flip.ne.0.0 .and. nts_jt65.eq.0) cycle - if(flip.eq.0.0 .and. nts_q65.eq.0) cycle - if(sync(n)%birdie) cycle - -! Test for signal outside of TxT range and set bw for this signal type - j1=(sync(n)%xdt + 1.0)/tstep - 1.0 - j2=(sync(n)%xdt + 52.0)/tstep + 1.0 - if(flip.ne.0) j2=(sync(n)%xdt + 47.811)/tstep + 1.0 - ipol=sync(n)%ipol - pavg=0. - do j=1,j1 - pavg=pavg + ss(ipol,j,n-20:n+20) - enddo - do j=j2,jz - pavg=pavg + ss(ipol,j,n-20:n+20) - enddo - jsum=j1 + (jz-j2+1) - pmax=maxval(pavg(-2:2)) !### Why not just pavg(0) ? - base=(sum(pavg)-pmax)/jsum - pmax=pmax/base - if(pmax.gt.5.0) cycle - skip=.false. - do m=1,k !Skip false syncs within signal bw - diffhz=1000.0*(f0-cand(m)%f) - bw=nts_q65*110.0 - if(cand(m)%iflip.ne.0) bw=nts_jt65*178.0 - if(diffhz.gt.-0.03*bw .and. diffhz.lt.1.03*bw) skip=.true. - enddo - if(skip) cycle - k=k+1 - cand(k)%snr=snr1 - cand(k)%f=f0 - cand(k)%xdt=sync(n)%xdt - cand(k)%pol=sync(n)%pol - cand(k)%ipol=sync(n)%ipol - cand(k)%iflip=nint(flip) - cand(k)%indx=n +! sync candidates. A valid generalized Q65 score replaces the legacy mixed-mode +! surface, so that path returns Q65 candidates only; MAP65 discovers JT65 +! independently through ccf65(). Legacy paths may retain JT65 candidates. +! The nts_* variables are the submode tone spacings: 1 2 4 8 16 for A B C D E. +! Birdies are detected and excised. Candidates are returned in cand(). + + integer, parameter :: MAX_PEAKS = 100 + real pavg(-20:20) + real base, bw, diffhz, df3, flip, flip_top, pmax, snr1, snr_top, tstep + real(real64) f0 + integer i, ia, ib, ipol, iz, j + integer j1, j2, k, n, n_top, jsum, m + integer, allocatable :: indx(:) + logical skip + + call wb_sync(ss, savg, xpol, nts_q65.ne.0, jz, nfa, nfb) !Output to sync() array + + tstep = 2048.0/11025.0 !0.185760 s: 0.5*tsym_jt65, 0.3096*tsym_q65 + df3 = real(nrate_active)/real(nfft_active) + ia = nint(1000*nfa/df3) + 1 + ib = nint(1000*nfb/df3) + 1 + if (ia .lt. 21) ia = 21 + if (ib .gt. nfft_active - 20) ib = nfft_active - 20 + iz = ib - ia + 1 + + allocate (indx(iz)) + + ! w3sz this if block should not be necessary but it is + if (iz <= 0) then +! print *, 'GET_CAND: iz <= 0, ia=', ia, ' ib=', ib + flush (6) + return + endif + + call indexx(sync(ia:ib)%ccfmax, iz, indx) !Sort by relative snr + + n_top = indx(iz) + ia - 1 + snr_top = sync(n_top)%ccfmax + flip_top = sync(n_top)%iflip + + k = 0 + do i = 1, MAX_PEAKS + if ((iz + 1 - i) .lt. 1) cycle !w3sz debug + n = indx(iz + 1 - i) + ia - 1 + f0 = 0.001*(n - 1)*df3 + snr1 = sync(n)%ccfmax + if (snr1 .lt. SNR1_THRESHOLD) exit + flip = sync(n)%iflip + if (flip .ne. 0.0 .and. nts_jt65 .eq. 0) cycle + if (flip .eq. 0.0 .and. nts_q65 .eq. 0) cycle + if (sync(n)%birdie) cycle + +! Test for signal outside of TxT range and set bw for this signal type + j1 = max(0,min(jz,int((sync(n)%xdt + 1.0)/tstep - 1.0))) + j2 = max(1,int((sync(n)%xdt + 52.0)/tstep + 1.0)) + if (flip .ne. 0) j2 = int((sync(n)%xdt + 47.811)/tstep + 1.0) + j2 = max(1,j2) + ipol = sync(n)%ipol + pavg = 0. + do j = 1, j1 + pavg = pavg + ss(ipol, j, n - 20:n + 20) + enddo + do j = j2, jz + pavg = pavg + ss(ipol, j, n - 20:n + 20) + enddo + jsum = outside_row_count(j1,j2,jz) + if (jsum .gt. 0) then + pmax = maxval(pavg(-2:2)) !### Why not just pavg(0) ? + base = (sum(pavg) - pmax)/jsum + pmax = pmax/base + if (pmax .gt. 5.0) cycle + endif + skip = .false. + do m = 1, k !Skip false syncs within signal bw + if (cand(m)%iflip .ne. nint(flip)) cycle !only dedupe within the same type + diffhz = 1000.0*(f0 - cand(m)%f) + bw = nts_q65*110.0 + if (cand(m)%iflip .ne. 0) bw = nts_jt65*178.0 + if (diffhz .gt. -0.03*bw .and. diffhz .lt. 1.03*bw) skip = .true. + enddo + if (skip) cycle + k = k + 1 + cand(k)%snr = snr1 + cand(k)%f = f0 + cand(k)%xdt = sync(n)%xdt + cand(k)%pol = sync(n)%pol + cand(k)%ipol = sync(n)%ipol + cand(k)%iflip = nint(flip) + cand(k)%indx = n + ! write(50,3050) i,k,m,f0+32.0,diffhz,bw,snr1,db(snr1) !3050 format(3i5,f8.3,2f8.0,2f8.2) - if(k.ge.MAX_CANDIDATES) exit - enddo - ncand=k - - return -end subroutine get_candidates + if (k .ge. MAX_CANDIDATES) exit + enddo + ncand = k + return + end subroutine get_candidates -subroutine wb_sync(ss,savg,xpol,jz,nfa,nfb) + subroutine wb_sync(ss, savg, xpol, q65_enabled, jz, nfa, nfb) + use iso_c_binding + use iso_fortran_env, only: real64 + use debug_log + use indexx_mod + use map65_polarization_score_mod, only: generalized_polarization_score,polarization_matrix + use txpol_mod + use trimlist_mod + use pctile_mod + use polfit_mod + use npar_ptrs_mod, only: nrate_active, nfft_active + implicit none -! Compute "orange sync curve" using the Q65 sync pattern + !==== Dummy arguments ===================================================== + real, intent(in) :: ss(4,322,nfft_active) + real, intent(in) :: savg(4,nfft_active) + logical, intent(in) :: xpol,q65_enabled + integer, intent(in) :: jz, nfa, nfb - use timer_module, only: timer - parameter (NFFT=32768) - parameter (LAGMAX=30) - real ss(4,322,NFFT) - real savg(4,NFFT) - real savg_med(4) - real ccf4(4),ccf4best(4),a(3) - logical first,xpol - integer isync(22) - integer jsync0(63),jsync1(63) - integer ip(1) + integer, parameter :: LAGMAX = 30 + integer, parameter :: Q65_SYNC_ROWS = 3*22, JT65_SYNC_ROWS = 2*63 + integer, parameter :: Q65_MIN_ROWS = Q65_SYNC_ROWS - 3 + integer, parameter :: JT65_MIN_ROWS = JT65_SYNC_ROWS - 2 + real(c_float) :: savg_med(4) + real ccf4(4), ccf4best(4), a(3) + real base, ccf, ccfmax, combine_poldeg, df3, fac, flip, poldeg, row_scale, tstep + real(real64) :: combine_angle,g00,g01,g11,n00,n01,n11,physical_angle + real(real64) :: projections(4),whitened_score + integer i, ia, ib, ipolbest, j, k, lag, lagbest, nrows + integer npol, ipol + logical first,generalized_available,score_valid + integer isync(22) + integer jsync0(63), jsync1(63) + integer q65_available(22,0:LAGMAX), q65_row_count(0:LAGMAX) + integer jt65_0_available(63,0:LAGMAX), jt65_0_row_count(0:LAGMAX) + integer jt65_1_available(63,0:LAGMAX), jt65_1_row_count(0:LAGMAX) + integer ip(1) + + ! --- JT65 wideband debugging probe --- + ! real :: freq_hz ! Q65 sync symbols - data isync/1,9,12,13,15,22,23,26,27,33,35,38,46,50,55,60,62,66,69,74,76,85/ - data jsync0/ & - 1, 4, 5, 9, 10, 11, 12, 13, 14, 16, 18, 22, 24, 25, 28, 32, & - 33, 34, 37, 38, 39, 40, 42, 43, 45, 46, 47, 48, 52, 53, 55, 57, & - 59, 60, 63, 64, 66, 68, 70, 73, 80, 81, 89, 90, 92, 95, 97, 98, & - 100,102,104,107,108,111,114,119,120,121,122,123,124,125,126/ - data jsync1/ & - 2, 3, 6, 7, 8, 15, 17, 19, 20, 21, 23, 26, 27, 29, 30, 31, & - 35, 36, 41, 44, 49, 50, 51, 54, 56, 58, 61, 62, 65, 67, 69, 71, & - 72, 74, 75, 76, 77, 78, 79, 82, 83, 84, 85, 86, 87, 88, 91, 93, & - 94, 96, 99,101,103,105,106,109,110,112,113,115,116,117,118/ - data first/.true./ - save first,isync,jsync0,jsync1 - - tstep=2048.0/11025.0 !0.185760 s: 0.5*tsym_jt65, 0.3096*tsym_q65 - if(first) then - fac=0.6/tstep - do i=1,22 !Expand the Q65 sync stride - isync(i)=nint((isync(i)-1)*fac) + 1 - enddo - do i=1,63 - jsync0(i)=2*(jsync0(i)-1) + 1 - jsync1(i)=2*(jsync1(i)-1) + 1 - enddo - first=.false. - endif - - df3=96000.0/NFFT - ia=nint(1000*nfa/df3) + 1 !Flat frequency range for WSE converters - ib=nint(1000*nfb/df3) + 1 - if(ia.lt.1) ia=1 - if(ib.gt.NFFT-1) ib=NFFT-1 - npol=1 - if(xpol) npol=4 - - do i=1,npol - call pctile(savg(i,ia:ib),ib-ia+1,50,savg_med(i)) - enddo + data isync/1, 9, 12, 13, 15, 22, 23, 26, 27, 33, 35, 38, 46, 50, 55, 60, 62, 66, 69, 74, 76, 85/ + data jsync0/ & + 1, 4, 5, 9, 10, 11, 12, 13, 14, 16, 18, 22, 24, 25, 28, 32, & + 33, 34, 37, 38, 39, 40, 42, 43, 45, 46, 47, 48, 52, 53, 55, 57, & + 59, 60, 63, 64, 66, 68, 70, 73, 80, 81, 89, 90, 92, 95, 97, 98, & + 100, 102, 104, 107, 108, 111, 114, 119, 120, 121, 122, 123, 124, 125, 126/ + data jsync1/ & + 2, 3, 6, 7, 8, 15, 17, 19, 20, 21, 23, 26, 27, 29, 30, 31, & + 35, 36, 41, 44, 49, 50, 51, 54, 56, 58, 61, 62, 65, 67, 69, 71, & + 72, 74, 75, 76, 77, 78, 79, 82, 83, 84, 85, 86, 87, 88, 91, 93, & + 94, 96, 99, 101, 103, 105, 106, 109, 110, 112, 113, 115, 116, 117, 118/ + data first/.true./ + save first, isync, jsync0, jsync1 + + tstep = 2048.0/11025.0 !0.185760 s: 0.5*tsym_jt65, 0.3096*tsym_q65 + if (first) then + fac = 0.6/tstep + do i = 1, 22 !Expand the Q65 sync stride + isync(i) = nint((isync(i) - 1)*fac) + 1 + enddo + do i = 1, 63 + jsync0(i) = 2*(jsync0(i) - 1) + 1 + jsync1(i) = 2*(jsync1(i) - 1) + 1 + enddo + first = .false. + endif + + df3 = real(nrate_active)/real(nfft_active) + ia = nint(1000*nfa/df3) + 1 !Flat frequency range for WSE converters + ib = nint(1000*nfb/df3) + 1 + if (ia .lt. 1) ia = 1 + if (ib .gt. nfft_active - 1) ib = nfft_active - 1 + npol = 1 + if (xpol) npol = 4 + + q65_row_count = 0 + jt65_0_row_count = 0 + jt65_1_row_count = 0 + do lag = 0, LAGMAX + do j = 1, 22 + k = isync(j) + lag + q65_available(j,lag) = min(3,max(0,jz-k+1)) + q65_row_count(lag) = q65_row_count(lag) + q65_available(j,lag) + enddo + do j = 1, 63 + k = jsync0(j) + lag + jt65_0_available(j,lag) = min(2,max(0,jz-k+1)) + jt65_0_row_count(lag) = jt65_0_row_count(lag) + jt65_0_available(j,lag) + + k = jsync1(j) + lag + jt65_1_available(j,lag) = min(2,max(0,jz-k+1)) + jt65_1_row_count(lag) = jt65_1_row_count(lag) + jt65_1_available(j,lag) + enddo + enddo + + do i = 1, npol + call pctile(savg(i, ia:ib), ib - ia + 1, 50, savg_med(i)) + enddo + n00=real(savg_med(1),real64)/real(jz,real64) + n11=n00 + n01=0.0_real64 + generalized_available=.false. + if (xpol .and. q65_enabled) then + n11=real(savg_med(3),real64)/real(jz,real64) + call pctile(0.5*(savg(2,ia:ib)-savg(4,ia:ib)),ib-ia+1,50,base) + n01=real(base,real64)/real(jz,real64) + call generalized_polarization_score(0.0_real64,0.0_real64,0.0_real64, & + n00,n11,n01,whitened_score,physical_angle,combine_angle,generalized_available) + endif ! do i=ia,ib ! write(14,3014) 0.001*(i-1)*df3,savg(1:npol,i) !3014 format(5f10.3) ! enddo - lagbest=0 - ipolbest=1 - flip=0. - - do i=ia,ib - ccfmax=0. - do lag=0,LAGMAX - - ccf=0. - ccf4=0. - do j=1,22 !Test for Q65 sync - k=isync(j) + lag - ccf4(1:npol)=ccf4(1:npol) + ss(1:npol,k,i+1) + & - ss(1:npol,k+1,i+1) + ss(1:npol,k+2,i+1) - enddo - ccf4(1:npol)=ccf4(1:npol) - savg(1:npol,i+1)*3*22/float(jz) - ccf=maxval(ccf4) - ip=maxloc(ccf4) - ipol=ip(1) - if(ccf.gt.ccfmax) then - ipolbest=ipol - lagbest=lag - ccfmax=ccf - ccf4best=ccf4 - flip=0. - endif + lagbest = 0 + ipolbest = 1 + flip = 0. - ccf=0. - ccf4=0. - do j=1,63 !Test for JT65 sync, std msg - k=jsync0(j) + lag - ccf4(1:npol)=ccf4(1:npol) + ss(1:npol,k,i+1) + ss(1:npol,k+1,i+1) - enddo - ccf4(1:npol)=ccf4(1:npol) - savg(1:npol,i+1)*2*63/float(jz) - ccf=maxval(ccf4) - ip=maxloc(ccf4) - ipol=ip(1) - if(ccf.gt.ccfmax) then - ipolbest=ipol - lagbest=lag - ccfmax=ccf - ccf4best=ccf4 - flip=1.0 - endif + do i = ia, ib + ccfmax = 0. + poldeg = 0. + combine_poldeg = 0. + q65_generalized_sync(i)%ccfmax=0. + q65_generalized_sync(i)%xdt=0. + q65_generalized_sync(i)%pol=0. + q65_generalized_sync(i)%combine_pol=0. + q65_generalized_sync(i)%ipol=1 + q65_generalized_sync(i)%iflip=0 + q65_generalized_sync(i)%birdie=.false. + do lag = 0, LAGMAX + + nrows = q65_row_count(lag) + if (nrows .ge. Q65_MIN_ROWS) then + ccf = 0. + ccf4 = 0. + do j = 1, 22 !Test for Q65 sync + k = isync(j) + lag + if (q65_available(j,lag) .ge. 1) & + ccf4(1:npol) = ccf4(1:npol) + ss(1:npol,k,i) + if (q65_available(j,lag) .ge. 2) & + ccf4(1:npol) = ccf4(1:npol) + ss(1:npol,k+1,i) + if (q65_available(j,lag) .ge. 3) & + ccf4(1:npol) = ccf4(1:npol) + ss(1:npol,k+2,i) + enddo + ccf4(1:npol) = ccf4(1:npol) - savg(1:npol,i)*real(nrows)/real(jz) + row_scale = sqrt(real(Q65_SYNC_ROWS)/real(nrows)) + ccf4(1:npol) = row_scale*ccf4(1:npol) + ccf = maxval(ccf4) + ip = maxloc(ccf4) + ipol = ip(1) + if (generalized_available) then + projections=real(ccf4,real64) + call polarization_matrix(projections,g00,g11,g01) + call generalized_polarization_score(g00,g11,g01,n00,n11,n01, & + whitened_score,physical_angle,combine_angle,score_valid) + if (score_valid .and. whitened_score > & + real(q65_generalized_sync(i)%ccfmax,real64)) then + q65_generalized_sync(i)%ccfmax=real(whitened_score) + q65_generalized_sync(i)%xdt=lag*tstep-1.0 + q65_generalized_sync(i)%pol=real(physical_angle) + q65_generalized_sync(i)%combine_pol=real(combine_angle) + q65_generalized_sync(i)%ipol=ipol + endif + endif + if (ccf .gt. ccfmax) then + ipolbest = ipol + lagbest = lag + ccfmax = ccf + ccf4best = ccf4 + flip = 0. + endif + endif + + nrows = jt65_0_row_count(lag) + if (nrows .ge. JT65_MIN_ROWS) then + ccf = 0. + ccf4 = 0. + do j = 1, 63 !Test for JT65 sync, std msg + k = jsync0(j) + lag + if (jt65_0_available(j,lag) .ge. 1) & + ccf4(1:npol) = ccf4(1:npol) + ss(1:npol,k,i) + if (jt65_0_available(j,lag) .ge. 2) & + ccf4(1:npol) = ccf4(1:npol) + ss(1:npol,k+1,i) + enddo + ccf4(1:npol) = ccf4(1:npol) - savg(1:npol,i)*real(nrows)/real(jz) + row_scale = sqrt(real(JT65_SYNC_ROWS)/real(nrows)) + ccf4(1:npol) = row_scale*ccf4(1:npol) + ccf = maxval(ccf4) + ip = maxloc(ccf4) + ipol = ip(1) + if (ccf .gt. ccfmax) then + ipolbest = ipol + lagbest = lag + ccfmax = ccf + ccf4best = ccf4 + flip = 1.0 + endif + endif + + nrows = jt65_1_row_count(lag) + if (nrows .ge. JT65_MIN_ROWS) then + ccf = 0. + ccf4 = 0. + do j = 1, 63 !Test for JT65 sync, OOO msg + k = jsync1(j) + lag + if (jt65_1_available(j,lag) .ge. 1) & + ccf4(1:npol) = ccf4(1:npol) + ss(1:npol,k,i) + if (jt65_1_available(j,lag) .ge. 2) & + ccf4(1:npol) = ccf4(1:npol) + ss(1:npol,k+1,i) + enddo + ccf4(1:npol) = ccf4(1:npol) - savg(1:npol,i)*real(nrows)/real(jz) + row_scale = sqrt(real(JT65_SYNC_ROWS)/real(nrows)) + ccf4(1:npol) = row_scale*ccf4(1:npol) + ccf = maxval(ccf4) + ip = maxloc(ccf4) + ipol = ip(1) + if (ccf .gt. ccfmax) then + ipolbest = ipol + lagbest = lag + ccfmax = ccf + ccf4best = ccf4 + flip = -1.0 + endif + endif - ccf=0. - ccf4=0. - do j=1,63 !Test for JT65 sync, OOO msg - k=jsync1(j) + lag - ccf4(1:npol)=ccf4(1:npol) + ss(1:npol,k,i+1) + ss(1:npol,k+1,i+1) - enddo - ccf4(1:npol)=ccf4(1:npol) - savg(1:npol,i+1)*2*63/float(jz) - ccf=maxval(ccf4) - ip=maxloc(ccf4) - ipol=ip(1) - if(ccf.gt.ccfmax) then - ipolbest=ipol - lagbest=lag - ccfmax=ccf - ccf4best=ccf4 - flip=-1.0 + enddo ! lag + + if (xpol .and. ccfmax .ge. SNR1_THRESHOLD) then + call polfit(ccf4best, 4, a) + poldeg = a(3) + endif + combine_poldeg=poldeg + sync(i)%ccfmax = ccfmax + sync(i)%xdt = lagbest*tstep - 1.0 + sync(i)%pol = poldeg + sync(i)%combine_pol = combine_poldeg + sync(i)%ipol = ipolbest + sync(i)%iflip = int(flip) + sync(i)%birdie = .false. + if (ccfmax/(savg(ipolbest, i)/savg_med(ipolbest)) .lt. 3.0) sync(i)%birdie = .true. + if (generalized_available) then + ipol=q65_generalized_sync(i)%ipol + if (q65_generalized_sync(i)%ccfmax/(savg(ipol,i)/savg_med(ipol)) .lt. 3.0) & + q65_generalized_sync(i)%birdie=.true. endif - enddo ! lag - - poldeg=0. - if(xpol .and. ccfmax.ge.SNR1_THRESHOLD) then - call polfit(ccf4best,4,a) - poldeg=a(3) - endif - sync(i)%ccfmax=ccfmax - sync(i)%xdt=lagbest*tstep-1.0 - sync(i)%pol=poldeg - sync(i)%ipol=ipolbest - sync(i)%iflip=flip - sync(i)%birdie=.false. - if(ccfmax/(savg(ipolbest,i)/savg_med(ipolbest)).lt.3.0) sync(i)%birdie=.true. -! if(sync(i)%iflip.eq.0 .and. sync(i)%ccfmax .gt. 20.0) then -! write(50,3050) i,lagbest,sync(i)%ccfmax,sync(i)%xdt,sync(i)%ipol, & -! sync(i)%birdie,ccf4best -!3050 format(2i5,f10.3,f8.2,i5,1x,L3,4f7.1) -! endif - - enddo ! i (frequency bin) - - call pctile(sync(ia:ib)%ccfmax,ib-ia+1,50,base) - sync(ia:ib)%ccfmax=sync(ia:ib)%ccfmax/base - - bw=65*4*1.66666667 !Q65-60C bandwidth - nbw=bw/df3 + 1 !Number of bins to blank - syncmin=2.0 - nguard=10 - do i=ia,ib - if(sync(i)%ccfmax.lt.syncmin) cycle - spk=maxval(sync(i:i+nbw)%ccfmax) - ip =maxloc(sync(i:i+nbw)%ccfmax) - i0=ip(1)+i-1 - ja=min(i,i0-nguard) - jb=i0+nbw+nguard - sync(ja:jb)%ccfmax=0. - sync(i0)%ccfmax=spk - enddo + ! --- JT65 wideband probe (new) --- +! freq_hz = 0.001 * (i - 1) * df3 ! convert FFT bin index to kHz + +! if (abs(freq_hz - 11.305d0) .lt. 0.02d0) then +! write(*,*) 'WBSYNC BIN: freq=', freq_hz, & +! ' ccfmax=', sync(i)%ccfmax, & +! ' birdie=', sync(i)%birdie, & +! ' iflip=', sync(i)%iflip +! endif + + enddo ! i (frequency bin) + + call pctile(sync(ia:ib)%ccfmax, ib - ia + 1, 50, base) + sync(ia:ib)%ccfmax = sync(ia:ib)%ccfmax/base + if (generalized_available) then + call pctile(q65_generalized_sync(ia:ib)%ccfmax,ib-ia+1,50,base) + if (base > tiny(base)) then + q65_generalized_sync(ia:ib)%ccfmax=q65_generalized_sync(ia:ib)%ccfmax/base + sync(ia:ib)=q65_generalized_sync(ia:ib) + endif + endif + + ! A local-peak "collapse to single survivor" pass used to run here, + ! blanking a wide (~450 Hz) same-type swath around whatever bin its + ! own forward-only search happened to land on. Because that search + ! and blanking radius were not centered on the true global peak, it + ! could -- and, for closely-spaced real Q65 signals, did -- wipe out + ! a much stronger genuine peak in favor of a weaker one found earlier + ! in the frequency sweep, corrupting the candidate frequency reported + ! for that signal (confirmed via w3sz debug logging: a real Q65 + ! signal's candidate frequency was off by ~150-200 Hz from its true + ! peak whenever this pass ran, and exactly correct with it removed). + ! get_candidates() below already does its own correct, strength- + ! ordered, same-type-only deduplication (skip a candidate within its + ! own signal bandwidth of an already-accepted stronger one), which + ! does not have this failure mode, so this pass is not needed. ! do i=ia,ib ! write(15,3015) 0.001*(i-1)*df3+32.0,sync(i)%ccfmax,sync(i)%xdt, & @@ -275,7 +438,22 @@ subroutine wb_sync(ss,savg,xpol,jz,nfa,nfb) !3015 format(3f10.3,2i6,L5) ! enddo - return -end subroutine wb_sync + return + end subroutine wb_sync + + pure integer function outside_row_count(j1,j2,jz) + implicit none + integer, intent(in) :: j1,j2,jz + + outside_row_count = max(0,min(j1,jz)) + max(0,jz-max(1,j2)+1) + end function outside_row_count + + subroutine init_wideband_sync() + use npar_ptrs_mod, only: nfft_active + implicit none + if (.not. allocated(sync)) allocate (sync(nfft_active)) + if (.not. allocated(q65_generalized_sync)) & + allocate (q65_generalized_sync(nfft_active)) + end subroutine init_wideband_sync end module wideband_sync diff --git a/map65/libm65/win_event_shim.c b/map65/libm65/win_event_shim.c new file mode 100644 index 00000000..612d717a --- /dev/null +++ b/map65/libm65/win_event_shim.c @@ -0,0 +1,30 @@ +// win_event_shim.c +#include <windows.h> +#include <stdlib.h> + +void* win_create_event(void) +{ + HANDLE h = CreateEventW(NULL, FALSE, FALSE, NULL); + return (void*)h; +} + +int win_set_event(void* h) +{ + return SetEvent((HANDLE)h); +} + +int win_reset_event(void* h) +{ + return ResetEvent((HANDLE)h); +} + +int win_wait_for_single_object(void* h) +{ + DWORD rc = WaitForSingleObject((HANDLE)h, INFINITE); + return (rc == WAIT_OBJECT_0) ? 0 : 1; +} + +void win_close_event(void* h) +{ + CloseHandle((HANDLE)h); +} diff --git a/map65/libm65/zplot.f90 b/map65/libm65/zplot.f90 index 55aa3c6f..4155a537 100644 --- a/map65/libm65/zplot.f90 +++ b/map65/libm65/zplot.f90 @@ -1,34 +1,43 @@ -subroutine zplot(amp,nz,jj,ave,rms) - - real amp(nz) - character*1 line(100),mark(0:6) - data mark/' ',' ','.','-','+','X','$'/ - - sum=0. - smax=0. - do i=1,nz - sum=sum+amp(i) - if(amp(i).gt.smax) then - smax=amp(i) - ipk=i - endif - enddo - ave=(sum-smax)/(nz-1) - sq=0. - do i=1,nz - if(i.ne.ipk) sq=sq+(amp(i)-ave)**2 - enddo - rms=sqrt(sq/(nz-2)) - - do i=1,nz - n=(amp(i)-ave)/rms -! n=(amp(i)-ave)/0.33 - if(n.lt.0) n=0 - if(n.gt.6) n=6 - line(i)=mark(n) - enddo - write(89,1010) jj,0.01*ave,0.01*rms,(line(i),i=1,nz) -1010 format(i3,2f6.1,1x,100a1) +module zplot_mod + implicit none +contains + subroutine zplot(amp,nz,jj,ave,rms) + implicit none + integer, intent(in) :: nz, jj + real, intent(in) :: amp(nz) + real, intent(out) :: ave, rms + + character*1 :: line(100) + character*1 :: mark(0:6) + data mark/' ',' ','.','-','+','X','$'/ + integer :: i, ipk, n + real :: sum, smax, sq - return -end subroutine zplot + sum=0. + smax=0. + do i=1,nz + sum=sum+amp(i) + if(amp(i).gt.smax) then + smax=amp(i) + ipk=i + endif + enddo + ave=(sum-smax)/(nz-1) + sq=0. + do i=1,nz + if(i.ne.ipk) sq=sq+(amp(i)-ave)**2 + enddo + rms=sqrt(sq/(nz-2)) + + do i=1,nz + n=(amp(i)-ave)/rms + ! n=(amp(i)-ave)/0.33 + if(n.lt.0) n=0 + if(n.gt.6) n=6 + line(i)=mark(n) + enddo + write(89,1010) jj,0.01*ave,0.01*rms,(line(i),i=1,nz) + 1010 format(i3,2f6.1,1x,100a1) + + end subroutine zplot +end module zplot_mod diff --git a/map65/liveCQSender.cpp b/map65/liveCQSender.cpp index 6e42cf3c..c2e27780 100644 --- a/map65/liveCQSender.cpp +++ b/map65/liveCQSender.cpp @@ -27,7 +27,6 @@ #include <QRandomGenerator> #endif -#include "../Logger.hpp" #include "devsetup.h" # define DEBUGPSK 1; @@ -38,19 +37,18 @@ namespace quint16 SERVICE_PORT {443}; //this is https test port } -liveCQSender::liveCQSender(QString const& myCall, QString const& myGrid, QString const& theUrl) - : logger_ {boost::log::keywords::channel = "PSKRPRT"} - , m_myCall {myCall} - , m_myGrid {myGrid} - , m_theUrl {theUrl} - { - qRegisterMetaType<QAbstractSocket::SocketError>(); - qDebug() << "Current thread for impl (liveCQSender):" << QThread::currentThread(); - } - +liveCQSender::liveCQSender(QString const& myCall, + QString const& myGrid, + QString const& theUrl) + : + m_myCall{myCall}, + m_myGrid{myGrid}, + m_theUrl{theUrl} +{ +} void liveCQSender::init() { - qDebug() << "liveCQSender::init running on thread: " << QThread::currentThread(); + // qDebug() << "liveCQSender::init running on thread: " << QThread::currentThread(); socket.reset(new QSslSocket(this)); // Connect signals before connecting diff --git a/map65/liveCQSender.hpp b/map65/liveCQSender.hpp index b4f6db66..afb96665 100644 --- a/map65/liveCQSender.hpp +++ b/map65/liveCQSender.hpp @@ -1,7 +1,5 @@ #ifndef LIVECQSENDER_HPP_ #define LIVECQSENDER_HPP_ -#include <boost/log/sources/severity_channel_logger.hpp> -#include <boost/log/trivial.hpp> #include <QObject> #include <QTimer> #include <QSslSocket> @@ -42,8 +40,6 @@ private slots: void sendData(const QByteArray &payload); private: - using logger_type = boost::log::sources::severity_channel_logger_mt<boost::log::trivial::severity_level>; - logger_type mutable logger_; QString m_myCall; QString m_myGrid; QString m_theUrl; diff --git a/map65/main.cpp b/map65/main.cpp index 3df7e762..5c8de1d7 100644 --- a/map65/main.cpp +++ b/map65/main.cpp @@ -5,30 +5,103 @@ #include <QtGui> #endif #include <QApplication> +#ifdef _WIN32 +#include <windows.h> +#endif #include "revision_utils.hpp" #include "mainwindow.h" +#include "fortran_mutex.hpp" +#include "globals.h" +#include "runtime_paths.h" + +#include <cstdio> + +extern "C" void set_runtime_params_(int rate_hz, int nfft, int nfft_big); extern "C" { // Fortran procedures we need void four2a_ (_Complex float *, int * nfft, int * ndim, int * isign, int * iform, int len); } +extern int g_sampleRate; +extern int active_nfft; +int g_activeNfft = 32768; // default + int main(int argc, char *argv[]) { +#ifdef _WIN32 +# ifdef MAP_GUI_SUBSYSTEM + FreeConsole(); +# endif +#endif + +#ifdef _WIN32 +# ifdef MAP_GUI_SUBSYSTEM +# pragma message("MAP_GUI_SUBSYSTEM is defined in C++") +# else +# pragma message("MAP_GUI_SUBSYSTEM is NOT defined in C++") +# endif +#endif QApplication a {argc, argv}; - // Override programs executable basename as application name. a.setApplicationName ("MAP65"); - a.setApplicationVersion ("3.2"); - // switch off as we share an Info.plist file with WSJT-X + a.setApplicationVersion ("3.8.2"); a.setAttribute (Qt::AA_DontUseNativeMenuBar); + + QString appDir = QApplication::applicationDirPath(); + QString dataDir = writableMap65DataDir(); + QSettings settings(map65SettingsFile(appDir, dataDir), QSettings::IniFormat); + settings.beginGroup("Common"); + int srFlag = readFSam96000(settings, 1); + settings.endGroup(); + if(srFlag <= 1) g_sampleRate = 96000; + else if(srFlag == 2) g_sampleRate = 192000; + if (g_sampleRate != 96000 && g_sampleRate != 192000) + g_sampleRate = 96000; + +// ------------------------------------------------------------ +// NEW: compute active FFT sizes for MAP65 +// ------------------------------------------------------------ +int active_rate = g_sampleRate; + +// Keep ~3 Hz bin resolution like WSJT-X/QMAP +auto round_pow2 = [](int x) { + int p = 1; + while (p < x) p <<= 1; + return p; +}; + +// symspec FFT size +active_nfft = round_pow2( + static_cast<int>( + static_cast<long long>(BASELINE_NFFT) * active_rate / BASELINE_RATE + ) +); + +g_activeNfft = active_nfft; + +// big FFT size (56 symbols * sample rate) +int active_nfft_big = 56 * active_rate; + +// ------------------------------------------------------------ +// Push runtime parameters into Fortran BEFORE MainWindow starts +// ------------------------------------------------------------ +set_runtime_params_(active_rate, active_nfft, active_nfft_big); + +// ------------------------------------------------------------ +// allocate buffers now that sample rate is known +// ------------------------------------------------------------ +id.resize(4 * 60 * g_sampleRate); + MainWindow w; + w.show (); QObject::connect (&a, &QApplication::lastWindowClosed, &a, &QApplication::quit); auto result = a.exec (); // clean up lazily initialized FFTW3 resources { + std::lock_guard<std::mutex> lock(g_fortran_decode_mutex); int nfft {-1}; int ndim {1}; int isign {1}; diff --git a/map65/mainwindow.cpp b/map65/mainwindow.cpp index cc444928..3cb1e760 100644 --- a/map65/mainwindow.cpp +++ b/map65/mainwindow.cpp @@ -2,7 +2,10 @@ #include "mainwindow.h" #include <fftw3.h> #include <QDir> +#include <QRegularExpression> #include <QSettings> +#include <QStandardPaths> +#include <QStringList> #include <QTimer> #include <QToolTip> #include "revision_utils.hpp" @@ -19,13 +22,58 @@ #include "bandmap.h" #include "txtune.h" #include "sleep.h" +#include "commons.h" +#include "soundin.h" #include <portaudio.h> +#include <iostream> #include <QApplication> #include <QDebug> #include <QDateTime> +#include <QTime> +#include <QFile> +#include <QTextStream> +#include <QString> +#include <QByteArray> + +//#include <io.h> +#include <stdio.h> + +#include <cstdio> +#include <cstdlib> +#include <unistd.h> // for pipe(), dup2() +#include <math.h> +#include <thread> +#include <fcntl.h> + +#include "stdout_channel.h" +#include "fortran_mutex.hpp" +#include "pskreporter_settings.h" +#include "runtime_paths.h" + +#if !defined(Q_OS_WIN) +extern "C" { + void ptt_set_override(const char *path); +} +#endif + +extern "C" { + int ptt_(int* nport, int* itx, int* iptt); +} + +#ifdef __unix__ +extern "C" void ptt_close(void); +#endif + +#ifdef MessageBox +#undef MessageBox +#endif -#define NFFT 32768 +QByteArray g_TxTuneGeometry; + +int g_sampleRate = 96000; +int active_nfft; +std::vector<qint16> id; short int iwave[2*60*12000]; //Wave file for Tx audio int nwave; //Length of Tx waveform @@ -36,35 +84,133 @@ double outputLatency; //Latency in seconds int txPower; int iqAmp; int iqPhase; -qint16 id[4*60*96000]; +int pipefd[2]; // pipefd[0] = read end, pipefd[1] = write end TxTune* g_pTxTune = NULL; -QSharedMemory mem_m65("mem_m65"); -extern const int RxDataFrequency = 96000; -extern const int TxDataFrequency = 11025; +std::atomic<bool> stop_m65{false}; QString guiDate; //liveCQ QStringList allDecodes; //liveCQ QStringList allDecodes2; //liveCQ QString m_otherUrl; bool m_w3szUrl; -bool m_spot_to_psk_reporter; + +struct MainWindow::DecoderContext +{ + StdoutChannel* stdoutChan; + DecoderContext(); + ~DecoderContext(); +}; + +MainWindow::DecoderContext::DecoderContext() +{ + stdoutChan = new StdoutChannel( + L"MAP65_STDOUT_MAPPING", + L"MAP65_STDOUT_EVENT", + 1024 * 1024 + ); +} + +MainWindow::DecoderContext::~DecoderContext() +{ + delete stdoutChan; +} + +// TEMP diagnostic 2026-09-10 for the "decode reaches map65_rx.log but not the +// Messages window, only on the first decode cycle after MAP65 starts" report. +// Writes to its own separate log file rather than the shared w3sz_debug.log +// Fortran's dbg() uses -- the two processes/threads have no lock between +// them, and sharing a file produces torn, interleaved lines. Timestamps use +// the same sec_midn()-style local h*3600+m*60+s+ms/1000 format as the +// Fortran log, so the two can still be correlated by eye. Strip both files' +// worth of logging before merge. +// +// Mirrors run_m65.f90's dbg_enabled flag -- flip to true to re-enable this +// log without touching any of the cppDbg(...) call sites scattered through +// this file. +static bool const cppDbgEnabled = false; + +static void cppDbg(const QString &msg) +{ + if (!cppDbgEnabled) return; + double const t = [] { + QTime const now = QTime::currentTime(); + return now.hour() * 3600.0 + now.minute() * 60.0 + now.second() + now.msec() / 1000.0; + }(); + QFile f("w3sz_debug_cpp.log"); + if (f.open(QIODevice::Append | QIODevice::Text)) { + QTextStream out(&f); + out << "mainwindow: " << msg << " at t=" << QString::number(t, 'f', 3) << "\n"; + } +} //-------------------------------------------------- MainWindow constructor MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), m_appDir {QApplication::applicationDirPath ()}, - m_settings_filename {m_appDir + "/map65.ini"}, + m_installedDataDir {installed_data_directory ().absolutePath ()}, + m_dataDir {writableMap65DataDir ()}, + m_eclipseFile {map65RuntimeSourceFile (m_appDir, m_installedDataDir, m_dataDir, + "eclipse.txt")}, + m_settings_filename {map65SettingsFile (m_appDir, m_dataDir)}, m_astro_window {new Astro {m_settings_filename}}, m_band_map_window {new BandMap {m_settings_filename}}, m_messages_window(nullptr), m_wide_graph_window {new WideGraph {m_settings_filename}}, m_gui_timer {new QTimer {this}} { + qDebug() << "IN MainWindow Constructor active_nfft IS: " << active_nfft; + if (!QDir::setCurrent(m_dataDir)) { + qWarning() << "Unable to set MAP65 working directory:" << m_dataDir; + } + QByteArray dataDirBytes = m_dataDir.toLocal8Bit(); + set_wsjtx_dir_(dataDirBytes.constData(), dataDirBytes.size()); + ensureMap65RuntimeFile(m_appDir, m_installedDataDir, m_dataDir, "CALL3.TXT"); + constexpr int baseSeconds = 56; + const int sampleRate = g_sampleRate; + constexpr int channels = 4; // dd(1..4, t) + + decoderCtx = new DecoderContext(); + startSharedMemoryStdoutReader(decoderCtx); + + // Worst-case: xpol = true ? 2 * baseSeconds * sampleRate I/Q pairs + const int pairsWorst = 2 * baseSeconds * sampleRate; + const int ddSize = pairsWorst * channels; + this->ddSize = ddSize; + dd = new float[ddSize]; + + // Tell Fortran about the maximum shape (channels × pairsWorst) + set_dd_ptr(dd, channels, pairsWorst); + + qDebug() << "g_sampleRate:" << g_sampleRate + << "sampleRate:" << sampleRate + << "id.size():" << id.size() + << "bytes:" << id.size() * sizeof(id[0]); + + std::cout << "dd pointer set to: " << dd + << " size: " << ddSize + << " (channels=" << channels + << ", pairsWorst=" << pairsWorst << ")\n"; + + ss = new float[4 * 322 * active_nfft]; + savg = new float[4 * active_nfft]; + set_ss_ptr(ss, 4, 322, active_nfft); + std::cout << "ss pointer set to: " << ss << std::endl; + set_savg_ptr(savg, 4, active_nfft); + std::cout << "savg pointer set to: " << savg << std::endl; + dd_old = new float[ddSize]; + set_dd_old_ptr(dd_old, channels, pairsWorst); + ss_old = new float[4 * 322 * active_nfft]; + savg_old = new float[4 * active_nfft]; + set_ss_old_ptr(ss_old, 4, 322, active_nfft); + set_savg_old_ptr(savg_old, 4, active_nfft); + + qDebug() << "MAINWINDOW created dd ss savg "; + ui->setupUi(this); - on_EraseButton_clicked(); +// on_EraseButton_clicked(); //placing this here is a bug that will sometimes produce a crash on startup. ui->labUTC->setStyleSheet( \ "QLabel { background-color : black; color : yellow; }"); ui->labTol1->setStyleSheet( \ @@ -100,6 +246,7 @@ MainWindow::MainWindow(QWidget *parent) : ui->actionNo_Deep_Search->setActionGroup(DepthGroup); ui->actionNormal_Deep_Search->setActionGroup(DepthGroup); ui->actionAggressive_Deep_Search->setActionGroup(DepthGroup); + ui->actionFull_Deep_Search->setActionGroup(DepthGroup); QButtonGroup* txMsgButtonGroup = new QButtonGroup; txMsgButtonGroup->addButton(ui->txrb1,1); @@ -108,11 +255,100 @@ MainWindow::MainWindow(QWidget *parent) : txMsgButtonGroup->addButton(ui->txrb4,4); txMsgButtonGroup->addButton(ui->txrb5,5); txMsgButtonGroup->addButton(ui->txrb6,6); - connect(txMsgButtonGroup,SIGNAL(buttonClicked(int)),SLOT(set_ntx(int))); + connect(txMsgButtonGroup, + QOverload<QAbstractButton *>::of(&QButtonGroup::buttonClicked), + this, + [this, txMsgButtonGroup](QAbstractButton *btn) { + int id = txMsgButtonGroup->id(btn); + set_ntx(id); + }); + connect(ui->decodedTextBrowser,SIGNAL(selectCallsign(bool)),this, SLOT(selectCall2(bool))); - setWindowTitle (program_title ()); + // Callsign-overlay toggle (N6NU 2026-05-12, port of QMAP feature). + // View menu action ↔ WideGraph state, two-way mirror via signal. + if (m_wide_graph_window) { + ui->actionShow_callsigns_on_Waterfall->setChecked( + m_wide_graph_window->decodeLabelsEnabled()); + connect(ui->actionShow_callsigns_on_Waterfall, &QAction::toggled, + m_wide_graph_window.data(), &WideGraph::setDecodeLabelsEnabled); + connect(m_wide_graph_window.data(), &WideGraph::decodeLabelsEnabledChanged, + ui->actionShow_callsigns_on_Waterfall, &QAction::setChecked); + + // Decoded-callsign overlay transparency — exclusive action group + // (View → Callsign transparency). None=255 / Low=220 / Medium=200 / + // High=175. Persisted under [WideGraph]/decode_label_alpha. + QActionGroup* transparencyGroup = new QActionGroup(this); + ui->actionTransparency_None ->setActionGroup(transparencyGroup); + ui->actionTransparency_Low ->setActionGroup(transparencyGroup); + ui->actionTransparency_Medium->setActionGroup(transparencyGroup); + ui->actionTransparency_High ->setActionGroup(transparencyGroup); + { + const int a = m_wide_graph_window->decodeLabelAlpha(); + if (a == 175) ui->actionTransparency_High ->setChecked(true); + else if (a == 200) ui->actionTransparency_Medium->setChecked(true); + else if (a == 220) ui->actionTransparency_Low ->setChecked(true); + else ui->actionTransparency_None ->setChecked(true); + } + auto* wg = m_wide_graph_window.data(); + connect(ui->actionTransparency_None, &QAction::triggered, + wg, [wg]{ wg->setDecodeLabelAlpha(255); }); + connect(ui->actionTransparency_Low, &QAction::triggered, + wg, [wg]{ wg->setDecodeLabelAlpha(220); }); + connect(ui->actionTransparency_Medium, &QAction::triggered, + wg, [wg]{ wg->setDecodeLabelAlpha(200); }); + connect(ui->actionTransparency_High, &QAction::triggered, + wg, [wg]{ wg->setDecodeLabelAlpha(175); }); + + // Decoded-callsign overlay font-size — exclusive action group + // (View → Callsign font size). Small=7 / Normal=8 (default) / + // Medium=10 / Large=12. Persisted via WideGraph::setDecodeLabelFontSize. + QActionGroup* fontGroup = new QActionGroup(this); + ui->actionCallsign_font_small ->setActionGroup(fontGroup); + ui->actionCallsign_font_normal->setActionGroup(fontGroup); + ui->actionCallsign_font_medium->setActionGroup(fontGroup); + ui->actionCallsign_font_large ->setActionGroup(fontGroup); + switch (wg->decodeLabelFontSize()) { + case DecodeLabelFontSize::Small: + ui->actionCallsign_font_small ->setChecked(true); break; + case DecodeLabelFontSize::Medium: + ui->actionCallsign_font_medium->setChecked(true); break; + case DecodeLabelFontSize::Large: + ui->actionCallsign_font_large ->setChecked(true); break; + case DecodeLabelFontSize::Normal: + default: + ui->actionCallsign_font_normal->setChecked(true); break; + } + connect(ui->actionCallsign_font_small, &QAction::triggered, + wg, [wg]{ wg->setDecodeLabelFontSize(DecodeLabelFontSize::Small); }); + connect(ui->actionCallsign_font_normal, &QAction::triggered, + wg, [wg]{ wg->setDecodeLabelFontSize(DecodeLabelFontSize::Normal); }); + connect(ui->actionCallsign_font_medium, &QAction::triggered, + wg, [wg]{ wg->setDecodeLabelFontSize(DecodeLabelFontSize::Medium); }); + connect(ui->actionCallsign_font_large, &QAction::triggered, + wg, [wg]{ wg->setDecodeLabelFontSize(DecodeLabelFontSize::Large); }); + + // Callsign-overlay anchor position. Top (legacy) or Bottom (sit + // above the divider so fresh signals at the top of the waterfall + // remain visible). Persisted under [WideGraph]/decode_label_position + // via WideGraph::setDecodeLabelPosition. + QActionGroup* positionGroup = new QActionGroup(this); + ui->actionCallsign_position_top ->setActionGroup(positionGroup); + ui->actionCallsign_position_bottom->setActionGroup(positionGroup); + if (wg->decodeLabelPosition() == DecodeLabelPosition::Bottom) { + ui->actionCallsign_position_bottom->setChecked(true); + } else { + ui->actionCallsign_position_top ->setChecked(true); + } + connect(ui->actionCallsign_position_top, &QAction::triggered, + wg, [wg]{ wg->setDecodeLabelPosition(DecodeLabelPosition::Top); }); + connect(ui->actionCallsign_position_bottom, &QAction::triggered, + wg, [wg]{ wg->setDecodeLabelPosition(DecodeLabelPosition::Bottom); }); + } + + setWindowTitle (branded_program_title ()); + qDebug() << "MAINWINDOW about to start soundInThread SIGNAL/SLOT connections"; connect(&soundInThread, SIGNAL(readyForFFT(int)), this, SLOT(dataSink(int))); @@ -121,19 +357,9 @@ MainWindow::MainWindow(QWidget *parent) : connect(&soundInThread, SIGNAL(status(QString)), this, SLOT(showStatusMessage(QString))); createStatusBar(); + qDebug() << "MAINWINDOW created soundInThread SIGNAL/SLOT connections"; - connect(&proc_m65, SIGNAL(readyReadStandardOutput()), this, SLOT(readFromStdout())); - connect(&proc_m65, &QProcess::errorOccurred, this, &MainWindow::m65_error); - connect(&proc_m65, static_cast<void (QProcess::*) (int, QProcess::ExitStatus)> (&QProcess::finished), - [this] (int exitCode, QProcess::ExitStatus status) { - if (subProcessFailed (&proc_m65, exitCode, status)) - { - QTimer::singleShot (0, this, SLOT (close ())); - } - }); - - connect(&proc_editor, SIGNAL(error(QProcess::ProcessError)), - this, SLOT(editor_error())); + connect(&proc_editor, &QProcess::errorOccurred, this, &MainWindow::editor_error); connect(m_gui_timer, &QTimer::timeout, this, &MainWindow::guiUpdate); @@ -149,13 +375,12 @@ MainWindow::MainWindow(QWidget *parent) : m_ntx=1; m_myCall="K1JT"; m_myGrid="FN20qi"; - m_saveDir="/users/joe/map65/install/save"; - m_azelDir="/users/joe/map65/install/"; + m_saveDir=QDir {m_dataDir}.absoluteFilePath("save"); + m_azelDir=m_dataDir; m_editorCommand="notepad"; m_txFreq=125; m_setftx=0; m_loopall=false; - m_startAnother=false; m_saveAll=false; m_onlyEME=false; m_sec0=-1; @@ -167,7 +392,7 @@ MainWindow::MainWindow(QWidget *parent) : m_NB=false; m_mode="JT65B"; m_mode65=2; - m_fs96000=true; + m_fs96000=1; m_udpPort=50004; m_adjustIQ=0; m_applyIQcal=0; @@ -187,42 +412,39 @@ MainWindow::MainWindow(QWidget *parent) : ySignalMeter = new SignalMeter(ui->yMeterFrame); ySignalMeter->resize(50, 160); -#ifdef WIN32 - while(true) { - int iret=killbyname("m65.exe"); - if(iret == 603) break; - if(iret != 0) msgBox("KillByName return code: " + - QString::number(iret)); - } -#endif + fftwf_import_wisdom_from_filename (QDir {m_dataDir}.absoluteFilePath ("map65_wisdom.dat").toLocal8Bit ()); - if(!mem_m65.attach()) { - if (!mem_m65.create(sizeof(datcom_))) { - msgBox("Unable to create shared memory segment."); - } - } - char *to = (char*)mem_m65.data(); - int size=sizeof(datcom_); - if(datcom_.newdat==0) { - int noffset = 4*4*5760000 + 4*4*322*32768 + 4*4*32768; - to += noffset; - size -= noffset; - } - memset(to,0,size); //Zero all decoding params in shared memory + readSettings(); //Restore user's setup params - fftwf_import_wisdom_from_filename (QDir {m_appDir}.absoluteFilePath ("map65_wisdom.dat").toLocal8Bit ()); + // Push mycall/mygrid/hiscall/hisgrid/neme to the Fortran side here, right + // after settings load, instead of waiting for the first + // MainWindow::decode() call to do it (decode() still pushes these on + // every cycle further down; this just makes the values available + // sooner). run_m65.f90 builds the deep65 CALL3.TXT candidate list eagerly + // before its decode loop starts (build_call3_candidates() in deep65.f90); + // without this, that eager build ran against Fortran's still-default/ + // blank mycall/hiscall, and decode0.f90's genuine mycall-changed check + // then forced a second, redundant rebuild on the first real decode. + { + QString mcall = (m_myCall + " ").mid(0, 12); + QString mgrid = (m_myGrid + " ").mid(0, 6); + QString hcall = (ui->dxCallEntry->text() + " ").mid(0, 12); + QString hgrid = (ui->dxGridEntry->text() + " ").mid(0, 6); + setMyCall(mcall); + setMyGrid(mgrid); + setHisCall(hcall); + setHisGrid(hgrid); + setNeme(0); + if (ui->actionOnly_EME_calls->isChecked()) setNeme(1); + } PaError paerr=Pa_Initialize(); //Initialize Portaudio if(paerr!=paNoError) { msgBox("Unable to initialize PortAudio."); } - readSettings(); //Restore user's setup params - QFile lockFile(m_appDir + "/.lock"); //Create .lock so m65 will wait - lockFile.open(QIODevice::ReadWrite); QFile quitFile(m_appDir + "/.quit"); quitFile.remove(); - proc_m65.start(QDir::toNativeSeparators(m_appDir + "/m65"), {"-s", }); - + m_pbdecoding_style1="QPushButton{background-color: cyan; \ border-style: outset; border-width: 1px; border-radius: 5px; \ border-color: black; min-width: 5em; padding: 3px;}"; @@ -237,8 +459,8 @@ MainWindow::MainWindow(QWidget *parent) : on_actionAstro_Data_triggered(); //Create the other windows on_actionWide_Waterfall_triggered(); - on_actionBand_Map_triggered(); + m_band_map_window->setColors(m_colors); if (m_astro_window) m_astro_window->setFontSize (m_astroFont); @@ -256,6 +478,8 @@ MainWindow::MainWindow(QWidget *parent) : future1 = new QFuture<void>; watcher1 = new QFutureWatcher<void>; connect(watcher1, SIGNAL(finished()),this,SLOT(diskDat())); + bool ok = connect(watcher1, SIGNAL(finished()), this, SLOT(onDiskDecodeFinished())); + qDebug() << "onDiskDecodeFinished watcher connected" << ok; future2 = new QFuture<void>; watcher2 = new QFutureWatcher<void>; @@ -263,8 +487,9 @@ MainWindow::MainWindow(QWidget *parent) : // Assign input device and start input thread soundInThread.setInputDevice(m_paInDevice); - if(m_fs96000) soundInThread.setRate(96000.0); - if(!m_fs96000) soundInThread.setRate(95238.1); + if(m_fs96000 == 1) soundInThread.setRate(96000.0); + else if(m_fs96000 ==0) soundInThread.setRate(95238.1); + else if(m_fs96000 ==2) soundInThread.setRate(192000.0); soundInThread.setBufSize(10*7056); soundInThread.setNetwork(m_network); soundInThread.setPort(m_udpPort); @@ -276,13 +501,11 @@ MainWindow::MainWindow(QWidget *parent) : soundOutThread.setOutputDevice(m_paOutDevice); m_monitoring=true; // Start with Monitoring ON + qDebug() << "m_monitoring set to" << m_monitoring << "at" << Q_FUNC_INFO; + soundInThread.setMonitoring(m_monitoring); m_diskData=false; - m_tol=500; - m_wide_graph_window->setTol(m_tol); m_wide_graph_window->setFcal(m_fCal); - if(m_fs96000) m_wide_graph_window->setFsample(96000); - if(!m_fs96000) m_wide_graph_window->setFsample(95238); m_wide_graph_window->m_mult570=m_mult570; m_wide_graph_window->m_mult570Tx=m_mult570Tx; m_wide_graph_window->m_cal570=m_cal570; @@ -291,7 +514,7 @@ MainWindow::MainWindow(QWidget *parent) : // Create "m_worked", a dictionary of all calls in wsjt.log QFile f("wsjt.log"); - f.open(QIODevice::ReadOnly); + qDebug() << "MainWindow Constructor File open result:" << f.open(QFileDevice::ReadOnly); if(f.isOpen()) { QTextStream in(&f); QString line,t,callsign; @@ -314,26 +537,49 @@ MainWindow::MainWindow(QWidget *parent) : connect (m_wide_graph_window.get (), &WideGraph::f11f12, this, &MainWindow::bumpDF); QTimer::singleShot (0, this,[this]() { - m_messages_window = new Messages(m_settings_filename); + m_messages_window = new Messages(m_settings_filename, m_eclipseFile); m_messages_window->show(); on_actionMessages_triggered(); connect (m_messages_window, &Messages::click2OnCallsign, this, &MainWindow::doubleClickOnMessages); if (m_messages_window) m_messages_window->setColors(m_colors); }); + QTimer::singleShot (2000, [=] { + setNhsym(1); + }); + QTimer::singleShot (4000, [=] { + qDebug() << "MAINWINDOW reads Fortran fcenter as: " << getFcenter(); + }); + //default freq at startup for Doppler and Tsky - datcom_.fcenter = m_wide_graph_window->m_dForceCenterFreq; - if(datcom_.fcenter == 0) datcom_.fcenter = 144.125; + setFcenter(m_wide_graph_window->m_dForceCenterFreq); + if( getFcenter() == 0) setFcenter(144.125); + qDebug() << "MAINWINDOW reached end of Constructor"; // only start the guiUpdate timer after this constructor has finished QTimer::singleShot (0, [=] { m_gui_timer->start(100); //Don't change the 100 ms! }); + + // Start Run_m65 + QTimer::singleShot(0, this, SLOT(startDecoder())); } //--------------------------------------------------- MainWindow destructor MainWindow::~MainWindow() { + // Stop stdout reader thread + stdoutReaderStop.store(true); + + // Wake event so thread exits immediately + if (decoderCtx && decoderCtx->stdoutChan) { + void* ev = decoderCtx->stdoutChan->eventHandle; + if (ev) + win_set_event(ev); + } + + if (stdoutReaderThread.joinable()) + stdoutReaderThread.join(); writeSettings(); if (soundInThread.isRunning()) { soundInThread.quit(); @@ -344,14 +590,380 @@ MainWindow::~MainWindow() soundOutThread.wait(3000); } Pa_Terminate(); - fftwf_export_wisdom_to_filename (QDir {m_appDir}.absoluteFilePath ("map65_wisdom.dat").toLocal8Bit ()); - if(!m_decoderBusy) { - QFile lockFile(m_appDir + "/.lock"); - lockFile.remove(); - } + fftwf_export_wisdom_to_filename (QDir {m_dataDir}.absoluteFilePath ("map65_wisdom.dat").toLocal8Bit ()); delete ui; } +void MainWindow::startDecoder() +{ + qDebug() << "MAINWINDOW calling run_m65_ "; + + QFutureWatcher<void>* watcher_m65 = new QFutureWatcher<void>(this); + connect(watcher_m65, &QFutureWatcher<void>::finished, + this, &MainWindow::onRunM65Finished); + + watcher_m65->setFuture(QtConcurrent::run([=]() { + + qDebug() << "DECODE: starting run_m65_() with m_fs96000=" << m_fs96000; + + // Hook up shared stdout channel for Fortran + StdoutSharedRegion* region = + decoderCtx->stdoutChan->shared.getRegion(); + + void* bufPtr = static_cast<void*>(region->buffer); + void* hdrPtr = static_cast<void*>(®ion->header); + int bufSize = static_cast<int>(decoderCtx->stdoutChan->shared.getBufferSize()); + intptr_t eventH = reinterpret_cast<intptr_t>(decoderCtx->stdoutChan->eventHandle); + + set_stdout_channel(bufPtr, hdrPtr, bufSize, eventH); + + // Now run the decoder + std::lock_guard<std::mutex> lock(g_fortran_decode_mutex); + int xpol_flag = m_xpol ? 1 : 0; + run_m65_(&xpol_flag, &m_fs96000); + + qDebug() << "DECODE: run_m65_() returned"; + })); + +} + +void MainWindow::startSharedMemoryStdoutReader(DecoderContext* ctx) +{ + stdoutReaderThread = std::thread([this, ctx]() { + + StdoutSharedRegion* region = + ctx->stdoutChan->shared.getRegion(); + + char* bufferBase = + reinterpret_cast<char*>(region->buffer); + + std::size_t bufSize = + ctx->stdoutChan->shared.getBufferSize(); + + // Linux: eventHandle is a void* pointing to posix_event_t + void* ev = ctx->stdoutChan->eventHandle; + + // NEW: start reading from the current writeIndex + StdoutSharedHeader h0 = region->header; + std::uint32_t readIndex = h0.writeIndex; + if (readIndex >= bufSize) + readIndex = 0; + region->header.readIndex = readIndex; + + // TEMP diagnostic 2026-09-10: h0.writeIndex should always be 0 here -- + // StdoutSharedMemory's constructor unconditionally zeroes writeIndex/ + // readIndex right after mapping (see stdout_shared_memory.cpp), and + // that happens synchronously on the main thread before this reader + // thread is even spawned. If this ever logs a nonzero value, that + // assumption is wrong and this "start from current writeIndex" line + // is silently skipping over real data written before this point. + cppDbg(QString("stdout reader INIT readIndex=%1 (h0.writeIndex=%2) bufSize=%3") + .arg(readIndex).arg(h0.writeIndex).arg(bufSize)); + + std::string lineBuffer; + + while (!stdoutReaderStop.load()) { + + // Linux replacement for WaitForSingleObject(ev, INFINITE) + win_wait_for_single_object(ev); + + // After wakeup, read new data + StdoutSharedHeader h = region->header; + std::uint32_t writeIndex = h.writeIndex; + if (writeIndex >= bufSize) + writeIndex = 0; + + while (readIndex != writeIndex) { + char c = bufferBase[readIndex]; + readIndex++; + if (readIndex >= bufSize) + readIndex = 0; + + lineBuffer.push_back(c); + if (c == '\n') { + std::string line = lineBuffer; + lineBuffer.clear(); + + QString text = QString::fromStdString(line); + QMetaObject::invokeMethod( + this, + [this, text]() { processStdOut(text); }, + Qt::QueuedConnection + ); + } + } + + // Publish how far we've drained so the Fortran writer can + // compute free space and wait for room instead of wrapping + // around and overwriting data we haven't read yet. + region->header.readIndex = readIndex; + } + + }); +} + +void MainWindow::processStdOut(QString t) +{ + +// qDebug().noquote() << QDateTime::currentMSecsSinceEpoch() << "PROCESS STDOUT:" << t; + + // TEMP diagnostic 2026-09-10: confirms whether a decode line that made it + // into map65_rx.log (written Fortran-side, independent of this whole + // path) ever actually arrived here on the GUI thread. If a "!"-prefixed + // line is missing from this log around the time of a report-vs-rx.log + // mismatch, the loss is upstream (shared-memory ring buffer / reader + // thread); if it IS here but never appended to the Messages window, the + // loss is in handleControlLine/shouldDisplay below. + cppDbg(QString("processStdOut RECV \"%1\"").arg(t.trimmed())); + + if (m_decodeDisplayFilter.handleControlLine(t)) return; + + if (t.startsWith("<DecodeSkipped>")) { + bool validRequestId = false; + auto requestId = t.trimmed().section(' ', -1).toLongLong(&validRequestId); + if (validRequestId && is_current_decode_request(requestId)) { + m_decodeDisplayFilter.completeCycle(); + decodeBusy(false); + ui->DecodeButton->setStyleSheet(""); + } + return; + } + + //qDebug() << "in processStdOut STDOUT:" << t; +if (t.indexOf("<QuickDecodeDone>") >= 0) { + + // Any decoder output means "not idle" — reset idle timer in auto/disk mode + + m_nsum = t.mid(17,4).toInt(); + m_nsave = t.mid(21,4).toInt(); + lab7->setText(QString{"Avg: %1"}.arg(m_nsum)); + if (m_modeQ65 > 0) + m_wide_graph_window->setDecodeFinished(); + } + + // --- <EarlyFinished> / <DecodeFinished> --- + if (t.indexOf("<EarlyFinished>") >= 0 || t.indexOf("<DecodeFinished>") >= 0) { + + if (t.indexOf("<DecodeFinished>") >= 0) { + bool validRequestId = false; + auto requestId = t.trimmed().section(' ', -1).toLongLong(&validRequestId); + if (!validRequestId || !is_current_decode_request(requestId)) return; + } + + if (t.indexOf("<EarlyFinished>") >= 0) + m_decodeDisplayFilter.completeEarlyPass(); + if (t.indexOf("<DecodeFinished>") >= 0) + m_decodeDisplayFilter.completeCycle(); + + if (m_widebandDecode) { + if (m_messages_window) + m_messages_window->setText(m_messagesText, m_bandmapText); + if (m_band_map_window) + m_band_map_window->setText(m_bandmapText); + m_widebandDecode = false; + } + if (t.indexOf("<DecodeFinished>") >= 0) { + ++m_decodeFinishedCount; + + decodeBusy(false); +// qDebug().noquote() << QDateTime::currentMSecsSinceEpoch() << "decodeBusy(false)"; + if (m_diskData) onDiskDecodeFinished(); + + int ndecodes = t.mid(40,5).toInt(); + lab8->setText(QString::number(ndecodes)); + m_map65RxLog = 0; + + // Only clear the button's "busy" styling on <DecodeFinished>, not + // <EarlyFinished> -- decodeBusy(false) is likewise gated on + // <DecodeFinished> alone, and the final pass can legitimately take + // many seconds longer than the early pass, during which the button + // must keep showing busy while more decodes are still arriving. + ui->DecodeButton->setStyleSheet(""); + } + return; +} + + // --- same position as legacy --- + read_log(); + + // --- "!" decoded text lines --- + if (t.startsWith("!")) { + int n = t.length(); + int m = 2; +#ifdef WIN32 + m = 3; +#endif + // The m=2/m=3 trim above assumes a normal decode line's fixed + // layout, whose last field is disposable padding/polarization -- + // Find Delta Phi's "!Best-fit Dphi = NNN deg" summary line ends on + // real content instead (the "g" of "deg"), so the same trim chops + // it to "...de". Just trim the line terminator for this one case. + const QString decode_line = (t.indexOf("Best-fit") >= 0) + ? t.mid(1).trimmed() + : t.mid(1, n - m); + + if (n >= 30 || t.indexOf("Best-fit") >= 0) { + bool const display = m_decodeDisplayFilter.shouldDisplay(decode_line); + // TEMP diagnostic 2026-09-10 -- see the matching note at the top + // of processStdOut(). If display=false here for a line that has + // no legitimate earlier-pass duplicate, the display filter itself + // (map65_decode_display_filter.cpp) is the culprit. + cppDbg(QString("shouldDisplay=%1 for \"%2\"").arg(display ? "true" : "false").arg(decode_line)); + if (display) + ui->decodedTextBrowser->append(decode_line); + } + + int max = ui->decodedTextBrowser->verticalScrollBar()->maximum(); + ui->decodedTextBrowser->verticalScrollBar()->setValue(max); + + // Callsign-overlay tap (N6NU 2026-05-13, DG2YCB feedback round 4). + // Two stdout-write paths for decodes (q65b.f90:227, map65a.f90:430) + // share enough format that we can parse them together: + // JT65: ("!",I3,I5,I4,I6.4,F5.1,I5,1X,A1,1X,A22,I2,I5,I5,1X,A1) + // Q65 : ("!",I3.3,I5,I4,I6.4,F5.1,I5," : ",A28,A3,I4,1X,A1) + // The Q65 line is the only one that contains a literal " : " — use + // that as the mode discriminator (right(2) does NOT work: both + // lines end in 1X+A1 = " cp", just a single status char). + // + // Q65 stdout writes are guarded by an in-tolerance-of-mouse check + // (q65b.f90:226), so most off-target Q65 decodes never reach this + // tap. The "&" bandmap handler below covers them as a fallback. + if (m_wide_graph_window) { + const QString trimmed = decode_line.trimmed(); + const int sep = decode_line.indexOf(" : "); + const bool is_jt65 = (sep < 0); // " : " present ⇒ Q65 + + // The "!" decode line packs the audio frequency into TWO + // columns per the Fortran writes at map65a.f90:387 and + // q65b.f90:227 — format ("!",I3,I5,...) where nkHz is the + // integer kHz and ndf is the signed delta-Hz within that + // kHz, so true freq = nkHz + ndf/1000.0. The previous + // "first token that parses as a number in [0,1e6)" approach + // dropped ndf (off by ±500 Hz for small nkHz) or worse, + // picked ndf itself when nkHz ≥ 100 made the right- + // justified I3 collide with the leading "!" (the parser + // then read ndf in Hz as kHz). + QString rest = trimmed; + if (rest.startsWith('!')) rest = rest.mid(1); + const QStringList all_cols = rest.split( + QRegularExpression("\\s+"),SkipEmptyParts); + double freq_khz = -1.0; + if (all_cols.size() >= 2) { + bool ok1 = false, ok2 = false; + const int nkHz = all_cols[0].toInt(&ok1); + const int ndf = all_cols[1].toInt(&ok2); + if (ok1 && ok2) freq_khz = nkHz + ndf / 1000.0; + } + + QString body; + if (sep > 0) { + body = decode_line.mid(sep + 3).trimmed(); + } else if (decode_line.size() > 31) { + body = decode_line.mid(31).trimmed(); + } + const QStringList msg_cols = body.split( + QRegularExpression("\\s+"),SkipEmptyParts); + QString sender; + if (msg_cols.size() >= 2) { + if (msg_cols[0] == "CQ") { + if (msg_cols.size() >= 3 && msg_cols[1] == "DX") sender = msg_cols[2]; + else sender = msg_cols[1]; + } else { + sender = msg_cols[1]; // directed: TO_call FROM_call + } + } + static const QRegularExpression call_re( + "^[A-Z0-9]{1,3}[0-9][A-Z0-9]{0,3}[A-Z](/[A-Z0-9]+)?$"); + if (freq_khz > 0 && !sender.isEmpty() + && call_re.match(sender.toUpper()).hasMatch()) { + m_wide_graph_window->addDecodeLabel(freq_khz, sender, is_jt65); + } + } + + // clear snapshots for this decode run, just like legacy + m_messagesText.clear(); + m_bandmapText.clear(); + } + + // --- "@" message lines --- + if (t.startsWith("@")) { + m_messagesText += t.mid(1); + m_widebandDecode = true; + } + + // --- "&" bandmap lines --- + // N6NU 2026-05-24: format widened to include the 5-char ndf from + // line3(k)(9:13). New layout: + // "&" + I3 kHz + I5 ndf + " " + A6 call + A2 age + // Old layout (pre-260524, used by stock map65): + // "&" + I3 kHz + " " + A6 call + A2 age + // We auto-detect by checking column 4: if it's a digit/space-of-int, + // it's the new format. Old format has the space-separator there. + if (t.startsWith("&")) { + // Detect format. New: chars 4..8 are an int (ndf). Old: char 4 + // is a space and chars 5..10 are the callsign. + const QString ndf_field = t.mid(4, 5); + bool ndf_ok = false; + const int ndf_hz = ndf_field.trimmed().toInt(&ndf_ok); + const int call_start = ndf_ok ? 10 : 5; + + QString q(t); + QString callsign = q.mid(call_start); + callsign = callsign.mid(0, callsign.indexOf(" ")); + if (callsign.length() > 2) { + if (m_worked[callsign]) { + q = q.mid(1,4) + " " + q.mid(call_start); + } else { + q = q.mid(1,4) + " *" + q.mid(call_start); + } + m_bandmapText += q; + + // Fallback overlay tap (N6NU 2026-05-13, DG2YCB feedback r4). + // We can't know the mode from this line, so pass is_jt65=false + // and mode_reliable=false. With the new format we now also + // have ndf precision, so freq_reliable=true. Old format + // callers still pass freq_reliable=false (integer kHz only). + if (m_wide_graph_window) { + bool ok_khz = false; + const int nkHz = t.mid(1, 3).trimmed().toInt(&ok_khz); + const double freq_khz = ndf_ok + ? (nkHz + ndf_hz / 1000.0) + : double(nkHz); + static const QRegularExpression call_re( + "^[A-Z0-9]{1,3}[0-9][A-Z0-9]{0,3}[A-Z](/[A-Z0-9]+)?$"); + if (ok_khz && freq_khz > 0 + && call_re.match(callsign.toUpper()).hasMatch()) { + m_wide_graph_window->addDecodeLabel( + freq_khz, callsign, /*is_jt65=*/false, + /*mode_reliable=*/false, + /*freq_reliable=*/ndf_ok); + } + } + } + } + + // --- "=" debug lines --- + if (t.startsWith("=")) { + int n = t.size(); + qDebug() << t.mid(1, n - 3).trimmed(); + } + // --- END OF processStdOut --- +} + +void MainWindow::onRunM65Finished() { + // Do something when run_m65 finishes + // qDebug() << "DECODE: onRunM65Finished()"; +} + +void MainWindow::onDiskDecodeFinished() +{ + if (!m_path.isEmpty()) + setWindowTitle("MAP65â„¢ - " + QFileInfo(m_path).fileName()); + + if (m_loopall) + on_actionOpen_next_in_directory_triggered(); +} + //-------------------------------------------------------- writeSettings() void MainWindow::writeSettings() { @@ -365,11 +977,13 @@ void MainWindow::writeSettings() settings.setValue("DXgrid",ui->dxGridEntry->text()); } + { SettingsGroup g {&settings, "Common"}; settings.setValue("MyCall",m_myCall); settings.setValue("MyGrid",m_myGrid); settings.setValue("IDint",m_idInt); - settings.setValue("PTTport",m_pttPort); + settings.setValue("PTTpath",m_pttPath); + settings.setValue("PTTPortNumber",m_pttPortNumber); settings.setValue("AstroFont",m_astroFont); settings.setValue("Xpol",m_xpol); settings.setValue("XpolX",m_xpolx); @@ -378,15 +992,12 @@ void MainWindow::writeSettings() settings.setValue("Editor",m_editorCommand); settings.setValue("DXCCpfx",m_dxccPfx); settings.setValue("Timeout",m_timeout); - settings.setValue("TxPower",txPower); - settings.setValue("IQamp",iqAmp); - settings.setValue("IQphase",iqPhase); settings.setValue("ApplyIQcal",m_applyIQcal); settings.setValue("dPhi",m_dPhi); settings.setValue("Fcal",m_fCal); settings.setValue("Fadd",m_fAdd); settings.setValue("NetworkInput", m_network); - settings.setValue("FSam96000", m_fs96000); + settings.setValue("FSam96000", QString::number(m_pendingFs96000 >= 0 ? m_pendingFs96000 : m_fs96000)); settings.setValue("SoundInIndex",m_nDevIn); settings.setValue("paInDevice",m_paInDevice); settings.setValue("SoundOutIndex",m_nDevOut); @@ -424,12 +1035,26 @@ void MainWindow::writeSettings() settings.setValue("w3szUrl",m_w3szUrl); //liveCQ settings.setValue("otherUrl",m_otherUrl); //liveCQ settings.setValue("spotPSK",m_spot_to_psk_reporter); + settings.setValue("PSKReporterTCPIP",m_psk_reporter_tcpip); + settings.setValue("FTol",m_tol); + settings.endGroup(); + } + + { + settings.beginGroup("TxTune"); + settings.setValue("geometry", g_TxTuneGeometry); + settings.setValue("TxPower",txPower); + settings.setValue("IQamp",iqAmp); + settings.setValue("IQphase",iqPhase); + settings.endGroup(); + } } //---------------------------------------------------------- readSettings() void MainWindow::readSettings() { QSettings settings(m_settings_filename, QSettings::IniFormat); + auto const pskReporterSettings = readMap65PSKReporterSettings(settings); { SettingsGroup g {&settings, "MainWindow"}; restoreGeometry(settings.value("geometry").toByteArray()); @@ -440,31 +1065,47 @@ void MainWindow::readSettings() ui->txFirstCheckBox->setChecked(m_txFirst); } + { SettingsGroup g {&settings, "Common"}; m_myCall=settings.value("MyCall","").toString(); m_myGrid=settings.value("MyGrid","").toString(); m_idInt=settings.value("IDint",0).toInt(); - m_pttPort=settings.value("PTTport",0).toInt(); + m_pttPath=settings.value("PTTpath",0).toString(); + m_pttPortNumber = settings.value("PTTPortNumber",0).toInt(); + #if !defined(Q_OS_WIN) + ptt_set_override(m_pttPath.toUtf8().constData()); + #endif m_astroFont=settings.value("AstroFont",20).toInt(); m_xpol=settings.value("Xpol",false).toBool(); ui->actionFind_Delta_Phi->setEnabled(m_xpol); m_xpolx=settings.value("XpolX",false).toBool(); - m_saveDir=settings.value("SaveDir",m_appDir + "/save").toString(); - m_azelDir=settings.value("AzElDir",m_appDir).toString(); + m_saveDir=settings.value("SaveDir",QDir {m_dataDir}.absoluteFilePath("save")).toString(); + m_azelDir=settings.value("AzElDir",m_dataDir).toString(); + if (!settings.value("AzElDirMigratedToDataDir",false).toBool()) { + // One-time migration: earlier versions defaulted AzElDir to the + // application/bin directory instead of the user data directory, and + // that default got persisted the first time settings were saved. An + // exact-match check against the *current* m_appDir can't catch this, + // since the saved value may point at some older build's bin directory + // that no longer matches this run's m_appDir at all. So instead: force + // everyone onto the new default exactly once, unconditionally, then + // remember it's done so a deliberate later customization (via the + // Setup dialog's AzEl Directory field) is never overwritten again. + m_azelDir = m_dataDir; + settings.setValue("AzElDirMigratedToDataDir",true); + } m_editorCommand=settings.value("Editor","notepad").toString(); m_dxccPfx=settings.value("DXCCpfx","").toString(); m_timeout=settings.value("Timeout",20).toInt(); - txPower=settings.value("TxPower",100).toInt(); - iqAmp=settings.value("IQamp",0).toInt(); - iqPhase=settings.value("IQphase",0).toInt(); m_applyIQcal=settings.value("ApplyIQcal",0).toInt(); ui->actionApply_IQ_Calibration->setChecked(m_applyIQcal!=0); m_dPhi=settings.value("dPhi",0).toInt(); m_fCal=settings.value("Fcal",0).toInt(); - m_fAdd=settings.value("FAdd",0).toDouble(); + m_fAdd=settings.value("Fadd",0).toDouble(); soundInThread.setFadd(m_fAdd); m_network = settings.value("NetworkInput",true).toBool(); - m_fs96000 = settings.value("FSam96000",true).toBool(); + m_fs96000 = readFSam96000(settings,1); + qDebug() << "In MainWindow::readSettings FSam96000 is read as:" << m_fs96000; m_nDevIn = settings.value("SoundInIndex", 0).toInt(); m_paInDevice = settings.value("paInDevice",0).toInt(); m_nDevOut = settings.value("SoundOutIndex", 0).toInt(); @@ -530,55 +1171,95 @@ void MainWindow::readSettings() if(m_ndepth==0) ui->actionNo_Deep_Search->setChecked(true); if(m_ndepth==1) ui->actionNormal_Deep_Search->setChecked(true); if(m_ndepth==2) ui->actionAggressive_Deep_Search->setChecked(true); + if(m_ndepth==3) ui->actionFull_Deep_Search->setChecked(true); m_w3szUrl=settings.value("w3szUrl",true).toBool(); m_otherUrl=settings.value("otherUrl","").toString(); - m_spot_to_psk_reporter=settings.value("spotPSK",true).toBool(); + m_spot_to_psk_reporter = pskReporterSettings.enabled; + m_psk_reporter_tcpip = pskReporterSettings.use_tcpip; + + m_tol=settings.value("FTol",500).toInt(); + m_wide_graph_window->setTol(m_tol); + int i = 5; + if(m_tol==20) i=1; + if(m_tol==50) i=2; + if(m_tol==100) i=3; + if(m_tol==200) i=4; + if(m_tol==500) i=5; + if(m_tol==1000) i=6; + ui->labTol1->setText(QString::number(m_tol)); + ui->tolSpinBox->setValue(i); + qDebug() << "In mainwindow m_spot_to_psk_reporter is: " << m_spot_to_psk_reporter; + + qDebug() << "In mainwindow m_modeTx is: " << m_modeTx; + qDebug() << "In mainwindow m_mode is: " << m_mode; + qDebug() << "In mainwindow n_modeJT65 is: " << m_modeJT65; + qDebug() << "In mainwindow n_modeQ65 is: " << m_modeQ65; + settings.endGroup(); + } + + { + settings.beginGroup("TxTune"); + g_TxTuneGeometry = settings.value("geometry").toByteArray(); + txPower=settings.value("TxPower",100).toInt(); + iqAmp=settings.value("IQamp",0).toInt(); + iqPhase=settings.value("IQphase",0).toInt(); + settings.endGroup(); + } } //-------------------------------------------------------------- dataSink() void MainWindow::dataSink(int k) { - static float s[NFFT],splot[NFFT]; + static float* s = nullptr; + static float* splot = nullptr; + if (!s) { + s = new float[active_nfft]; + splot = new float[active_nfft]; + } static int n=0; static int ihsym=0; static int nzap=0; static int ntrz=0; static int nkhz; - static int nfsample=96000; - static int nxpol=0; + int nfsample = 96000; + if (m_fs96000 == 0) nfsample = 95238; + else if(m_fs96000 == 2) nfsample = 192000; + setNfsample(nfsample); + int nxpol= m_xpol ? 1 : 0; + setNxpol(nxpol); static int nsec0=0; static int nsum=0; - static float fgreen; static int ndiskdat; static int nb; static int nadj=0; static float px=0.0,py=0.0; - static uchar lstrong[1024]; + constexpr int lstrongSize = 1024; + static uchar lstrong[lstrongSize]; static float rejectx; static float rejecty; static float slimit; static double xsum=0.0; - + if(m_diskData) { ndiskdat=1; - datcom_.ndiskdat=1; + setNdiskdat(1); } else { ndiskdat=0; - datcom_.ndiskdat=0; + setNdiskdat(0); } + + setIdphi(m_dPhi); // Get x and y power, polarized spectrum, nkhz, and ihsym nb=0; if(m_NB) nb=1; - nfsample=96000; - if(!m_fs96000) nfsample=95238; nxpol=0; if(m_xpol) nxpol=1; - fgreen=m_wide_graph_window->fGreen(); nadj++; if(m_adjustIQ==0) nadj=0; + symspec_(&k, &nxpol, &ndiskdat, &nb, &m_NBslider, &m_dPhi, - &nfsample, &fgreen, &m_adjustIQ, &m_applyIQcal, + &m_adjustIQ, &m_applyIQcal, &m_gainx, &m_gainy, &m_phasex, &m_phasey, &rejectx, &rejecty, &px, &py, s, &nkhz, &ihsym, &nzap, &slimit, lstrong); @@ -613,8 +1294,9 @@ void MainWindow::dataSink(int k) } xSignalMeter->setValue(px); // Update the signal meters ySignalMeter->setValue(py); + if(m_monitoring || m_diskData) { - m_wide_graph_window->dataSink2(s,nkhz,ihsym,m_diskData,lstrong); + m_wide_graph_window->dataSink2(s,nkhz,ihsym,m_diskData,lstrong,lstrongSize); } if(nadj == 10) { @@ -627,7 +1309,7 @@ void MainWindow::dataSink(int k) ); } else { ui->decodedTextBrowser->append( - QString {"Amp: %1 Phase: %1"} + QString {"Amp: %1 Phase: %2"} .arg (m_gainx, 6, 'f', 4) .arg (m_phasex, 6, 'f', 4) ); @@ -638,28 +1320,28 @@ void MainWindow::dataSink(int k) //Average over specified number of spectra if (n==0) { - for (int i=0; i<NFFT; i++) + for (int i=0; i<active_nfft; i++) splot[i]=s[i]; } else { - for (int i=0; i<NFFT; i++) + for (int i=0; i<active_nfft; i++) splot[i] += s[i]; } n++; if (n>=m_waterfallAvg) { - for (int i=0; i<NFFT; i++) { + for (int i=0; i<active_nfft; i++) { splot[i] /= n; //Normalize the average } // Time according to this computer qint64 ms = QDateTime::currentMSecsSinceEpoch() % 86400000; - int ntr = (ms/1000) % m_TRperiod; - if((m_diskData && ihsym <= m_waterfallAvg) || (!m_diskData && ntr<ntrz)) { - for (int i=0; i<NFFT; i++) { + int ntr1 = (ms/1000) % m_TRperiod; + if((m_diskData && ihsym <= m_waterfallAvg) || (!m_diskData && ntr1<ntrz)) { + for (int i=0; i<active_nfft; i++) { splot[i] = 1.e30; } } - ntrz=ntr; + ntrz=ntr1; n=0; } @@ -667,19 +1349,22 @@ void MainWindow::dataSink(int k) if(m_RxState==0 and ihsym>=280 and !m_diskData) { //Early decode, t=52 s m_RxState=1; - datcom_.newdat=1; - datcom_.nagain=0; - datcom_.nhsym=ihsym; + setDecoderReady(0); + setNewdat(1); + setNagain(0); + setNhsym(280); QDateTime t = QDateTime::currentDateTimeUtc(); m_dateTime=t.toString("yyyy-MMM-dd hh:mm"); decode(); //Start the decoder + // qDebug() << "decoding at t=52s in dataSink in mainwindow.cpp"; } if(m_RxState<=1 and ihsym>=302) { //Decode at t=56 s (for Q65 and data from disk) m_RxState=2; - datcom_.newdat=1; - datcom_.nagain=0; - datcom_.nhsym=ihsym; + setDecoderReady(0); + setNewdat(1); + setNagain(0); + setNhsym(302); QDateTime t = QDateTime::currentDateTimeUtc(); m_dateTime=t.toString("yyyy-MMM-dd hh:mm"); decode(); //Start the decoder @@ -688,12 +1373,174 @@ void MainWindow::dataSink(int k) t.time().toString("hhmm"); if(m_xpol) fname += ".tf2"; if(!m_xpol) fname += ".iq"; - *future2 = QtConcurrent::run(savetf2, fname, m_xpol); + *future2 = QtConcurrent::run([this](QString fname, bool xpol) { + this->savetf2(fname, xpol); + }, fname, m_xpol); + + qDebug() << "saving to file " << fname << " in dataSink in mainwindow.cpp"; watcher2->setFuture(*future2); } } + soundInThread.m_dataSinkBusy.store (false, std::memory_order_release); +} - soundInThread.m_dataSinkBusy=false; +/* Generate gaussian random float with mean=0 and std_dev=1 */ +float gran() +{ + float fac,rsq,v1,v2; + static float gset; + static int iset; + + if(iset){ + /* Already got one */ + iset = 0; + return gset; + } + /* Generate two evenly distributed numbers between -1 and +1 + * that are inside the unit circle + */ + do { + v1 = 2.0 * (float)rand() / RAND_MAX - 1; + v2 = 2.0 * (float)rand() / RAND_MAX - 1; + rsq = v1*v1 + v2*v2; + } while(rsq >= 1.0 || rsq == 0.0); + fac = sqrt(-2.0*log(rsq)/rsq); + gset = v1*fac; + iset++; + return v2*fac; +} + +float* MainWindow::getDd() const +{ + return dd; +} + +void MainWindow::savetf2(QString fname, bool xpol) +{ + int npts=2*56*g_sampleRate; + if(xpol) npts=2*npts; + FILE* fp = fopen(fname.toUtf8().constData(), "wb"); + + if (!fp) { + qDebug() << "FAILED TO OPEN FILE:" << fname; + perror("fopen"); + return; + } + + qint16* buf = static_cast<qint16*>(malloc(npts * sizeof(*buf))); + + if(fp != NULL) { + double fcenter = getFcenter(); + //fcenter = 1296.125; + fwrite(&fcenter, sizeof(fcenter), 1, fp); // Write fcenter to file + uint64_t zero = 0; + fwrite(&zero, sizeof(zero), 1, fp); // another 8 bytes + qDebug() << "in savetf2 fcenter is: " << fcenter; + + int j = 0; + for (int i = 0; i < npts; i += 2) { + buf[i] = static_cast<qint16>(dd[j++]); + buf[i + 1] = static_cast<qint16>(dd[j++]); + if (!xpol) j += 2; // Skip over dd(3,x) and dd(4,x) + } + + fwrite(buf, sizeof(buf[0]), npts, fp); + qDebug() << "saving file " << fname << " to disk in savetf2 in mainwindow.cpp"; + fclose(fp); + } + free(buf); +} + +void MainWindow::getfile(QString fname, bool xpol, int dbDgrd) +{ + cancel_pending_decode_requests(); + int npts = 2 * 56 * g_sampleRate; + if (xpol) npts = 2 * npts; + + // j indexes dd[], which has 4 channels per pair + int j = 0; + + // Clear id[] properly + memset(id.data(), 0, npts * sizeof(id[0])); + + // Open file + FILE* fp = fopen(fname.toUtf8().constData(), "rb"); + if (!fp) { + qWarning() << "Failed to open file:" << fname; + return; + } + + qDebug().noquote() << QString("NEWFILE: nfsample=%1 nrate_active=%2") + .arg(active_nfft) + .arg(g_sampleRate); + + + // Read fcenter + double fcenter = 0.0; + if (fread(&fcenter, sizeof(fcenter), 1, fp) != 1) { + fclose(fp); + return; + } + + setFcenter(fcenter); + + qint64 sampleBytes = static_cast<qint64>(npts) * static_cast<qint64>(sizeof(id[0])); + qint64 expectedPaddedSize = static_cast<qint64>(sizeof(fcenter)) + + static_cast<qint64>(sizeof(uint64_t)) + sampleBytes; + if (QFileInfo {fname}.size() == expectedPaddedSize) { + uint64_t pad = 0; + if (fread(&pad, sizeof(pad), 1, fp) != 1) { + fclose(fp); + return; + } + } + + + // Read raw samples + size_t nRead = fread(id.data(), sizeof(id[0]), npts, fp); + qDebug() << "fread read" << nRead << "samples, expected" << npts; + + fclose(fp); + + // Compute degradation factors + float dgrd = 0.0; + if (dbDgrd < 0) + dgrd = 23.0 * sqrt(pow(10.0, -0.1 * (double)dbDgrd) - 1.0); + + float fac = 23.0 / sqrt(dgrd * dgrd + 23.0 * 23.0); + + // Fill dd[] + j = 0; + for (int i = 0; i < npts; i += 2) { + + if (dbDgrd < 0) { + dd[j++] = fac * ((float)id[i] + dgrd * gran()); + dd[j++] = fac * ((float)id[i + 1] + dgrd * gran()); + } else { + dd[j++] = id[i]; + dd[j++] = id[i + 1]; + } + + if (!xpol) { + // Skip channels 3 and 4 + j += 2; + + } + } + + // qDebug() << "GETFILE: starting decode for:" << fname; + setNdiskdat(1); + int nfreq = getFcenter(); + if (nfreq > 9998) setFcenter(9990.100); + + int i0 = fname.indexOf(".tf2"); + if (i0 < 0) i0 = fname.indexOf(".iq"); + + setNutc(0); + if (i0 > 0) { + setNutc(100 * fname.mid(i0 - 4, 2).toInt() + + fname.mid(i0 - 2, 2).toInt()); + } } void MainWindow::showSoundInError(const QString& errorMsg) @@ -702,142 +1549,112 @@ void MainWindow::showSoundInError(const QString& errorMsg) void MainWindow::showStatusMessage(const QString& statusMsg) {statusBar()->showMessage(statusMsg);} -void MainWindow::on_actionDeviceSetup_triggered() //Setup Dialog +void MainWindow::on_actionDeviceSetup_triggered() { DevSetup dlg(this); - dlg.m_myCall=m_myCall; - dlg.m_myGrid=m_myGrid; - dlg.m_idInt=m_idInt; - dlg.m_pttPort=m_pttPort; - dlg.m_astroFont=m_astroFont; - dlg.m_xpol=m_xpol; - dlg.m_xpolx=m_xpolx; - dlg.m_saveDir=m_saveDir; - dlg.m_azelDir=m_azelDir; - dlg.m_editorCommand=m_editorCommand; - dlg.m_dxccPfx=m_dxccPfx; - dlg.m_timeout=m_timeout; - dlg.m_dPhi=m_dPhi; - dlg.m_fCal=m_fCal; - dlg.m_fAdd=m_fAdd; - dlg.m_network=m_network; - dlg.m_fs96000=m_fs96000; - dlg.m_nDevIn=m_nDevIn; - dlg.m_nDevOut=m_nDevOut; - dlg.m_udpPort=m_udpPort; - dlg.m_IQswap=m_IQswap; - dlg.m_dB=m_dB; - dlg.m_initIQplus=m_initIQplus; - dlg.m_bIQxt=m_bIQxt; - dlg.m_cal570=m_cal570; - dlg.m_TxOffset=m_TxOffset; - dlg.m_mult570=m_mult570; - dlg.m_mult570Tx=m_mult570Tx; - dlg.m_colors=m_colors; - dlg.m_w3szUrl = m_w3szUrl; //liveCQ - dlg.m_otherUrl=m_otherUrl; //liveCQ - dlg.m_spot_to_psk_reporter = m_spot_to_psk_reporter; + + connect(&dlg, &DevSetup::sampleRateChanged, + this, &MainWindow::onSampleRateChanged); dlg.initDlg(); - if(dlg.exec() == QDialog::Accepted) { - m_myCall=dlg.m_myCall; - m_myGrid=dlg.m_myGrid; - m_idInt=dlg.m_idInt; - m_pttPort=dlg.m_pttPort; - m_astroFont=dlg.m_astroFont; - if(m_astro_window && m_astro_window->isVisible()) m_astro_window->setFontSize(m_astroFont); - m_xpol=dlg.m_xpol; - ui->actionFind_Delta_Phi->setEnabled(m_xpol); - m_xpolx=dlg.m_xpolx; - m_saveDir=dlg.m_saveDir; - m_azelDir=dlg.m_azelDir; - m_editorCommand=dlg.m_editorCommand; - m_dxccPfx=dlg.m_dxccPfx; - m_timeout=dlg.m_timeout; - m_dPhi=dlg.m_dPhi; - m_fCal=dlg.m_fCal; - m_fAdd=dlg.m_fAdd; - m_wide_graph_window->setFcal(m_fCal); - m_fs96000=dlg.m_fs96000; - m_network=dlg.m_network; - m_nDevIn=dlg.m_nDevIn; - m_paInDevice=dlg.m_paInDevice; - m_nDevOut=dlg.m_nDevOut; - m_paOutDevice=dlg.m_paOutDevice; - m_udpPort=dlg.m_udpPort; - m_IQswap=dlg.m_IQswap; - m_dB=dlg.m_dB; - m_initIQplus=dlg.m_initIQplus; - m_bIQxt=dlg.m_bIQxt; - m_colors=dlg.m_colors; - m_messages_window->setColors(m_colors); - m_band_map_window->setColors(m_colors); - m_cal570=dlg.m_cal570; - m_TxOffset=dlg.m_TxOffset; - m_mult570Tx=dlg.m_mult570Tx; - m_wide_graph_window->m_mult570=m_mult570; - m_wide_graph_window->m_mult570Tx=m_mult570Tx; - m_wide_graph_window->m_cal570=m_cal570; - soundInThread.setSwapIQ(m_IQswap); - soundInThread.setScale(m_dB); - m_w3szUrl=dlg.m_w3szUrl; - m_otherUrl=dlg.m_otherUrl; - m_spot_to_psk_reporter=dlg.m_spot_to_psk_reporter; - QSettings settings(m_settings_filename, QSettings::IniFormat); + + if (dlg.exec() == QDialog::Accepted) { - SettingsGroup g {&settings, "MainWindow"}; - } - SettingsGroup g {&settings, "Common"}; - settings.setValue("w3szUrl",m_w3szUrl); //liveCQ - settings.setValue("otherUrl",m_otherUrl); //liveCQ - settings.setValue("spotPSK",m_spot_to_psk_reporter); - settings.setValue("MyCall",m_myCall); - settings.setValue("MyGrid",m_myGrid); - settings.setValue("IDint",m_idInt); - settings.setValue("PTTport",m_pttPort); - settings.setValue("AstroFont",m_astroFont); - settings.setValue("Xpol",m_xpol); - settings.setValue("XpolX",m_xpolx); - settings.setValue("SaveDir",m_saveDir); - settings.setValue("AzElDir",m_azelDir); - settings.setValue("Editor",m_editorCommand); - settings.setValue("DXCCpfx",m_dxccPfx); - settings.setValue("Timeout",m_timeout); - settings.setValue("TxPower",txPower); - settings.setValue("IQamp",iqAmp); - settings.setValue("IQphase",iqPhase); - settings.setValue("ApplyIQcal",m_applyIQcal); - settings.setValue("dPhi",m_dPhi); - settings.setValue("Fcal",m_fCal); - settings.setValue("Fadd",m_fAdd); - - if(dlg.m_restartSoundIn) { + if (dlg.m_restartRequired) + { + m_pendingFs96000 = dlg.m_pendingFs96000; + writeSettings(); + if (m_messages_window) { + m_messages_window->setPSKReportingEnabled(m_spot_to_psk_reporter); + } + return; + } + m_pendingFs96000 = -1; + + // + // Apply runtime effects for SoundIn + // + if (dlg.m_restartSoundIn) + { soundInThread.quit(); soundInThread.wait(1000); + + soundInThread.setInputDevice(m_paInDevice); soundInThread.setNetwork(m_network); - if(m_fs96000) soundInThread.setRate(96000.0); - if(!m_fs96000) soundInThread.setRate(95238.1); soundInThread.setFadd(m_fAdd); - if(!m_xpol) soundInThread.setNrx(1); - if(m_xpol) soundInThread.setNrx(2); - soundInThread.setInputDevice(m_paInDevice); + if (m_fs96000 == 1) soundInThread.setRate(96000.0); + else if (m_fs96000 == 0) soundInThread.setRate(95238.1); + else if (m_fs96000 == 2) soundInThread.setRate(192000.0); + soundInThread.setSwapIQ(m_IQswap); + soundInThread.setScale(m_dB); + soundInThread.setPort(m_udpPort); + soundInThread.setNrx(m_xpol ? 2 : 1); + soundInThread.start(QThread::HighestPriority); } - if(dlg.m_restartSoundOut) { + // + // Apply runtime effects for SoundOut + // + if (dlg.m_restartSoundOut) + { soundOutThread.quitExecution=true; soundOutThread.wait(1000); + soundOutThread.setOutputDevice(m_paOutDevice); -// soundOutThread.start(QThread::HighPriority); + soundOutThread.start(); } + + // + // GUI updates + // + if (m_astro_window && m_astro_window->isVisible()) + m_astro_window->setFontSize(m_astroFont); + + ui->actionFind_Delta_Phi->setEnabled(m_xpol); + + m_messages_window->setColors(m_colors); + m_band_map_window->setColors(m_colors); + + // + // WideGraph updates + // + m_wide_graph_window->m_mult570 = m_mult570; + m_wide_graph_window->m_mult570Tx = m_mult570Tx; + m_wide_graph_window->m_cal570 = m_cal570; + m_wide_graph_window->setFcal(m_fCal); + + // + // Save to disk + // + writeSettings(); + if (m_messages_window) { + m_messages_window->setPSKReportingEnabled(m_spot_to_psk_reporter); + } } } +void MainWindow::onSampleRateChanged(int newRate) +{ + if (!m_wide_graph_window) + return; + + if (newRate == 96000 || newRate == 95238) + m_wide_graph_window->setFreqSpanLimits(60, 90); + else + m_wide_graph_window->setFreqSpanLimits(60, 190); + + m_wide_graph_window->updateSpanFromSpinbox(); +} + + void MainWindow::on_monitorButton_clicked() //Monitor { m_monitoring=true; + qDebug() << "m_monitoring set to" << m_monitoring << "at" << Q_FUNC_INFO; soundInThread.setMonitoring(true); m_diskData=false; + } void MainWindow::on_actionLinrad_triggered() //Linrad palette { @@ -1008,6 +1825,12 @@ void MainWindow::createStatusBar() //createStatusBar lab7->setMinimumSize(QSize(50,10)); lab7->setFrameStyle(QFrame::Panel | QFrame::Sunken); statusBar()->addWidget(lab7); + + lab8 = new QLabel("QSOs: 0"); + lab8->setAlignment(Qt::AlignHCenter); + lab8->setMinimumSize(QSize(50,10)); + lab8->setFrameStyle(QFrame::Panel | QFrame::Sunken); + statusBar()->addWidget(lab8); } void MainWindow::on_tolSpinBox_valueChanged(int i) //tolSpinBox @@ -1023,42 +1846,43 @@ void MainWindow::on_actionExit_triggered() //Exit() close (); } -void MainWindow::closeEvent (QCloseEvent * e) +void MainWindow::closeEvent(QCloseEvent *e) { - if (m_gui_timer) m_gui_timer->stop (); - m_wide_graph_window->saveSettings(); - QFile quitFile(m_appDir + "/.quit"); - quitFile.open(QIODevice::ReadWrite); - QFile lockFile(m_appDir + "/.lock"); - lockFile.remove(); // Allow m65 to terminate - - // close pipes - proc_m65.closeReadChannel (QProcess::StandardOutput); - proc_m65.closeReadChannel (QProcess::StandardError); - - // flush all input - proc_m65.setReadChannel (QProcess::StandardOutput); - proc_m65.readAll (); - proc_m65.setReadChannel (QProcess::StandardError); - proc_m65.readAll (); - - proc_m65.disconnect (); - if (!proc_m65.waitForFinished (1000)) proc_m65.kill(); - quitFile.remove(); - mem_m65.detach(); - if (m_astro_window) m_astro_window->close (); - if (m_band_map_window) m_band_map_window->close (); - if (m_messages_window) { - m_messages_window->setClosingForShutdown(true); - m_messages_window->close(); // Now closeEvent runs fully - } - if (m_wide_graph_window) m_wide_graph_window->close (); - QMainWindow::closeEvent (e); + set_stop_m65(1); + if (m_gui_timer) m_gui_timer->stop(); + m_wide_graph_window->saveSettings(); + + QFile quitFile(m_appDir + "/.quit"); + (void)quitFile.open(QFileDevice::ReadWrite); + setQuitID(quitFile.handle()); + + if (m_astro_window) m_astro_window->close(); + if (m_band_map_window) m_band_map_window->close(); + if (m_messages_window) { + m_messages_window->setClosingForShutdown(true); + m_messages_window->close(); + } + if (m_wide_graph_window) m_wide_graph_window->close(); + +#ifdef __unix__ + ptt_close(); // close persistent Linux serial port +#endif + + if (g_pTxTune) { + g_pTxTune->close(); + delete g_pTxTune; + g_pTxTune = nullptr; + } + + quitFile.remove(); + QMainWindow::closeEvent(e); } + void MainWindow::on_stopButton_clicked() //stopButton { m_monitoring=false; + qDebug() << "m_monitoring set to" << m_monitoring << "at" << Q_FUNC_INFO; soundInThread.setMonitoring(m_monitoring); m_loopall=false; } @@ -1103,6 +1927,16 @@ void MainWindow::on_actionQ65_Sensitivity_in_MAP65_3_0_triggered() QDesktopServices::openUrl (QUrl {"https://wsjt.sourceforge.io/Q65_Sensitivity_in_MAP65.pdf"}); } +void MainWindow::on_actionCopyright_Notice_triggered() +{ + MessageBox::warning_message (this, copyright_notice_text ()); +} + +void MainWindow::on_actionTrademark_Policy_triggered() +{ + QDesktopServices::openUrl (QUrl {"https://wsjtx.github.io/wsjtx/trademark.html"}); +} + void MainWindow::on_actionAstro_Data_triggered() //Display Astro { if (m_astro_window ) m_astro_window->show(); @@ -1126,7 +1960,12 @@ void MainWindow::on_actionMessages_triggered() //Display Messages void MainWindow::on_actionOpen_triggered() //Open File { m_monitoring=false; + qDebug() << "m_monitoring set to" << m_monitoring << "at" << Q_FUNC_INFO; + soundInThread.setMonitoring(m_monitoring); + // Wipe waterfall callsign overlay so stale labels from the previous + // file (or live capture) don't linger over the new decode. + if (m_wide_graph_window) m_wide_graph_window->clearDecodeLabels(); QString fname; if(m_xpol) { fname=QFileDialog::getOpenFileName(this, "Open File", m_path, @@ -1146,15 +1985,26 @@ void MainWindow::on_actionOpen_triggered() //Open File } on_stopButton_clicked(); m_diskData=true; + m_decoderBusy=true; //added 1.6.25 w3sz int dbDgrd=0; if(m_myCall=="K1JT" and m_idInt<0) dbDgrd=m_idInt; - *future1 = QtConcurrent::run(getfile, fname, m_xpol, dbDgrd); + *future1 = QtConcurrent::run([this](QString fname, bool xpol, int dbDgrd) { + this->getfile(fname, xpol, dbDgrd); + }, fname, m_xpol, dbDgrd); + // qDebug() << QDateTime::currentMSecsSinceEpoch() << "MainWindow::on_actionOpen_triggered Reading wav file: " << m_path; watcher1->setFuture(*future1); } } void MainWindow::on_actionOpen_next_in_directory_triggered() //Open Next { + if (m_decoderBusy) { + qDebug() << "Decode is busy; not starting next file yet."; + return; + } + m_decoderBusy = true; + if (m_wide_graph_window) m_wide_graph_window->clearDecodeLabels(); + int i,len; QFileInfo fi(m_path); QStringList list; @@ -1165,22 +2015,25 @@ void MainWindow::on_actionOpen_next_in_directory_triggered() //Open Next } for (i = 0; i < list.size()-1; ++i) { if(i==list.size()-2) m_loopall=false; - len=list.at(i).length(); - if(list.at(i)==m_path.right(len)) { + const QString &entry = list.at(i); + len = entry.length(); + if (entry == m_path.right(len)) { int n=m_path.length(); - QString fname=m_path.replace(n-len,len,list.at(i+1)); + QString fname = m_path; + fname.replace(n - len, len, list.at(i+1)); m_path=fname; - int i; - i=fname.indexOf(".iq") - 11; - if(m_xpol) i=fname.indexOf(".tf2") - 11; - if(i>=0) { + int idx = fname.indexOf(m_xpol ? ".tf2" : ".iq") - 11; + if (idx >= 0) { lab1->setStyleSheet("QLabel{background-color: #66ff66}"); - lab1->setText(" " + fname.mid(i,len) + " "); + lab1->setText(" " + fname.mid(idx, len) + " "); } m_diskData=true; int dbDgrd=0; if(m_myCall=="K1JT" and m_idInt<0) dbDgrd=m_idInt; - *future1 = QtConcurrent::run(getfile, fname, m_xpol, dbDgrd); + *future1 = QtConcurrent::run([this](QString fname, bool xpol, int dbDgrd) { + this->getfile(fname, xpol, dbDgrd); + }, fname, m_xpol, dbDgrd); + qDebug() << "MainWindow::on_actionOpen_next_in_directory_triggered Reading wav file: " << m_path; watcher1->setFuture(*future1); return; } @@ -1198,13 +2051,14 @@ void MainWindow::diskDat() //diskDat() double hsym; //These may be redundant?? m_diskData=true; - datcom_.newdat=1; + setNewdat(1); if(m_wide_graph_window->m_bForceCenterFreq) { - datcom_.fcenter=m_wide_graph_window->m_dForceCenterFreq; + setFcenter(m_wide_graph_window->m_dForceCenterFreq); } - if(m_fs96000) hsym=2048.0*96000.0/11025.0; //Samples per JT65 half-symbol - if(!m_fs96000) hsym=2048.0*95238.1/11025.0; + hsym=2048.0*96000.0/11025.0; //Samples per JT65 half-symbol if SR = 96000 + if(m_fs96000 == 0) hsym=2048.0*95238.1/11025.0; // Samples per JT65 half-symbol if SR = 95238.1 + else if(m_fs96000 == 2) hsym=2048.0*192000.0/11025.0; //Samples per JT65 half-symbol if SR = 192000 for(int i=0; i<304; i++) { // Do the half-symbol FFTs int k = i*hsym + 2048.5; dataSink(k); @@ -1215,6 +2069,7 @@ void MainWindow::diskDat() //diskDat() void MainWindow::diskWriteFinished() //diskWriteFinished { // qDebug() << "diskWriteFinished"; +// decode(); } //Delete ../save/*.tf2 void MainWindow::on_actionDelete_all_tf2_files_in_SaveDir_triggered() @@ -1243,6 +2098,14 @@ void MainWindow::on_actionErase_Band_Map_and_Messages_triggered() { m_band_map_window->setText(""); m_messages_window->setText("",""); + // m_messagesText/m_bandmapText accumulate across decode cycles and are + // only reset when a "!" line arrives (processStdOut). Without clearing + // them here too, the next <EarlyFinished>/<DecodeFinished> redisplay + // (or a cycle with no fresh decodes) repaints the stale pre-erase text + // right back into the windows. + m_messagesText.clear(); + m_bandmapText.clear(); + m_widebandDecode = false; m_map65RxLog |= 4; } @@ -1282,6 +2145,11 @@ void MainWindow::on_actionAggressive_Deep_Search_triggered() //Aggressive DS m_ndepth=2; } +void MainWindow::on_actionFull_Deep_Search_triggered() //Full DS +{ + m_ndepth=3; +} + void MainWindow::on_actionNone_triggered() //Save None { m_saveAll=false; @@ -1314,8 +2182,8 @@ void MainWindow::on_DecodeButton_clicked() //Decode request int n=m_sec0%m_TRperiod; if(m_monitoring and n>47 and (n<52 or m_decoderBusy)) return; if(!m_decoderBusy) { - datcom_.newdat=0; - datcom_.nagain=1; + setNewdat(0); + setNagain(1); decode(); } } @@ -1324,123 +2192,127 @@ void MainWindow::freezeDecode(int n) //freezeDecode() { if(n==2) { ui->tolSpinBox->setValue(5); - datcom_.ntol=m_tol; - datcom_.mousedf=0; + setNtol(m_tol); + setMousedf(0); } else { ui->tolSpinBox->setValue(qMin(3,ui->tolSpinBox->value())); - datcom_.ntol=m_tol; + setNtol(m_tol); } if(!m_decoderBusy) { - datcom_.nagain=1; - datcom_.newdat=0; + setNagain(1); + setNewdat(0); + set_manual_decode_flag(1); decode(); } } void MainWindow::decode() //decode() { + decodeBusy(true); + // Reset decode-finished count for this file + m_decodeFinishedCount = 0; + ui->DecodeButton->setStyleSheet(m_pbdecoding_style1); // QFile f("mockRTfiles.txt"); // if(datcom_.nagain==0 && (!m_diskData) && !f.exists()) { - if(datcom_.nagain==0 && (!m_diskData)) { + if(getNagain()==0 && (!m_diskData)) { qint64 ms = QDateTime::currentMSecsSinceEpoch() % 86400000; int imin=ms/60000; int ihr=imin/60; imin=imin % 60; - datcom_.nutc=100*ihr + imin; + setNutc(100*ihr + imin); } - datcom_.idphi=m_dPhi; - datcom_.mousedf=m_wide_graph_window->DF(); - datcom_.mousefqso=m_wide_graph_window->QSOfreq(); - datcom_.ndepth=m_ndepth; - datcom_.ndiskdat=0; + setIdphi(m_dPhi); + setMousedf(m_wide_graph_window->DF()); + setMousefqso(m_wide_graph_window->QSOfreq()); + setNdepth(m_ndepth); + setNdiskdat(0); if(m_diskData) { - datcom_.ndiskdat=1; - int i0=m_path.indexOf(".tf2"); - if(i0<0) i0=m_path.indexOf(".iq"); - if(i0>0) { - // Compute self Doppler using the filename for Date and Time - int nyear=m_path.mid(i0-11,2).toInt()+2000; - int month=m_path.mid(i0-9,2).toInt(); - int nday=m_path.mid(i0-7,2).toInt(); - int nhr=m_path.mid(i0-4,2).toInt(); - int nmin=m_path.mid(i0-2,2).toInt(); - double uth=nhr + nmin/60.0; - int nfreq=(int)datcom_.fcenter; - int ndop00; - - astrosub00_(&nyear, &month, &nday, &uth, &nfreq, m_myGrid.toLatin1(),&ndop00,6); - datcom_.nfast=ndop00; //Send self Doppler to decoder, via datcom + if(m_myGrid.trimmed().length()>=6) { + setNdiskdat(1); + int i0=m_path.indexOf(".tf2"); + if(i0<0) i0=m_path.indexOf(".iq"); + if(i0>0) { + // Compute self Doppler using the filename for Date and Time + int nyear=m_path.mid(i0-11,2).toInt()+2000; + int month=m_path.mid(i0-9,2).toInt(); + int nday=m_path.mid(i0-7,2).toInt(); + int nhr=m_path.mid(i0-4,2).toInt(); + int nmin=m_path.mid(i0-2,2).toInt(); + double uth=nhr + nmin/60.0; + int nfreq = getFcenter(); + int ndop00; + QByteArray myGridData = m_myGrid.toLatin1(); + astrosub00_(&nyear, &month, &nday, &uth, &nfreq, myGridData.constData(),&ndop00, myGridData.size()); + setNdop00(ndop00); //Send self Doppler to decoder, via datcom + } + } + else { + QMessageBox::information(this,"MAP65","No 6-digit MyGrid recognized by decode()"); + return; } } - datcom_.neme=0; - if(ui->actionOnly_EME_calls->isChecked()) datcom_.neme=1; + setNeme(0); + if(ui->actionOnly_EME_calls->isChecked()) setNeme(1); + + int ispan = int(m_wide_graph_window->fSpan()); + if (ispan % 2 == 1) ispan++; + + double fc = getFcenter(); //MHz + // ifc is fractional kHz of RF center, used to align baseband window with RF dial. + // Must stay in [0, 999]. Changing fcenter semantics will break wideband. + int ifc = int(1000.0*(fc - int(fc)) + 0.5); // fractional kHz of RF center - int ispan=int(m_wide_graph_window->fSpan()); - if(ispan%2 == 1) ispan++; - int ifc=int(1000.0*(datcom_.fcenter - int(datcom_.fcenter))+0.5); int nfa=m_wide_graph_window->nStartFreq(); int nfb=nfa+ispan; int nfshift=nfa + ispan/2 - ifc; - datcom_.nfa=nfa; - datcom_.nfb=nfb; - datcom_.nfcal=m_fCal; - datcom_.nfshift=nfshift; - datcom_.mcall3=0; - if(m_call3Modified) datcom_.mcall3=1; - datcom_.ntimeout=m_timeout; - datcom_.ntol=m_tol; - datcom_.nxant=0; - if(m_xpolx) datcom_.nxant=1; - if(datcom_.nutc < m_nutc0) m_map65RxLog |= 1; //Date and Time to map65_rx.log - m_nutc0=datcom_.nutc; - datcom_.map65RxLog=m_map65RxLog; - datcom_.nfsample=96000; - if(!m_fs96000) datcom_.nfsample=95238; - datcom_.nxpol=0; - if(m_xpol) datcom_.nxpol=1; - datcom_.nmode=10*m_modeQ65 + m_modeJT65; + setNfa(nfa); + setNfb(nfb); + setNfshift(nfshift); + + setNfcal(m_fCal); + setMcall3(0); + if(m_call3Modified) setMcall3(1); + setNtimeout(m_timeout); + setNtol(m_tol); + setNxant(0); + if(m_xpolx) setNxant(1); + if(getNutc() < m_nutc0) m_map65RxLog |= 1; //Date and Time to map65_rx.log + m_nutc0=getNutc(); + setMap65RxLog(m_map65RxLog); + if(m_fs96000 == 1) setNfsample(96000); + if(m_fs96000 == 0) setNfsample(95238); + else if(m_fs96000 == 2) setNfsample(192000); + // qDebug() << "MainWindow::decode setting nfsample to " << m_fs96000; + setNxpol(0); + if(m_xpol) setNxpol(1); + setNmode(10*m_modeQ65 + m_modeJT65); // datcom_.nfast=1; //No longer used - datcom_.nsave=m_nsave; - datcom_.max_drift=ui->sbMaxDrift->value(); - - QString mcall=(m_myCall+" ").mid(0,12); - QString mgrid=(m_myGrid+" ").mid(0,6); - QString hcall=(ui->dxCallEntry->text()+" ").mid(0,12); - QString hgrid=(ui->dxGridEntry->text()+" ").mid(0,6); - - memcpy(datcom_.mycall, mcall.toLatin1(), 12); - memcpy(datcom_.mygrid, mgrid.toLatin1(), 6); - memcpy(datcom_.hiscall, hcall.toLatin1(), 12); - memcpy(datcom_.hisgrid, hgrid.toLatin1(), 6); - memcpy(datcom_.datetime, m_dateTime.toLatin1(), 17); - datcom_.junk1=1234; - datcom_.junk2=5678; - - //newdat=1 ==> this is new data, must do the big FFT - //nagain=1 ==> decode only at fQSO +/- Tol - - char *to = (char*)mem_m65.data(); - char *from = (char*) datcom_.d4; - int size=sizeof(datcom_); - if(datcom_.newdat==0) { - int noffset = 4*4*5760000 + 4*4*322*32768 + 4*4*32768; - to += noffset; - from += noffset; - size -= noffset; - } - memcpy(to, from, qMin(mem_m65.size(), size-8)); - datcom_.nagain=0; - datcom_.ndiskdat=0; + setNsave(m_nsave); + setMaxDrift(ui->sbMaxDrift->value()); + +QString mcall = (m_myCall + " ").mid(0, 12); +QString mgrid = (m_myGrid + " ").mid(0, 6); +QString hcall = (ui->dxCallEntry->text() + " ").mid(0, 12); +QString hgrid = (ui->dxGridEntry->text() + " ").mid(0, 6); + + setMyCall(mcall); + setMyGrid(mgrid); + setHisCall(hcall); + setHisGrid(hgrid); + setDatetime(m_dateTime); + setNewdat(1); + setJunk1(1234); + setJunk2(5678); + + if (!m_diskData) setNdiskdat(0); //added 12-30-25 to agree with legacy + publish_decode_request(); m_map65RxLog=0; m_call3Modified=false; - - QFile lockFile(m_appDir + "/.lock"); // Allow m65 to start - lockFile.remove(); - decodeBusy(true); +// qDebug() << QDateTime::currentMSecsSinceEpoch() << "finished MainWindow::decode()"; } bool MainWindow::subProcessFailed (QProcess * process, int exit_code, QProcess::ExitStatus status) @@ -1453,6 +2325,7 @@ bool MainWindow::subProcessFailed (QProcess * process, int exit_code, QProcess:: if (argument.contains (' ')) argument = '"' + argument + '"'; arguments << argument; } + writeCrashData(); MessageBox::critical_message (this, tr ("Subprocess Error") , tr ("Subprocess failed with exit code %1") .arg (exit_code) @@ -1464,89 +2337,54 @@ bool MainWindow::subProcessFailed (QProcess * process, int exit_code, QProcess:: return false; } -void MainWindow::m65_error (QProcess::ProcessError) -{ - msgBox("Error starting or running\n" + m_appDir + "/m65 -s\n\n" - + proc_m65.errorString ()); - QTimer::singleShot (0, this, SLOT (close ())); -} +void MainWindow::writeCrashData() { + QFile file("crash_data.txt"); -void MainWindow::editor_error() //editor_error -{ - msgBox("Error starting or running\n" + m_appDir + "/" + m_editorCommand); -} + if (file.open(QIODevice::Append | QIODevice::Text)) { + QTextStream out(&file); -void MainWindow::readFromStdout() //readFromStdout -{ - while(proc_m65.canReadLine()) - { - QByteArray t=proc_m65.readLine(); - if(t.indexOf("<QuickDecodeDone>") >= 0) { - m_nsum=t.mid(17,4).toInt(); - m_nsave=t.mid(21,4).toInt(); - lab7->setText (QString {"Avg: %1"}.arg (m_nsum)); - if(m_modeQ65>0) m_wide_graph_window->setDecodeFinished(); - } + out << "---- Crash Data Dump ----\n"; - if((t.indexOf("<EarlyFinished>") >= 0) or (t.indexOf("<DecodeFinished>") >= 0)) { - if(m_widebandDecode) { - m_messages_window->setText(m_messagesText,m_bandmapText); - m_band_map_window->setText(m_bandmapText); - m_widebandDecode=false; - } - QFile lockFile(m_appDir + "/.lock"); - lockFile.open(QIODevice::ReadWrite); - if(t.indexOf("<DecodeFinished>") >= 0) { - int ndecodes=t.mid(40,5).toInt(); - lab5->setText(QString::number(ndecodes)); - m_map65RxLog=0; - m_startAnother=m_loopall; - } - ui->DecodeButton->setStyleSheet(""); - decodeBusy(false); - return; - } + out << "fcenter: " << getFcenter() << "\n"; - read_log(); + out << "nutc: " << getNutc() << ", idphi: " << getIdphi() + << ", mousedf: " << getMousedf() << ", mousefqso: " << getMousefqso() + << ", nagain: " << getNagain() << ", ndepth: " << getNdepth() << "\n"; - if(t.indexOf("!") >= 0) { - int n=t.length(); - int m=2; -#ifdef WIN32 - m=3; -#endif - if(n>=30 or t.indexOf("Best-fit")>=0) ui->decodedTextBrowser->append(t.mid(1,n-m)); - n=ui->decodedTextBrowser->verticalScrollBar()->maximum(); - ui->decodedTextBrowser->verticalScrollBar()->setValue(n); - m_messagesText=""; - m_bandmapText=""; - } + out << "ndiskdat: " << getNdiskdat() << ", neme: " << getNeme() + << ", newdat: " << getNewdat() << ", nfa: " << getNfa() + << ", nfb: " << getNfb() << ", nfcal: " << getNfcal() + << ", nfshift: " << getNfshift() << "\n"; - if(t.indexOf("@") >= 0) { - m_messagesText += t.mid(1); - m_widebandDecode=true; - } + out << "mcall3: " << getMcall3() << ", ntimeout: " << getNtimeout() + << ", ntol: " << getNtol() << ", nxant: " << getNxant() + << ", map65RxLog: " << getMap65RxLog() << ", nfsample: " << getNfsample() << "\n"; - if(t.indexOf("&") >= 0) { - QString q(t); - QString callsign=q.mid(5); - callsign=callsign.mid(0,callsign.indexOf(" ")); - if(callsign.length()>2) { - if(m_worked[callsign]) { - q=q.mid(1,4) + " " + q.mid(5); - } else { - q=q.mid(1,4) + " *" + q.mid(5); - } - m_bandmapText += q; - } - } - if(t.indexOf("=") >= 0) { - int n=t.size(); - qDebug() << t.mid(1,n-3).trimmed(); - } + out << "nxpol: " << getNxpol() << ", nmode: " << getNmode() + << ", nsave: " << getNsave() + << ", max_drift: " << getMaxDrift() << ", nhsym: " << getNhsym() << "\n"; + + out << "junk1: " << getJunk1() << ", junk2: " << getJunk2() << "\n"; + + out << "mycall: " << getMyCall() << "\n"; + out << "hiscall: " << getHisCall() << "\n"; + out << "mygrid: " << getMyGrid() << "\n"; + out << "hisgrid: " << getHisGrid() << "\n"; + out << "datetime: " << getDatetime() << "\n"; + + out << "--------------------------\n"; + + file.close(); + } else { + qWarning("Could not open crash_data.txt for writing."); } } +void MainWindow::editor_error() //editor_error +{ + msgBox("Error starting or running\n" + m_appDir + "/" + m_editorCommand); +} + void MainWindow::on_EraseButton_clicked() { qint64 ms=QDateTime::currentMSecsSinceEpoch(); @@ -1560,6 +2398,7 @@ void MainWindow::on_EraseButton_clicked() void MainWindow::decodeBusy(bool b) //decodeBusy() { +// qDebug() << QDateTime::currentMSecsSinceEpoch() << "decodeBusy(" << b << ")"; m_decoderBusy=b; ui->DecodeButton->setEnabled(!b); ui->actionOpen->setEnabled(!b); @@ -1598,32 +2437,43 @@ void MainWindow::guiUpdate() if(bTune0 and !bTune) { btxok=false; m_monitoring=bMonitoring0; + // qDebug() << "m_monitoring set to" << m_monitoring << "at" << Q_FUNC_INFO; + soundInThread.setMonitoring(m_monitoring); } if(bTune and !bTune0) bMonitoring0=m_monitoring; bTune0=bTune; if(m_auto or bTune) { - if((bTxTime or bTune) and iptt==0 and !m_txMute) { - int itx=1; - int ierr = ptt_(&m_pttPort,&itx,&iptt); // Raise PTT - if(ierr != 0) { - on_stopTxButton_clicked(); - char s[18]; - sprintf(s,"Cannot open COM%d",m_pttPort); - msgBox(s); + if ((bTxTime or bTune) && iptt == 0 && !m_txMute) { + + if (m_pttPath != "NONE") { + int itx = 1; + int nport = m_pttPortNumber; // the real COM port number + int ierr = ptt_(&nport, &itx, &iptt); + + if (ierr != 0) { + if (!m_pttErrorShown) { + char s[256]; + snprintf(s, sizeof(s), "Cannot open Port: %s", + m_pttPath.toUtf8().constData()); + msgBox(s); + m_pttErrorShown = true; + } + on_stopTxButton_clicked(); } + } - if(m_bIQxt) m_wide_graph_window->tx570(); // Set Si570 to Tx Freq + if (m_bIQxt) + m_wide_graph_window->tx570(); - if(!soundOutThread.isRunning()) { + if (!soundOutThread.isRunning()) soundOutThread.start(QThread::HighPriority); } - } - if((!bTxTime and !bTune) or m_txMute) { + + if ((!bTxTime && !bTune) || m_txMute) btxok=false; } - } // Calculate Tx waveform when needed if((iptt==1 && iptt0==0) || m_restart) { @@ -1641,7 +2491,7 @@ void MainWindow::guiUpdate() int mode65=m_mode65; int ntxFreq=1000; double samfac=1.0; - + // qDebug() << mode65 << samfac; if(m_modeTx=="JT65") { gen65_(message,&mode65,&samfac,&nsendingsh,msgsent,iwave, &nwave,len1,len1); @@ -1656,7 +2506,7 @@ void MainWindow::guiUpdate() QString t=" Tx " + m_modeTx + " "; t=t.left(11); QFile f("map65_tx.log"); - f.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append); + qDebug() << "MainWindow::guiUpdate 1 File open result:" << f.open(QFileDevice::WriteOnly | QFileDevice::Text | QFileDevice::Append); QTextStream out(&f); out << QDateTime::currentDateTimeUtc().toString("yyyy-MMM-dd hh:mm") << t << QString::fromLatin1(msgsent) @@ -1679,6 +2529,8 @@ void MainWindow::guiUpdate() xSignalMeter->setValue(0); ySignalMeter->setValue(0); m_monitoring=false; + // qDebug() << "m_monitoring set to" << m_monitoring << "at" << Q_FUNC_INFO; + soundInThread.setMonitoring(false); btxok=true; m_transmitting=true; @@ -1687,7 +2539,7 @@ void MainWindow::guiUpdate() QString t=" Tx " + m_modeTx + " "; t=t.left(11); QFile f("map65_tx.log"); - f.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append); + qDebug() << "MainWindow::guiUpdate 2 File open result:" << f.open(QFileDevice::WriteOnly | QFileDevice::Text | QFileDevice::Append); QTextStream out(&f); out << QDateTime::currentDateTimeUtc().toString("yyyy-MMM-dd hh:mm") << t << QString::fromLatin1(msgsent) @@ -1706,8 +2558,11 @@ void MainWindow::guiUpdate() if(nc0 <= 0) nc0++; if(nc0 == 0) { if(m_bIQxt) m_wide_graph_window->rx570(); // Set Si570 back to Rx Freq - int itx=0; - ptt_(&m_pttPort,&itx,&iptt); // Lower PTT + int itx = 0; + int nport = m_pttPortNumber; // the real COM port number + ptt_(&nport, &itx, &iptt); // Lower PTT + m_pttErrorShown = false; + if(!m_txMute) { soundOutThread.quitExecution=true;\ } @@ -1715,6 +2570,8 @@ void MainWindow::guiUpdate() m_wide_graph_window->enableSetRxHardware(true); if(m_auto) { m_monitoring=true; + // qDebug() << "m_monitoring set to" << m_monitoring << "at" << Q_FUNC_INFO; + soundInThread.setMonitoring(m_monitoring); } } @@ -1735,10 +2592,6 @@ void MainWindow::guiUpdate() m_wide_graph_window->updateFreqLabel(); - if(m_startAnother) { - m_startAnother=false; - on_actionOpen_next_in_directory_triggered(); - } if(m_modeQ65==0 and m_modeTx=="Q65") on_pbTxMode_clicked(); if(m_modeJT65==0 and m_modeTx=="JT65") on_pbTxMode_clicked(); @@ -1762,7 +2615,7 @@ void MainWindow::guiUpdate() lab1->setStyleSheet("QLabel{background-color: #ffff33}"); } char s[37]; - sprintf(s,"Tx: %s",msgsent); + snprintf(s, sizeof(s), "Tx: %.32s", msgsent); lab1->setText(s); } else if(m_monitoring) { lab1->setStyleSheet("QLabel{background-color: #00ff00}"); @@ -2001,11 +2854,16 @@ void MainWindow::genStdMsgs(QString rpt) //genStdMsgs() ui->txrb1->setChecked(true); } +QString MainWindow::call3Path() const +{ + return ensureMap65RuntimeFile(m_appDir, m_installedDataDir, m_dataDir, "CALL3.TXT"); +} + void MainWindow::lookup() //lookup() { QString hiscall=ui->dxCallEntry->text().toUpper().trimmed(); ui->dxCallEntry->setText(hiscall); - QString call3File = m_appDir + "/CALL3.TXT"; + QString call3File = call3Path(); QFile f(call3File); if(!f.open(QIODevice::ReadOnly | QIODevice::Text)) { msgBox("Cannot open " + call3File); @@ -2060,7 +2918,7 @@ void MainWindow::on_addButton_clicked() //Add button } else { newEntry += ",,,"; } - QString call3File = m_appDir + "/CALL3.TXT"; + QString call3File = call3Path(); QFile f1(call3File); if(!f1.open(QIODevice::ReadWrite | QIODevice::Text)) { msgBox("Cannot open " + call3File); @@ -2079,7 +2937,7 @@ void MainWindow::on_addButton_clicked() //Add button f1.seek (0); } - QString tmpFile = m_appDir + "/CALL3.TMP"; + QString tmpFile = QDir {m_dataDir}.absoluteFilePath("CALL3.TMP"); QFile f2(tmpFile); if(!f2.open(QIODevice::ReadWrite | QIODevice::Truncate | QIODevice::Text)) { msgBox("Cannot open " + tmpFile); @@ -2122,12 +2980,12 @@ void MainWindow::on_addButton_clicked() //Add button } if(m_call3Modified) { - auto const& old_path = m_appDir + "/CALL3.OLD"; + auto const& old_path = QDir {m_dataDir}.absoluteFilePath("CALL3.OLD"); QFile f0 {old_path}; if (f0.exists ()) f0.remove (); f1.copy (old_path); // copying as we want to preserve // symlinks - f1.open (QFile::WriteOnly | QFile::Text); // truncates + qDebug() << "MainWindow::on_addButton_clicked File open result:" << f1.open (QFileDevice::WriteOnly | QFileDevice::Text); // truncates f2.seek (0); f1.write (f2.readAll ()); // copy contents f2.remove (); @@ -2240,7 +3098,7 @@ void MainWindow::on_genStdMsgsPushButton_clicked() //genStdMsgs button void MainWindow::on_logQSOButton_clicked() //Log QSO button { - int nMHz=int(datcom_.fcenter); + int nMHz=getFcenter(); QDateTime t = QDateTime::currentDateTimeUtc(); QString qsoMode=lab5->text(); if(m_modeTx.startsWith("Q65")) qsoMode=lab6->text(); @@ -2301,7 +3159,6 @@ void MainWindow::on_actionJT65A_triggered() m_mode="JT65A"; m_modeJT65=1; m_mode65=1; - m_modeJT65=1; m_TRperiod=60; soundInThread.setPeriod(m_TRperiod); soundOutThread.setPeriod(m_TRperiod); @@ -2317,7 +3174,6 @@ void MainWindow::on_actionJT65B_triggered() m_mode="JT65B"; m_modeJT65=2; m_mode65=2; - m_modeJT65=2; m_TRperiod=60; soundInThread.setPeriod(m_TRperiod); soundOutThread.setPeriod(m_TRperiod); @@ -2420,8 +3276,11 @@ void MainWindow::on_actionEdit_wsjt_log_triggered() void MainWindow::on_actionTx_Tune_triggered() { - if(g_pTxTune==NULL) { + if (!g_pTxTune) { g_pTxTune = new TxTune(0); + + if (!g_TxTuneGeometry.isEmpty()) + g_pTxTune->restoreGeometry(g_TxTuneGeometry); } g_pTxTune->set_iqAmp(iqAmp); g_pTxTune->set_iqPhase(iqPhase); @@ -2457,7 +3316,7 @@ void MainWindow::read_log() // Update "m_worked" by reading wsjtx.log m_worked.clear(); //Start from scratch QFile f("wsjtx.log"); - f.open(QIODevice::ReadOnly); + qDebug() << "MainWindow::read_log File open result:" << f.open(QFileDevice::ReadOnly); if(f.isOpen()) { QTextStream in(&f); QString line,callsign; @@ -2472,3 +3331,8 @@ void MainWindow::read_log() f.close(); } } + +void pa_deinit() +{ + Pa_Terminate(); +} diff --git a/map65/mainwindow.h b/map65/mainwindow.h index 97d73b03..0262e0ac 100644 --- a/map65/mainwindow.h +++ b/map65/mainwindow.h @@ -8,17 +8,20 @@ #include <QDateTime> #include <QHash> #include <QProcess> -#include "getfile.h" #include "soundin.h" #include "soundout.h" #include "signalmeter.h" #include "commons.h" +#include "map65_decode_display_filter.h" #include "sleep.h" #include <QtConcurrent/QtConcurrent> +#include <QByteArray> -#define NFFT 32768 #define NSMAX 5760000 + +struct StdoutChannel; + //--------------------------------------------------------------- MainWindow namespace Ui { class MainWindow; @@ -29,6 +32,7 @@ class Astro; class BandMap; class Messages; class WideGraph; +extern QByteArray g_TxTuneGeometry; class MainWindow : public QMainWindow { @@ -37,7 +41,69 @@ class MainWindow : public QMainWindow public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); + + +private: + Ui::MainWindow *ui; + + struct DecoderContext; + DecoderContext* decoderCtx; + +public: + float* getDd() const; + std::thread stdoutReaderThread; + std::atomic<bool> stdoutReaderStop {false}; + void writeSettings(); + bool m_network; + int m_pttPortNumber = 0; + + QString m_pttPath; + QString m_appDir; + QString m_installedDataDir; + QString m_dataDir; + QString m_eclipseFile; + QString m_settings_filename; + qint32 m_nDevIn; + qint32 m_nDevOut; + qint32 m_idInt; + qint32 m_astroFont; + qint32 m_timeout; + qint32 m_dPhi; + qint32 m_fCal; + qint32 m_paInDevice; + qint32 m_paOutDevice; + qint32 m_udpPort; + qint32 m_NBslider; + qint32 m_mult570; + qint32 m_mult570Tx; + qint32 m_dB; + + double m_fAdd; + // double m_IQamp; + // double m_IQphase; + double m_cal570; + double m_TxOffset; + + bool m_xpol; + bool m_xpolx; + int m_fs96000; + int m_pendingFs96000 {-1}; + bool m_IQswap; + bool m_initIQplus; + bool m_bIQxt; + bool m_w3szUrl; + bool m_spot_to_psk_reporter; + bool m_psk_reporter_tcpip; + + QString m_myCall; + QString m_myGrid; + QString m_saveDir; + QString m_azelDir; + QString m_dxccPfx; + QString m_colors; + QString m_editorCommand; + QString m_otherUrl; public slots: void showSoundInError(const QString& errorMsg); @@ -46,19 +112,15 @@ public slots: void diskDat(); void diskWriteFinished(); void freezeDecode(int n); - void readFromStdout(); - void m65_error (QProcess::ProcessError); void editor_error(); void guiUpdate(); void doubleClickOnCall(QString hiscall, bool ctrl); void doubleClickOnMessages(QString hiscall, QString t2, bool ctrl); - -private: - virtual void keyPressEvent (QKeyEvent *) override; - virtual bool eventFilter (QObject *, QEvent *) override; - virtual void closeEvent (QCloseEvent *) override; - + void startDecoder(); + private slots: + void onDiskDecodeFinished(); + void onRunM65Finished(); void on_tx1_editingFinished(); void on_tx2_editingFinished(); void on_tx3_editingFinished(); @@ -81,6 +143,8 @@ private slots: void on_actionQSG_Q65_triggered(); void on_actionQSG_MAP65_v3_triggered(); void on_actionQ65_Sensitivity_in_MAP65_3_0_triggered(); + void on_actionCopyright_Notice_triggered(); + void on_actionTrademark_Policy_triggered(); void on_actionWide_Waterfall_triggered(); void on_actionBand_Map_triggered(); void on_actionMessages_triggered(); @@ -96,6 +160,7 @@ private slots: void on_actionNo_Deep_Search_triggered(); void on_actionNormal_Deep_Search_triggered(); void on_actionAggressive_Deep_Search_triggered(); + void on_actionFull_Deep_Search_triggered(); void on_actionNone_triggered(); void on_actionSave_all_triggered(); void on_actionKeyboard_shortcuts_triggered(); @@ -143,34 +208,26 @@ private slots: void on_actionQ65C_triggered(); void on_actionQ65D_triggered(); void on_actionQ65E_triggered(); - void on_pbTxMode_clicked(); + void onSampleRateChanged(int newRate); private: - Ui::MainWindow *ui; - QString m_appDir; - QString m_settings_filename; + QString call3Path() const; + virtual void keyPressEvent (QKeyEvent *) override; + virtual bool eventFilter (QObject *, QEvent *) override; + virtual void closeEvent (QCloseEvent *) override; + QScopedPointer<Astro> m_astro_window; QScopedPointer<BandMap> m_band_map_window; QPointer<Messages> m_messages_window; - void createMessagesWindow(); - //QScopedPointer<Messages> m_messages_window; QScopedPointer<WideGraph> m_wide_graph_window; QPointer<QTimer> m_gui_timer; qint64 m_msErase; - qint32 m_nDevIn; - qint32 m_nDevOut; - qint32 m_idInt; qint32 m_waterfallAvg; qint32 m_DF; qint32 m_tol; qint32 m_QSOfreq0; qint32 m_ntx; - qint32 m_pttPort; - qint32 m_astroFont; - qint32 m_timeout; - qint32 m_dPhi; - qint32 m_fCal; qint32 m_txFreq; qint32 m_setftx; qint32 m_ndepth; @@ -180,27 +237,15 @@ private: qint32 m_mode65; qint32 m_nrx; qint32 m_hsym0; - qint32 m_paInDevice; - qint32 m_paOutDevice; - qint32 m_udpPort; - qint32 m_NBslider; qint32 m_adjustIQ; qint32 m_applyIQcal; - qint32 m_mult570; - qint32 m_mult570Tx; qint32 m_nsum; qint32 m_nsave; qint32 m_TRperiod; qint32 m_modeJT65; qint32 m_modeQ65; qint32 m_RxState; - qint32 m_dB; - double m_fAdd; - // double m_IQamp; - // double m_IQphase; - double m_cal570; - double m_TxOffset; double m_xavg; bool m_monitoring; @@ -212,28 +257,41 @@ private: bool m_auto; bool m_txMute; bool m_restart; - bool m_xpol; - bool m_xpolx; bool m_call3Modified; - bool m_startAnother; bool m_saveAll; bool m_onlyEME; bool m_widebandDecode; bool m_kb8rq; bool m_NB; - bool m_fs96000; - bool m_IQswap; - bool m_initIQplus; - bool m_bIQxt; + bool m_pttErrorShown = false; + QString m_path; + QString m_pbdecoding_style1; + QString m_pbmonitor_style; + QString m_pbAutoOn_style; + QString m_messagesText; + QString m_bandmapText; + Map65DecodeDisplayFilter m_decodeDisplayFilter; + QString m_hisCall; + QString m_hisGrid; + QString m_palette; + QString m_dateTime; + QString m_mode; + QString m_modeTx; + float m_gainx; float m_gainy; float m_phasex; float m_phasey; float m_pctZap; - QRect m_wideGraphGeom; + int ddSize = 0; + // --- Minute-boundary tracking for symspec --- + int ntr0 = -1; // previous ntr value (seconds into TR period) + int m_TRperiod0 = 0; // previous TR period (usually 60) + int nhsym0 = 0; // ihsym at start of minute (reset when newmin=1) + QLabel* lab1; // labels in status bar QLabel* lab2; QLabel* lab3; @@ -241,6 +299,7 @@ private: QLabel* lab5; QLabel* lab6; QLabel* lab7; + QLabel* lab8; QMessageBox msgBox0; @@ -253,39 +312,27 @@ private: QProcess proc_qthid; QProcess proc_editor; - - QString m_path; - QString m_pbdecoding_style1; - QString m_pbmonitor_style; - QString m_pbAutoOn_style; - QString m_messagesText; - QString m_bandmapText; - QString m_myCall; - QString m_myGrid; - QString m_hisCall; - QString m_hisGrid; - QString m_saveDir; - QString m_azelDir; - QString m_dxccPfx; - QString m_palette; - QString m_dateTime; - QString m_mode; - QString m_colors; - QString m_editorCommand; - QString m_modeTx; + double fcenter = 0.0; + char mycall[12] = {}; + char mygrid[6] = {}; + char hiscall[12] = {}; + char hisgrid[6] = {}; + char datetime[17] = {}; QHash<QString,bool> m_worked; SignalMeter *xSignalMeter; SignalMeter *ySignalMeter; - SoundInThread soundInThread; //Instantiate the audio threads SoundOutThread soundOutThread; + QTimer* m_decodeIdleTimer = nullptr; + int m_decodeIdleTimeoutMs = 2500; // tweak 150–300 as needed + int m_decodeFinishedCount = 0; + //---------------------------------------------------- private functions void readSettings(); - void writeSettings(); void createStatusBar(); void updateStatusBar(); void msgBox(QString t); @@ -297,11 +344,18 @@ private: bool isGrid4(QString g); bool subProcessFailed (QProcess *, int exit_code, QProcess::ExitStatus); void read_log(); + void writeCrashData(); + void savetf2(QString fname, bool xpol); + void getfile(QString fname, bool m_xpol, int dbDgrd); + void processStdOut(QString text); + void startSharedMemoryStdoutReader(DecoderContext* ctx); + void createMessagesWindow(); }; -extern void getfile(QString fname, bool xpol, int idInt); -extern void savetf2(QString fname, bool xpol); -extern int killbyname(const char* progName); +extern int g_sampleRate; +extern int active_nfft; +extern std::vector<qint16> id; + extern void getDev(int* numDevices,char hostAPI_DeviceName[][50], int minChan[], int maxChan[], int minSpeed[], int maxSpeed[]); @@ -309,7 +363,7 @@ extern void getDev(int* numDevices,char hostAPI_DeviceName[][50], extern "C" { //----------------------------------------------------- C and Fortran routines void symspec_(int* k, int* nxpol, int* ndiskdat, int* nb, - int* m_NBslider, int* idphi, int* nfsample, float* fgreen, + int* m_NBslider, int* idphi, int* iqadjust, int* iqapply, float* gainx, float* gainy, float* phasex, float* phasey, float* rejectx, float* rejecty, float* px, float* py, float s[], int* nkhz, int* nhsym, diff --git a/map65/mainwindow.ui b/map65/mainwindow.ui index 5501f78b..fb09f4e1 100644 --- a/map65/mainwindow.ui +++ b/map65/mainwindow.ui @@ -6,8 +6,8 @@ <rect> <x>0</x> <y>0</y> - <width>635</width> - <height>560</height> + <width>900</width> + <height>600</height> </rect> </property> <property name="sizePolicy"> @@ -37,19 +37,19 @@ <widget class="QWidget" name="centralWidget"> <layout class="QVBoxLayout" name="verticalLayout_8"> <item> - <layout class="QVBoxLayout" name="verticalLayout_7"> + <layout class="QVBoxLayout" name="verticalLayout_7" stretch="5,0,0"> <item> <widget class="QGroupBox" name="groupBox"> <property name="sizePolicy"> - <sizepolicy hsizetype="Preferred" vsizetype="Expanding"> + <sizepolicy hsizetype="Expanding" vsizetype="Expanding"> <horstretch>0</horstretch> - <verstretch>0</verstretch> + <verstretch>1</verstretch> </sizepolicy> </property> <property name="minimumSize"> <size> - <width>453</width> - <height>170</height> + <width>0</width> + <height>0</height> </size> </property> <property name="maximumSize"> @@ -73,13 +73,13 @@ <property name="sizePolicy"> <sizepolicy hsizetype="Expanding" vsizetype="Expanding"> <horstretch>0</horstretch> - <verstretch>0</verstretch> + <verstretch>1</verstretch> </sizepolicy> </property> <property name="minimumSize"> <size> - <width>421</width> - <height>100</height> + <width>0</width> + <height>0</height> </size> </property> <property name="maximumSize"> @@ -102,10 +102,9 @@ </property> <property name="html"> <string><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><meta charset="utf-8" /><style type="text/css"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } -hr { height: 1px; border-width: 0; } -</style></head><body style=" font-family:'Consolas'; font-size:10pt; font-weight:400; font-style:normal;"> +</style></head><body style=" font-family:'Consolas','Consolas'; font-size:10pt; font-weight:400; font-style:normal;"> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Courier New';"><br /></p></body></html></string> </property> <property name="acceptRichText"> @@ -559,7 +558,7 @@ hr { height: 1px; border-width: 0; } <property name="sizeHint" stdset="0"> <size> <width>20</width> - <height>40</height> + <height>20</height> </size> </property> </spacer> @@ -609,7 +608,7 @@ hr { height: 1px; border-width: 0; } <property name="sizeHint" stdset="0"> <size> <width>20</width> - <height>40</height> + <height>20</height> </size> </property> </spacer> @@ -645,7 +644,7 @@ hr { height: 1px; border-width: 0; } <property name="sizeHint" stdset="0"> <size> <width>20</width> - <height>20</height> + <height>15</height> </size> </property> </spacer> @@ -737,7 +736,7 @@ hr { height: 1px; border-width: 0; } <property name="sizeHint" stdset="0"> <size> <width>20</width> - <height>20</height> + <height>15</height> </size> </property> </spacer> @@ -1289,8 +1288,8 @@ hr { height: 1px; border-width: 0; } <rect> <x>0</x> <y>0</y> - <width>635</width> - <height>17</height> + <width>900</width> + <height>23</height> </rect> </property> <widget class="QMenu" name="menuFile"> @@ -1336,12 +1335,42 @@ hr { height: 1px; border-width: 0; } <addaction name="actionLinrad"/> <addaction name="actionCuteSDR"/> </widget> + <widget class="QMenu" name="menuCallsign_transparency"> + <property name="title"> + <string>Callsign transparency</string> + </property> + <addaction name="actionTransparency_None"/> + <addaction name="actionTransparency_Low"/> + <addaction name="actionTransparency_Medium"/> + <addaction name="actionTransparency_High"/> + </widget> + <widget class="QMenu" name="menuCallsign_font"> + <property name="title"> + <string>Callsign font size</string> + </property> + <addaction name="actionCallsign_font_small"/> + <addaction name="actionCallsign_font_normal"/> + <addaction name="actionCallsign_font_medium"/> + <addaction name="actionCallsign_font_large"/> + </widget> + <widget class="QMenu" name="menuCallsign_position"> + <property name="title"> + <string>Callsign position</string> + </property> + <addaction name="actionCallsign_position_top"/> + <addaction name="actionCallsign_position_bottom"/> + </widget> <addaction name="actionAstro_Data"/> <addaction name="actionBand_Map"/> <addaction name="actionMessages"/> <addaction name="actionWide_Waterfall"/> <addaction name="separator"/> <addaction name="menuWaterfall_palette"/> + <addaction name="separator"/> + <addaction name="actionShow_callsigns_on_Waterfall"/> + <addaction name="menuCallsign_transparency"/> + <addaction name="menuCallsign_font"/> + <addaction name="menuCallsign_position"/> </widget> <widget class="QMenu" name="menuDecode"> <property name="title"> @@ -1353,6 +1382,7 @@ hr { height: 1px; border-width: 0; } <addaction name="actionNo_Deep_Search"/> <addaction name="actionNormal_Deep_Search"/> <addaction name="actionAggressive_Deep_Search"/> + <addaction name="actionFull_Deep_Search"/> <addaction name="separator"/> </widget> <widget class="QMenu" name="menuSave"> @@ -1374,6 +1404,10 @@ hr { height: 1px; border-width: 0; } <addaction name="actionKeyboard_shortcuts"/> <addaction name="actionSpecial_mouse_commands"/> <addaction name="actionAvailable_suffixes_and_add_on_prefixes"/> + <addaction name="separator"/> + <addaction name="actionCopyright_Notice"/> + <addaction name="actionTrademark_Policy"/> + <addaction name="separator"/> <addaction name="actionAbout"/> </widget> <widget class="QMenu" name="menuMode"> @@ -1424,12 +1458,22 @@ hr { height: 1px; border-width: 0; } </action> <action name="actionAbout"> <property name="text"> - <string>About MAP65</string> + <string>About MAP65â„¢</string> </property> <property name="shortcut"> <string>Ctrl+F1</string> </property> </action> + <action name="actionCopyright_Notice"> + <property name="text"> + <string>Copyright notice</string> + </property> + </action> + <action name="actionTrademark_Policy"> + <property name="text"> + <string>Trademark policy</string> + </property> + </action> <action name="actionAstro_Data"> <property name="text"> <string>Astro Data</string> @@ -1453,6 +1497,106 @@ hr { height: 1px; border-width: 0; } <string>Wide Waterfall</string> </property> </action> + <action name="actionShow_callsigns_on_Waterfall"> + <property name="checkable"> + <bool>true</bool> + </property> + <property name="checked"> + <bool>true</bool> + </property> + <property name="text"> + <string>Show callsigns on Waterfall</string> + </property> + <property name="toolTip"> + <string>Toggle the decoded-callsign overlay on the wide waterfall. Default ON. Persists across launches.</string> + </property> + </action> + <action name="actionTransparency_None"> + <property name="checkable"> + <bool>true</bool> + </property> + <property name="checked"> + <bool>true</bool> + </property> + <property name="text"> + <string>None</string> + </property> + </action> + <action name="actionTransparency_Low"> + <property name="checkable"> + <bool>true</bool> + </property> + <property name="text"> + <string>Low</string> + </property> + </action> + <action name="actionTransparency_Medium"> + <property name="checkable"> + <bool>true</bool> + </property> + <property name="text"> + <string>Medium</string> + </property> + </action> + <action name="actionTransparency_High"> + <property name="checkable"> + <bool>true</bool> + </property> + <property name="text"> + <string>High</string> + </property> + </action> + <action name="actionCallsign_font_small"> + <property name="checkable"> + <bool>true</bool> + </property> + <property name="text"> + <string>Small (7 pt)</string> + </property> + </action> + <action name="actionCallsign_font_normal"> + <property name="checkable"> + <bool>true</bool> + </property> + <property name="checked"> + <bool>true</bool> + </property> + <property name="text"> + <string>Normal (8 pt)</string> + </property> + </action> + <action name="actionCallsign_font_medium"> + <property name="checkable"> + <bool>true</bool> + </property> + <property name="text"> + <string>Medium (10 pt)</string> + </property> + </action> + <action name="actionCallsign_font_large"> + <property name="checkable"> + <bool>true</bool> + </property> + <property name="text"> + <string>Large (12 pt)</string> + </property> + </action> + <action name="actionCallsign_position_top"> + <property name="checkable"> + <bool>true</bool> + </property> + <property name="text"> + <string>Top of waterfall</string> + </property> + </action> + <action name="actionCallsign_position_bottom"> + <property name="checkable"> + <bool>true</bool> + </property> + <property name="text"> + <string>Bottom of waterfall (above divider)</string> + </property> + </action> <action name="actionOpen"> <property name="text"> <string>Open</string> @@ -1567,6 +1711,14 @@ hr { height: 1px; border-width: 0; } <string>Aggressive Deep Search</string> </property> </action> + <action name="actionFull_Deep_Search"> + <property name="checkable"> + <bool>true</bool> + </property> + <property name="text"> + <string>Full Deep Search</string> + </property> + </action> <action name="actionNone"> <property name="checkable"> <bool>true</bool> @@ -1843,7 +1995,7 @@ hr { height: 1px; border-width: 0; } <customwidget> <class>DisplayText</class> <extends>QTextBrowser</extends> - <header>widgets/displaytext.h</header> + <header>displaytext.h</header> </customwidget> </customwidgets> <resources/> diff --git a/map65/map65.pro b/map65/map65.pro deleted file mode 100644 index 79a2e5c4..00000000 --- a/map65/map65.pro +++ /dev/null @@ -1,73 +0,0 @@ -#------------------------------------------------- -# -# Project created by QtCreator 2011-07-07T08:39:24 -# -#------------------------------------------------- - -QT += core gui network -greaterThan(QT_MAJOR_VERSION, 4): QT += widgets -CONFIG += thread -#CONFIG += console - -TARGET = map65 -VERSION = 2.5.0 -TEMPLATE = app -DEFINES = QT5 -DESTDIR = /MAP65_2.9 - -F90 = gfortran -gfortran.output = ${QMAKE_FILE_BASE}.o -gfortran.commands = $$F90 -c -O2 -o ${QMAKE_FILE_OUT} ${QMAKE_FILE_NAME} -gfortran.input = F90_SOURCES -QMAKE_EXTRA_COMPILERS += gfortran - -win32 { -DEFINES = WIN32 -} - -unix { -DEFINES = UNIX -} - -SOURCES += main.cpp mainwindow.cpp plotter.cpp about.cpp \ - soundin.cpp soundout.cpp devsetup.cpp \ - widegraph.cpp getfile.cpp messages.cpp bandmap.cpp \ - astro.cpp displaytext.cpp getdev.cpp \ - txtune.cpp meterwidget.cpp signalmeter.cpp \ - cqdatasender.cpp liveCQSender.cpp Radio.cpp \ - PSKReporter.cpp - -win32 { -SOURCES += killbyname.cpp set570.cpp -} - -HEADERS += mainwindow.h plotter.h soundin.h soundout.h \ - about.h devsetup.h widegraph.h getfile.h messages.h \ - bandmap.h commons.h sleep.h astro.h displaytext.h \ - txtune.h meterwidget.h signalmeter.h cqdatasender.h \ - liveCQSender.hpp Radio.hpp PSKReporter.hpp - -FORMS += mainwindow.ui about.ui devsetup.ui widegraph.ui \ - messages.ui bandmap.ui astro.ui \ - txtune.ui - -RC_FILE = map65.rc - -unix { -LIBS += ../map65/libm65/libm65.a -LIBS += -lfftw3f -lportaudio -lgfortran -#LIBS +- -lusb -} - -win32 { -LIBS += ../map65/libm65/libm65.a -LIBS += ../map65/libfftw3f_win.a -LIBS += ../map65/palir-02.dll -LIBS += libwsock32 -#LIBS += C:/MinGW/lib/libf95.a -LIBS += -lgfortran -#LIBS += -lusb -LIBS += ../map65/libusb.a -#LIBS += -lQt5Concurrent -#LIBS += c:\JTSDK-QT\Qt5\Tools\mingw48_32\i686-w64-mingw32\lib\libmingwex.a -} diff --git a/map65/map65_decode_display_filter.cpp b/map65/map65_decode_display_filter.cpp new file mode 100644 index 00000000..107001d4 --- /dev/null +++ b/map65/map65_decode_display_filter.cpp @@ -0,0 +1,95 @@ +#include "map65_decode_display_filter.h" + +#include <QtGlobal> + +namespace +{ +QString const passMarker {"<Map65DecodePass>"}; +constexpr int duplicateFrequencyToleranceHz = 20; +} + +bool Map65DecodeDisplayFilter::handleControlLine(QString const& line) +{ + if (!line.startsWith(passMarker)) return false; + + QString const pass = line.mid(passMarker.size()).trimmed().toLower(); + if (pass == "early") + { + pass_ = Pass::Early; + earlyDecodes_.clear(); + } + else if (pass == "final") pass_ = Pass::Final; + else if (pass == "manual") pass_ = Pass::Manual; + else if (pass == "disk") pass_ = Pass::Disk; + else pass_ = Pass::Unknown; + + return true; +} + +bool Map65DecodeDisplayFilter::shouldDisplay(QString const& decodeLine) +{ + if (pass_ == Pass::Manual || pass_ == Pass::Disk || pass_ == Pass::Unknown) + return true; + + Identity identity; + if (!parseIdentity(decodeLine, &identity)) return true; + + for (auto const& earlyDecode : earlyDecodes_) + { + if (pass_ == Pass::Final && matches(earlyDecode, identity)) return false; + } + + if (pass_ == Pass::Early) earlyDecodes_.append(identity); + return true; +} + +void Map65DecodeDisplayFilter::completeEarlyPass() +{ + pass_ = Pass::Unknown; +} + +void Map65DecodeDisplayFilter::completeCycle() +{ + pass_ = Pass::Unknown; + earlyDecodes_.clear(); +} + +bool Map65DecodeDisplayFilter::parseIdentity(QString const& input, Identity * identity) +{ + QString line = input; + if (line.startsWith('!')) line.remove(0, 1); + if (line.size() < 53) return false; + + bool khzOk = false; + bool dfOk = false; + bool utcOk = false; + int const khz = line.mid(0, 3).trimmed().toInt(&khzOk); + int const df = line.mid(3, 5).trimmed().toInt(&dfOk); + int const utc = line.mid(12, 6).trimmed().toInt(&utcOk); + int const hour = utc / 100; + int const minute = utc % 100; + if (!khzOk || !dfOk || !utcOk || hour < 0 || hour > 23 + || minute < 0 || minute > 59) + return false; + + QString const separator = line.mid(28, 3); + if (separator != " : " && separator != " # ") return false; + bool const q65 = separator == " : "; + int const messageLength = q65 ? 28 : 22; + if (line.size() < 31 + messageLength) return false; + QString const message = line.mid(31, messageLength).simplified().toUpper(); + if (message.isEmpty()) return false; + + identity->q65 = q65; + identity->utc = utc; + identity->frequencyHz = 1000 * khz + df; + identity->message = message; + return true; +} + +bool Map65DecodeDisplayFilter::matches(Identity const& left, Identity const& right) +{ + return left.q65 == right.q65 && left.utc == right.utc + && left.message == right.message + && qAbs(left.frequencyHz - right.frequencyHz) <= duplicateFrequencyToleranceHz; +} diff --git a/map65/map65_decode_display_filter.h b/map65/map65_decode_display_filter.h new file mode 100644 index 00000000..72130a07 --- /dev/null +++ b/map65/map65_decode_display_filter.h @@ -0,0 +1,40 @@ +#ifndef MAP65_DECODE_DISPLAY_FILTER_H +#define MAP65_DECODE_DISPLAY_FILTER_H + +#include <QString> +#include <QVector> + +class Map65DecodeDisplayFilter +{ +public: + bool handleControlLine(QString const& line); + bool shouldDisplay(QString const& decodeLine); + void completeEarlyPass(); + void completeCycle(); + +private: + enum class Pass + { + Unknown, + Early, + Final, + Manual, + Disk + }; + + struct Identity + { + bool q65; + int utc; + int frequencyHz; + QString message; + }; + + static bool parseIdentity(QString const& line, Identity * identity); + static bool matches(Identity const& left, Identity const& right); + + Pass pass_ {Pass::Unknown}; + QVector<Identity> earlyDecodes_; +}; + +#endif diff --git a/map65/map65_decode_lifecycle.txt b/map65/map65_decode_lifecycle.txt new file mode 100644 index 00000000..95296fbb --- /dev/null +++ b/map65/map65_decode_lifecycle.txt @@ -0,0 +1,68 @@ +MAP65 decode request lifecycle +============================== + +Parameter ownership +------------------- +The C-facing getters and setters in npar_ptrs_mod operate on a draft +parameter record. MainWindow::decode prepares that record, then calls +publish_decode_request. Publication copies the complete record into a FIFO +queue and assigns it a monotonically increasing request ID. + +A dedicated mutex protects draft access, publication, cancellation and +claiming. It is separate from g_fortran_decode_mutex, which is held for the +decoder thread's entire lifetime. + +run_m65 claims one queued request before calling m65a. Claiming removes that +request from the queue and copies its parameters into decoder-owned active +storage. All decoder routines use those active parameters until the call +returns. GUI updates can prepare and publish subsequent requests without +changing the active pass. + +The live waterfall reads the draft center frequency through get_fcenter. +Runtime sample-rate/FFT sizes and the working directory are initialized +before decoding and are not per-request parameters. + +Triggers and completion +----------------------- +Automatic live decoding publishes an early request at 280 half-symbols and a +final request at 302 half-symbols. Disk input publishes the final request. +The FIFO preserves both requests if the early pass is delayed or has not +started when the final trigger arrives. + +The live input generation advances when the sound/UDP input resets its +write pointer, before writing the next interval's samples. Each request +records that generation. An automatic live +request still pending after rollover expires instead of decoding another +interval's samples. The decoder emits <DecodeSkipped> with the expired +request ID; the GUI clears busy only for the latest request, without +changing decode counts or advancing a disk sequence. Manual repeats and +disk requests do not expire on live rollover. + +newdat belongs to the active request and starts at 1. The DSP receives its +own copy for FFT-cache invalidation. Clearing that copy or finishing a pass +cannot erase or repeat a pending request. + +The Decode button sets nagain to reuse the previous sample snapshot. +Freeze-decode also sets manualDecodeFlag. Publication consumes the draft +manual flag, so it cannot leak into the next automatic request. + +An early pass emits <EarlyFinished>. A final or manual pass emits +<DecodeFinished> with its request ID appended after the existing fixed-width +fields. The GUI accepts final completion only when that ID still matches the +latest published request. An older completion cannot clear busy state or +advance a disk sequence while newer work is pending. + +decoder_ready temporarily prevents claims while input/parameters are being +prepared; publication enables claims. Loading another file cancels queued +requests and invalidates older completion IDs. Shutdown frees queued +requests. Neither operation interrupts an already active DSP call. + +Sample-buffer boundary +---------------------- +The request queue owns scalar parameters and strings, not sample buffers. +decode0 copies live dd/ss/savg into the existing snapshot when an automatic +request starts; manual repeats reuse that snapshot. Requests claimed before +rollover still have the existing race between the sample copy and buffer +updates. Generation checks reject already obsolete pending requests; they +do not establish ownership of a claimed request's samples or synchronize +its sample copy. diff --git a/map65/messages.cpp b/map65/messages.cpp index 07936c4e..4ded52c2 100644 --- a/map65/messages.cpp +++ b/map65/messages.cpp @@ -5,9 +5,10 @@ #include "mainwindow.h" #include "qt_helpers.hpp" #include "../revision_utils.hpp" -#include "../Logger.hpp" -#include "PSKReporter.hpp" +#include "../Network/PSKReporter.hpp" #include "liveCQSender.hpp" +#include "pskreporter_decode.h" +#include "pskreporter_settings.h" #include <QCoreApplication> //liveCQ #include <QNetworkAccessManager> //liveCQ @@ -21,11 +22,8 @@ #include <QThread> #include <QDebug> -#include <iostream> -#include <string> -#include <memory> - -Messages::Messages (QString const& settings_filename, QWidget * parent) : +Messages::Messages (QString const& settings_filename, QString const& eclipse_filename, + QWidget * parent) : QDialog {parent}, ui {new Ui::Messages}, m_settings_filename {settings_filename} @@ -42,11 +40,13 @@ Messages::Messages (QString const& settings_filename, QWidget * parent) : ui->messagesTextBrowser->clear(); QSettings settings2 {m_settings_filename, QSettings::IniFormat}; + auto const pskReporterSettings = readMap65PSKReporterSettings(settings2); SettingsGroup h {&settings2, "Common"}; bool m_w3szUrl = settings2.value("w3szUrl",true).toBool(); QString m_otherUrl = settings2.value("otherUrl","").toString(); QString m_myCall=settings2.value("MyCall","").toString(); QString m_myGrid=settings2.value("MyGrid","").toString(); + m_spot_to_psk_reporter = pskReporterSettings.enabled; QString theUrl; if(m_w3szUrl) { @@ -78,29 +78,18 @@ Messages::Messages (QString const& settings_filename, QWidget * parent) : }); connect(livecqThread, &QThread::finished, livecqThread, &QObject::deleteLater); livecqThread->start(); - - // Create the thread and your PSKReporter object - pskThread = new QThread(this); - - connect(pskThread, &QThread::started, this, [this, m_myCall,m_myGrid]() { - auto* reporter = new PSKReporter(m_myCall, m_myGrid, QString {"MAP65 v" - + QCoreApplication::applicationVersion () - + " " + revision ()}.simplified ()); - reporter->moveToThread(this->pskThread); - connect(reporter, &PSKReporter::destroyed, pskThread, &QThread::quit); - QMetaObject::invokeMethod(reporter, "init", Qt::QueuedConnection); - - // Connect signals for control and communication - connect(this, &Messages::sendLocalStationData, reporter, &PSKReporter::setLocalStation); - connect(this, &Messages::sendRemoteStationData, reporter, &PSKReporter::addRemoteStation); - - }); - connect(pskThread, &QThread::finished, pskThread, &QObject::deleteLater); - pskThread->start(); - if (m_spot_to_psk_reporter) { - initializePSKReporting(); - } + m_psk_reporter.reset(new PSKReporter({ + pskReporterSettings.use_tcpip, + eclipse_filename, + QString {"MAP65 v" + QCoreApplication::applicationVersion() + + " " + revision()}.simplified() + })); + connect(m_psk_reporter.get(), &PSKReporter::errorOccurred, + this, &Messages::errorOccurred); + if (m_spot_to_psk_reporter) { + initializePSKReporting(); + } } Messages::~Messages() @@ -108,6 +97,9 @@ Messages::~Messages() //QSettings settings {m_settings_filename, QSettings::IniFormat}; //SettingsGroup g {&settings, "MainWindow"}; //settings.setValue ("MessagesGeom", geometry ()); + if (m_psk_reporter) { + m_psk_reporter->sendReport(true); + } delete ui; } @@ -133,7 +125,19 @@ void Messages::initializePSKReporting() SettingsGroup g {&settings, "Common"}; QString receiverCallsign=settings.value("MyCall","").toString(); QString receiverLocator=settings.value("MyGrid","").toString(); - emit sendLocalStationData(receiverCallsign, receiverLocator, "N/A", "N/A (MAP65)"); + m_psk_reporter->setLocalStation(receiverCallsign, receiverLocator, + "N/A", "N/A (MAP65)"); +} + +void Messages::setPSKReportingEnabled(bool enabled) +{ + auto const was_enabled = m_spot_to_psk_reporter; + m_spot_to_psk_reporter = enabled; + if (enabled) { + initializePSKReporting(); + } else if (was_enabled) { + m_psk_reporter->sendReport(true); + } } void Messages::sendLiveCQData(QStringList decodeList) { @@ -155,14 +159,14 @@ void Messages::sendLiveCQData(QStringList decodeList) { else return; for (const QString &theLine : decodeList) { QStringList thePostLine = theLine.split(" ",SkipEmptyParts); - if((thePostLine.at(5) == "CQ" || thePostLine.at(5) == "QRZ" || thePostLine.at(5) == "CQV" || thePostLine.at(5) == "CQH" || thePostLine.at(5) == "QRT") && m_myCall.length() >=3 && m_myGrid.length()>=4) { + if((thePostLine.at(5).trimmed() == "CQ" || thePostLine.at(5).trimmed() == "QRZ" || thePostLine.at(5).trimmed() == "CQV" || thePostLine.at(5) == "CQH" || thePostLine.at(5).trimmed() == "QRT") && m_myCall.length() >=3 && m_myGrid.length()>=4) { if(allDecodes.filter(theLine.mid(0,53)).length() == 0) { allDecodes.append(theLine); QString freq = thePostLine.at(0).trimmed(); QString dF = thePostLine.at(1).trimmed(); QString utcdatetimestringOriginal = guiDate + " " + thePostLine.at(3).trimmed() + "00"; //needs 2 spaces between date and time QDateTime utcdatetimeUTC = QDateTime::fromString(utcdatetimestringOriginal, "yyyy MMM dd HHmmss"); - utcdatetimeUTC.setTimeSpec((Qt::UTC)); + utcdatetimeUTC.setTimeZone(QTimeZone::utc()); QString utcdatetimeUTCString = utcdatetimeUTC.toString("yyyy-MM-ddTHH:mm:ss"); utcdatetimeUTCString = utcdatetimeUTCString + "Z"; QString dB = thePostLine.at(4).trimmed(); @@ -176,12 +180,12 @@ void Messages::sendLiveCQData(QStringList decodeList) { // Handle CQ CALL but NO GRID -- dot at 7 if(thePostLine.at(7).contains(".")) { callsign = thePostLine.at(6).trimmed().toUpper(); - bool isCall = testCall(callsign); + bool isCall = Map65PSKReporter::isValidMap65Callsign(callsign); if(!isCall) continue; dT =thePostLine.at(7).trimmed(); modeChar = thePostLine.at(8).trimmed(); - if(modeChar.contains("#")) mode = "JT65" + modeChar.back(); - else if(modeChar.contains(":")) mode = "Q65-60" + modeChar.back(); + if(modeChar.contains("#")) mode = QString("JT65") + modeChar.back(); + else if(modeChar.contains(":")) mode = QString("Q65-60") + modeChar.back(); if(m_xpol) { rpol = thePostLine.at(2).trimmed(); } else { @@ -193,20 +197,20 @@ void Messages::sendLiveCQData(QStringList decodeList) { } else if (thePostLine.at(8).contains(".")) { // Test for callsign at thePostLine(6) callsign = thePostLine.at(6).trimmed().toUpper(); - bool isCall = testCall(callsign); + bool isCall = Map65PSKReporter::isValidMap65Callsign(callsign); if(isCall) { grid = thePostLine.at(7).trimmed(); // Handle CQ XXX CALL } else { callsign = thePostLine.at(7).trimmed().toUpper(); - bool isCall = testCall(callsign); + bool isCall = Map65PSKReporter::isValidMap65Callsign(callsign); if(!isCall) continue; } dT =thePostLine.at(8).trimmed(); modeChar = thePostLine.at(9).trimmed(); if(modeChar.contains("#")) { - mode = "JT65" + modeChar.back(); + mode = QString("JT65") + modeChar.back(); if (m_xpol) { rpol = thePostLine.at(2).trimmed(); if(thePostLine.length()==11) { @@ -216,7 +220,7 @@ void Messages::sendLiveCQData(QStringList decodeList) { } else txpol="--"; } } else if(modeChar.contains(":")) { - mode = "Q65-60" + modeChar.back(); + mode = QString("Q65-60") + modeChar.back(); if (m_xpol) { rpol = thePostLine.at(2).trimmed(); if(thePostLine.length()==11) { @@ -229,7 +233,7 @@ void Messages::sendLiveCQData(QStringList decodeList) { // Handle CQ XXX CALL GRID } else if(thePostLine.at(9).contains(".")) { callsign = thePostLine.at(7).trimmed().toUpper(); - bool isCall = testCall(callsign); + bool isCall = Map65PSKReporter::isValidMap65Callsign(callsign); if(!isCall) continue; grid = thePostLine.at(8).trimmed(); @@ -237,7 +241,7 @@ void Messages::sendLiveCQData(QStringList decodeList) { modeChar = thePostLine.at(10).trimmed(); if(modeChar.contains("#")) { - mode = "JT65" + modeChar.back(); + mode = QString("JT65") + modeChar.back(); if (m_xpol) { rpol = thePostLine.at(2).trimmed(); if(thePostLine.length()==12) { @@ -247,7 +251,7 @@ void Messages::sendLiveCQData(QStringList decodeList) { } else txpol="--"; } } else if(modeChar.contains(":")) { - mode = "Q65-60" + modeChar.back(); + mode = QString("Q65-60") + modeChar.back(); if (m_xpol) { rpol = thePostLine.at(2).trimmed(); if(thePostLine.length()==12) { @@ -272,63 +276,6 @@ void Messages::sendLiveCQData(QStringList decodeList) { } } -bool Messages::testCall(QString w) -{ -// Check "callsign" to see if it could be a valid standard callsign or a valid -// compound callsign. -// Return a logical "call ok" indicator. - if(w.indexOf('.') >= 0) return false; - if(w.indexOf('+') >= 0) return false; - if(w.indexOf('-') >= 0) return false; - if(w.indexOf('?') >= 0) return false; - w = w.replace('<',""); - w = w.replace('>',""); - int n1=w.length(); - if(n1 > 11) return false; - QString bc = QString(); - QStringList wSplit = w.split("/"); - if(wSplit.length() > 1) { - if(wSplit.at(0).length() > wSplit.at(1).length()) { - bc = wSplit.at(0); - } - else { - bc = wSplit.at(1); - } - } - else { - bc = w; - } - int nbc=bc.trimmed().length(); - if(nbc > 8) return false; //Base call should have no more than 8 characters e.g. YW18FIFA - -// One of first two characters must be a letter - if((!bc[0].isLetter()) && (!bc[1].isLetter())) return false; -// Real calls don't start with Q, but we'll allow the placeholder -// callsign QU1RK to be considered a standard call: - if(bc[0]=='Q' && bc.mid(0,5) != "QU1RK") return false; - -// Must have a digit in 2nd or 3rd or 4th position - int i1=0; - if(bc[1].isDigit()) i1=1; - if(bc[2].isDigit()) i1=2; - if(bc[3].isDigit()) i1=3; - if(i1==0) return false; - -// Callsign must have a suffix of 1-4 letters e.g. YW18FIFA - if(i1==nbc) return false; - int n=0; - QChar j=QChar(); - for (int i=i1+1; i<=nbc-1; ++i) { - j=bc[i]; - if(j<QChar('A') || j > QChar('Z')) return false; - n=n+1; - } - if(n >= 1 && n <= 4) return true; - - return false; -} - - void Messages::onFinished(QNetworkReply *reply) { if (reply->error() == QNetworkReply::NoError) { @@ -344,7 +291,6 @@ void Messages::setText(QString t, QString t2) QString cfreq,cfreq0; m_t=t; m_t2=t2; - //bool firstTime = true; QStringList cqliveText; //liveCQ doLiveCQ = true; //liveCQ @@ -381,119 +327,29 @@ void Messages::setText(QString t, QString t2) cfreq0=cfreq; ui->messagesTextBrowser->append(t1.mid(5,67)); //was 5,61 } - if(doLiveCQ) { //liveCQ - if(cqliveText.size() > 0) { //liveCQ + if(doLiveCQ && cqliveText.size() > 0) { //liveCQ sendLiveCQData(cqliveText); //liveCQ doLiveCQ = false; //liveCQ } //liveCQ - } //liveCQ - if (m_spot_to_psk_reporter) { + if (m_spot_to_psk_reporter && cqliveText.size() > 0) { sendPSKReporterData(cqliveText); //PSKReporter } } -void Messages::sendPSKReporterData(QStringList decodeList) { - - QSettings settings(m_settings_filename, QSettings::IniFormat); +void Messages::sendPSKReporterData(QStringList decodeList) { + QSettings settings {m_settings_filename, QSettings::IniFormat}; SettingsGroup g {&settings, "Common"}; - - //QRZ parameters (3) - QString receiverCallsign=settings.value("MyCall","").toString(); - QString receiverLocator=settings.value("MyGrid","").toString(); - m_spot_to_psk_reporter = settings.value("spotPSK",true).toBool(); - //QRZ parameters (8) - QString senderCallsign; - QString senderLocator; - double doubleFreq = 0.0; //(Hz) - qint64 frequency = 0.0; - int sNR = -10; - QString mode = ""; - bool ok = false; - - for (const QString &theLine : decodeList) { - QStringList thePostLine = theLine.split(" ",SkipEmptyParts); - if((thePostLine.at(5) == "CQ" || thePostLine.at(5) == "QRZ" || thePostLine.at(5) == "CQV" || thePostLine.at(5) == "CQH" || thePostLine.at(5) == "QRT") && receiverCallsign.length() >=3 && receiverLocator.length()>=4) { - if(allDecodes2.filter(theLine.mid(0,53)).length() == 0) { - allDecodes2.append(theLine); - QString freq = thePostLine.at(0).trimmed(); - doubleFreq = freq.toDouble(&ok); - frequency = qRound64(doubleFreq * 1000000); - QString dF = thePostLine.at(1).trimmed(); - QString dB = thePostLine.at(4).trimmed(); - sNR = dB.toInt(&ok); - QString msgType = thePostLine.at(5).trimmed().toUpper(); - senderCallsign = ""; - senderLocator = "--"; - mode=""; - sNR=-10; - QString modeChar = ""; + auto const spots = Map65PSKReporter::parseMap65PSKReporterSpots( + decodeList, + settings.value("MyCall", "").toString(), + settings.value("MyGrid", "").toString(), + QDateTime::currentDateTimeUtc(), + allDecodes2); - int m_TRperiod = 60; - QString sTimeString = (thePostLine.at(3).trimmed() + "00"); - int sTime = sTimeString.toInt(); - int h=sTimeString.mid(0,2).toInt(); - int m=sTimeString.mid(2,2).toInt(); - int s=sTimeString.mid(4,2).toInt(); - QTime time2(h, m, s); - QDateTime qSpotTime; - if (sTime + m_TRperiod < 236000) { - qSpotTime = QDateTime(QDateTime::currentDateTimeUtc().date(), time2, Qt::UTC); - } - else { - qSpotTime = QDateTime((QDateTime::currentDateTimeUtc().addDays(-1)).date(), time2, Qt::UTC); - } - - // Handle CQ CALL but NO GRID -- dot at 7 - if(thePostLine.at(7).contains(".")) { - senderCallsign = thePostLine.at(6).trimmed().toUpper(); - bool isCall = testCall(senderCallsign); - if(!isCall) continue; - modeChar = thePostLine.at(8).trimmed(); - if(modeChar.contains("#")) mode = "JT65" + modeChar.back(); - else if(modeChar.contains(":")) mode = "Q65-60" + modeChar.back(); - - // Handle CQ CALL GRID or CQ XXX CALL -- dot at 8 - } else if (thePostLine.at(8).contains(".")) { - // Test for callsign at thePostLine(6) - senderCallsign = thePostLine.at(6).trimmed().toUpper(); - bool isCall = testCall(senderCallsign); - if(isCall) { - senderLocator = thePostLine.at(7).trimmed(); - // Handle CQ XXX CALL - } else { - senderCallsign = thePostLine.at(7).trimmed().toUpper(); - bool isCall = testCall(senderCallsign); - if(!isCall) continue; - } - modeChar = thePostLine.at(9).trimmed(); - if(modeChar.contains("#")) - { - mode = "JT65" + modeChar.back(); - } else if(modeChar.contains(":")) { - mode = "Q65-60" + modeChar.back(); - } - // Handle CQ XXX CALL GRID - } else if(thePostLine.at(9).contains(".")) { - senderCallsign = thePostLine.at(7).trimmed().toUpper(); - bool isCall = testCall(senderCallsign); - if(!isCall) continue; - senderLocator = thePostLine.at(8).trimmed(); - - modeChar = thePostLine.at(10).trimmed(); - if(modeChar.contains("#")) - { - mode = "JT65" + modeChar.back(); - } else if(modeChar.contains(":")) { - mode = "Q65-60" + modeChar.back(); - } - } - else { - continue; - } - - emit sendRemoteStationData(senderCallsign, senderLocator, frequency, mode, sNR, qSpotTime); - } - } + for (auto const& spot : spots) { + m_psk_reporter->addRemoteStation(spot.callsign, spot.locator, + spot.frequency, spot.mode, spot.snr, + spot.time); } } diff --git a/map65/messages.h b/map65/messages.h index 89170545..5b27157a 100644 --- a/map65/messages.h +++ b/map65/messages.h @@ -3,26 +3,25 @@ #include <QDialog> #include "commons.h" -#include "PSKReporter.hpp" #include <memory> #include <QNetworkReply> -#include <QDateTime> namespace Ui { class Messages; } -class PSKReporter; // Forward declaration — avoids including PSKReporter.h here +class PSKReporter; class Messages : public QDialog { Q_OBJECT public: - explicit Messages (QString const& settings_filename, QWidget * parent = nullptr); + explicit Messages (QString const& settings_filename, QString const& eclipse_filename, + QWidget * parent = nullptr); void setText(QString t, QString t2); void setColors(QString t); - void init_psk_reporter(bool const& param1, bool const& param2, QString const& param3); + void setPSKReportingEnabled(bool enabled); void setClosingForShutdown(bool value) { m_closingForShutdown = value; } ~Messages(); @@ -30,8 +29,6 @@ public: signals: void click2OnCallsign(QString hiscall, QString t2, bool ctrl); void errorOccurred(const QString &error); // Emitted on error - void sendLocalStationData(QString const& call, QString const& grid, QString const& antenna, QString const& rigInformation); - void sendRemoteStationData (QString const& call, QString const& grid, quint64 freq, QString const& mode, int snr, QDateTime qSpotTime); void sendLocalStationData2(QString const& call, QString const& grid, QString const& theUrl); void sendRemoteStationData2 (QByteArray const& postByteArray, QString const& theUrl); @@ -55,8 +52,8 @@ private: QString m_color2; QString m_color3; - QThread* pskThread; QThread* livecqThread; + std::unique_ptr<PSKReporter> m_psk_reporter; bool m_closingForShutdown = false; bool m_cqOnly; @@ -66,7 +63,7 @@ private: void sendPSKReporterData(QStringList decodeList); //PSKReporter void sendLiveCQData(QStringList decodeList); // This will trigger the web request void initializePSKReporting(); - bool testCall(QString w); //liveCQ + bool m_spot_to_psk_reporter {false}; QString w3szUrlAddr="https://w3sz.com/livecq_update.php"; //liveCQ diff --git a/map65/paInputDevice.c b/map65/paInputDevice.c index bad4973f..d836d5a5 100644 --- a/map65/paInputDevice.c +++ b/map65/paInputDevice.c @@ -43,7 +43,10 @@ void paInputDevice(int id, char* hostAPI_DeviceName, int* minChan, p=strstr(pa_device_hostapi,"WDM-KS"); if(p!=NULL) p1="WDM-KS"; - sprintf(p2,"%-8s %-39s",p1,pa_device_name); + snprintf(p2, sizeof(p2), + "%-8s %-39.39s", + p1, pa_device_name); + for(i=0; i<50; i++) { hostAPI_DeviceName[i]=p2[i]; if(p2[i]==0) break; diff --git a/map65/pa_get_device_info.c b/map65/pa_get_device_info.c index 968d3434..934ddc94 100644 --- a/map65/pa_get_device_info.c +++ b/map65/pa_get_device_info.c @@ -53,9 +53,16 @@ int pa_get_device_info (int n, if(n >= Pa_GetDeviceCount() ) return -1; deviceInfo = Pa_GetDeviceInfo(n); if (deviceInfo->maxInputChannels==0) return -1; - sprintf((char*)(pa_device_name),"%s",deviceInfo->name); - sprintf((char*)(pa_device_hostapi),"%s", - Pa_GetHostApiInfo( deviceInfo->hostApi )->name); + snprintf((char*)pa_device_name, + 128, + "%.127s", + deviceInfo->name); + +snprintf((char*)pa_device_hostapi, + 128, + "%.127s", + Pa_GetHostApiInfo(deviceInfo->hostApi)->name); + speed_warning=0; // bypass bug in Juli@ ASIO driver: diff --git a/map65/plotter.cpp b/map65/plotter.cpp index ab53a4ef..6397222b 100644 --- a/map65/plotter.cpp +++ b/map65/plotter.cpp @@ -1,11 +1,18 @@ #include "plotter.h" #include <math.h> +#include <algorithm> #include <QDebug> +#include <QFont> +#include <QFontMetrics> +#include <QPainter> #include <fstream> #include <iostream> +#include <iterator> #define MAX_SCREENSIZE 2048 +extern int g_sampleRate; +extern int g_activeNfft; CPlotter::CPlotter(QWidget *parent) : //CPlotter Constructor QFrame(parent) @@ -34,7 +41,6 @@ CPlotter::CPlotter(QWidget *parent) : //CPlotter Constructor m_fQSO = 125; m_TXkHz = m_fQSO; m_line = 0; - m_fSample = 96000; m_paintAllZoom = false; m_TxDF=0; m_bDecodeFinished=false; @@ -42,6 +48,18 @@ CPlotter::CPlotter(QWidget *parent) : //CPlotter Constructor CPlotter::~CPlotter() { } // Destructor +void CPlotter::ensureWaterfallHistory(int rows) +{ + rows = std::max(0, rows); + int stride = std::max(0, g_activeNfft); + size_t size = static_cast<size_t>(stride) * static_cast<size_t>(rows); + if (m_waterfallStride != stride || m_waterfallRows != rows || m_zwf.size() != size) { + m_zwf.assign(size, 0); + m_waterfallStride = stride; + m_waterfallRows = rows; + } +} + QSize CPlotter::minimumSizeHint() const { return QSize(50, 50); @@ -59,14 +77,14 @@ void CPlotter::resizeEvent(QResizeEvent* ) //resizeEvent() //if changed, resize pixmaps to new screensize m_Size = size(); int w = m_Size.width(); - int h = (m_Size.height()-60)/2; + int h = std::max(0, (m_Size.height()-60)/2); m_WaterfallPixmap = QPixmap(w,h); m_ZoomWaterfallPixmap = QPixmap(w,h); m_2DPixmap = QPixmap(w,h); m_WaterfallPixmap.fill(Qt::black); m_ZoomWaterfallPixmap.fill(Qt::black); m_2DPixmap.fill(Qt::black); - memset(m_zwf,0,32768*h); + ensureWaterfallHistory(h); m_ScalePixmap = QPixmap(w,30); m_ZoomScalePixmap = QPixmap(w,30); //(no change on resize...) m_ScalePixmap.fill(Qt::white); @@ -101,24 +119,34 @@ void CPlotter::paintEvent(QPaintEvent *) // paintEvent() QRect source(0,0,w,30); painter.drawPixmap(target,m_ZoomScalePixmap,source); - float df=m_fSample/32768.0; - int x0=16384 + (0.001*(m_ZoomStartFreq+m_fCal)+m_fQSO-m_nkhz+1.27046) * \ + float df = float(g_sampleRate) / float(g_activeNfft); + int x0 = g_activeNfft/2 + (0.001*(m_ZoomStartFreq+m_fCal)+m_fQSO-m_nkhz+1.27046) * \ 1000.0/df + 0.5; QPainter painter1(&m_WaterfallPixmap); QPainter painter2(&m_ZoomWaterfallPixmap); for(int i=0; i<w; i++) { //Paint the top row - painter2.setPen(m_ColorTbl[m_zwf[x0+i]]); + int idx = x0 + i; + unsigned char color = 0; + if (idx >= 0 && idx < m_waterfallStride && !m_zwf.empty()) { + color = m_zwf[static_cast<size_t>(idx)]; + } + painter2.setPen(m_ColorTbl[color]); painter2.drawPoint(i,0); } if(m_paintAllZoom or (x0 != x00 and x00 != -99)) { // If new fQSO, paint all rows int k=x0; for(int j=1; j<h; j++) { - k += 32768; + k += g_activeNfft; if(x0 != x00 and x00 != -99) { for(int i=0; i<w; i++) { - painter2.setPen(m_ColorTbl[m_zwf[i+k]]); + int idx = k + i; + unsigned char color = 0; + if (idx >= 0 && static_cast<size_t>(idx) < m_zwf.size()) { + color = m_zwf[static_cast<size_t>(idx)]; + } + painter2.setPen(m_ColorTbl[color]); painter2.drawPoint(i,j); } } @@ -169,6 +197,11 @@ void CPlotter::paintEvent(QPaintEvent *) // paintEvent() QRect target2(0,h+60,w,h); // (x,y,width,height) QRect source2(0,0,w,h); painter.drawPixmap(target2,m_ZoomWaterfallPixmap,source2); + // Decoded-callsign overlay — rendered last so labels sit on top of + // the upper waterfall pixmap. WideGraph maintains the list lifecycle. + if (!m_decodeLabels.isEmpty()) { + paintDecodeLabels(painter); + } m_paintEventBusy=false; } @@ -186,13 +219,17 @@ void CPlotter::draw(float s[], int i0, float splot[]) //draw() m_i0=i0; w = m_WaterfallPixmap.width(); h = m_WaterfallPixmap.height(); + ensureWaterfallHistory(h); double gain = pow(10.0,0.05*(m_plotGain+7)); //move current data down one line //(must do this before attaching a QPainter object) m_WaterfallPixmap.scroll(0,1,0,0,w,h); m_ZoomWaterfallPixmap.scroll(0,1,0,0, w, h); - memmove(&m_zwf[32768],m_zwf,32768*(h-1)); + if (m_waterfallStride > 0 && m_waterfallRows > 1) { + size_t stride = static_cast<size_t>(m_waterfallStride); + memmove(&m_zwf[stride], m_zwf.data(), stride * static_cast<size_t>(m_waterfallRows - 1)); + } QPainter painter1(&m_WaterfallPixmap); QPainter painter2D(&m_2DPixmap); @@ -241,14 +278,17 @@ void CPlotter::draw(float s[], int i0, float splot[]) //draw() } } - for(i=0; i<32768; i++) { + int rowBins = std::min(g_activeNfft, m_waterfallStride); + for (i = 0; i < rowBins; i++) { y = 10.0*log10(splot[i]); int y1 = 5.0*gain*(y + 30 - m_plotZero); if (y1<0) y1=0; if (y1>254) y1=254; if (splot[i]>1.e29) y1=255; m_hist2[y1]++; - m_zwf[i]=y1; + if (!m_zwf.empty()) { + m_zwf[static_cast<size_t>(i)] = static_cast<unsigned char>(y1); + } } if(s[0]>1.0e29) m_line=0; @@ -265,9 +305,9 @@ void CPlotter::draw(float s[], int i0, float splot[]) //draw() void CPlotter::UTCstr() { int ihr,imin; - if(datcom_.ndiskdat != 0) { - ihr=datcom_.nutc/100; - imin=(datcom_.nutc) % 100; + if(getNdiskdat() != 0) { + ihr=getNutc()/100; + imin=(getNutc()) % 100; } else { qint64 ms = QDateTime::currentMSecsSinceEpoch() % 86400000; imin=ms/60000; @@ -295,10 +335,17 @@ void CPlotter::DrawOverlay() //DrawOverlay() painter0.setFont(Font); painter0.setPen(Qt::black); - m_binsPerPixel = m_nSpan * 32768.0/(w*0.001*m_fSample) + 0.5; double FreqPerDiv=5.0; - double df = m_binsPerPixel*0.001*m_fSample/32768.0; - m_hdivs = w*df/FreqPerDiv + 0.9999; + double df = m_binsPerPixel * 0.001 * double(g_sampleRate) / double(g_activeNfft); + m_fSpan = w * df; + + m_hdivs = int(w * df / FreqPerDiv + 0.9999); + // Clamp to array size + const int MAX_HDIVS = 482; + if (m_hdivs < 0) m_hdivs = 0; + if (m_hdivs > MAX_HDIVS) m_hdivs = MAX_HDIVS; + + m_fSpan = w*df; m_ScalePixmap.fill(Qt::white); painter0.drawRect(0, 0, w, 30); @@ -345,7 +392,7 @@ void CPlotter::DrawOverlay() //DrawOverlay() painter0.setPen(pen0); x = m_xClick; painter0.drawLine(x,15,x,30); - int x0=(16384-m_i0)/m_binsPerPixel; + int x0=((g_activeNfft/2) - m_i0)/m_binsPerPixel; m_fGreen=(x-x0)*df; x0 += (x0-x); QPen pen3(Qt::red, 3); @@ -369,8 +416,10 @@ void CPlotter::DrawOverlay() //DrawOverlay() painter3.setPen(Qt::black); FreqPerDiv=0.2; - df = 0.001*m_fSample/32768.0; - m_hdivs = 32768*df/FreqPerDiv + 0.9999; + df = 0.001f * float(g_sampleRate) / float(g_activeNfft); + m_hdivs = int(g_activeNfft * df / FreqPerDiv + 0.9999); + if (m_hdivs < 0) m_hdivs = 0; + if (m_hdivs > MAX_HDIVS) m_hdivs = MAX_HDIVS; int nlabs=df*w/0.2 + 1.0; m_ZoomScalePixmap.fill(Qt::white); painter3.drawRect(0, 0, w, 30); @@ -392,7 +441,7 @@ void CPlotter::DrawOverlay() //DrawOverlay() m_HDivText[i]); } - df=m_fSample/32768.0; + df = float(g_sampleRate) / float(g_activeNfft); if(m_bLockTxRx) m_TxDF=m_DF; x = (m_DF + m_mode65*66*11025.0/4096.0 - m_ZoomStartFreq)/df; QPen pen2(Qt::darkGreen, 3); //Mark top JT65B tone with dark Green tick @@ -421,6 +470,7 @@ void CPlotter::DrawOverlay() //DrawOverlay() void CPlotter::MakeFrequencyStrs() //MakeFrequencyStrs { + float StartFreq = m_StartFreq; float freq; int i,j; @@ -430,7 +480,7 @@ void CPlotter::MakeFrequencyStrs() //MakeFrequencyStrs m_FreqUnits = 1; FreqPerDiv = 200; int w = m_WaterfallPixmap.width(); - float df=m_fSample/32768.0; + float df = float(g_sampleRate) / float(g_activeNfft); StartFreq = -w*df/2; int n=StartFreq/FreqPerDiv; StartFreq=n*200; @@ -520,10 +570,13 @@ int CPlotter::getPlotGain() //getPlotGain() void CPlotter::SetCenterFreq(int f) //setCenterFreq() { // f is the integer kHz portion of cfreq, from Linrad packets +// Store the true (un-snapped) center frequency so that pixel<->freq +// conversions (FreqfromX, XfromFreq, setFQSO) are accurate. The old +// 5 kHz snap distorted every click-to-frequency calculation and caused +// the green tickmark to land several kHz away from where the user +// clicked. Scale labels are rounded independently in MakeFrequencyStrs. if(f<0) f=m_nkhz; - int ns = (f+m_FreqOffset-0.5*m_fSpan)/5.0 + 0.5; - double fs = 5*ns; - m_CenterFreq = fs + 0.5*m_fSpan; + m_CenterFreq = f + m_FreqOffset; } qint64 CPlotter::centerFreq() //centerFreq() @@ -575,9 +628,9 @@ void CPlotter::setFQSO(int x, bool bf) //setFQSO() m_xClick=x; } if(m_bLockTxRx) m_TXkHz=m_fQSO; - m_TXfreq = floor(datcom_.fcenter) + 0.001*m_TXkHz; - DrawOverlay(); - update(); + m_TXfreq = floor(static_cast<int>(getFcenter())) + 0.001*m_TXkHz; + DrawOverlay(); + update(); } void CPlotter::setFcal(int n) //setFcal() @@ -597,8 +650,15 @@ int CPlotter::DF() {return m_DF;} // get DF void CPlotter::mousePressEvent(QMouseEvent *event) //mousePressEvent { int h = (m_Size.height()-60)/2; - int x=event->x(); - int y=event->y(); + int x; + int y; +#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) + x = event->position().x(); + y = event->position().y(); +#else + x = event->pos().x(); + y = event->pos().y(); +#endif int button=event->button(); if(y < h+30) { // Wideband waterfall if(button==1) { @@ -608,11 +668,12 @@ void CPlotter::mousePressEvent(QMouseEvent *event) //mousePressEvent if(x<0) x=0; // x is pixel number if(x>m_Size.width()) x=m_Size.width(); m_TXkHz = int(FreqfromX(x)+0.5); - m_TXfreq = floor(datcom_.fcenter) + 0.001*m_TXkHz; + m_TXfreq = floor(static_cast<int>(getFcenter())) + 0.001*m_TXkHz; } } else { // Zoomed waterfall - if(button==1) m_DF=int(m_ZoomStartFreq + x*m_fSample/32768.0); - if(button==2 and !m_bLockTxRx) m_TxDF=int(m_ZoomStartFreq + x*m_fSample/32768.0); + float df = float(g_sampleRate) / float(g_activeNfft); + if (button == 1) m_DF = int(m_ZoomStartFreq + x * df); + if (button == 2 && !m_bLockTxRx) m_TxDF = int(m_ZoomStartFreq + x * df); if(m_bLockTxRx) m_TxDF=m_DF; } DrawOverlay(); @@ -623,14 +684,22 @@ void CPlotter::mouseDoubleClickEvent(QMouseEvent *event) //mouse2click { if(event->button()!=1) return; //Act only on left double-click int h = (m_Size.height()-60)/2; - int x=event->x(); - int y=event->y(); + int x; + int y; +#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) + x = event->position().x(); + y = event->position().y(); +#else + x = event->pos().x(); + y = event->pos().y(); +#endif if(y < h+30) { m_DF=0; setFQSO(x,false); emit freezeDecode1(2); //### ??? } else { - float f = m_ZoomStartFreq + x*m_fSample/32768.0; + float df = float(g_sampleRate) / float(g_activeNfft); + float f = m_ZoomStartFreq + x * df; m_DF=int(f); emit freezeDecode1(1); DrawOverlay(); @@ -652,7 +721,7 @@ int CPlotter::autoZero() //autoZero() int sum2=0; for(int i=0; i<256; i++) { sum2 += m_hist2[i]; - if(sum2 > 16384) { + if (sum2 > g_activeNfft/2) { m_z2=i; break; } @@ -667,8 +736,23 @@ int CPlotter::autoZero() //autoZero() void CPlotter::setNSpan(int n) //setNSpan() { m_nSpan=n; +// ui->widePlot->resetWaterfall(); } +/* +void CPlotter::resetWaterfall() +{ + int w = m_WaterfallPixmap.width(); + int h = m_WaterfallPixmap.height(); + m_WaterfallPixmap = QPixmap(w, h); + m_WaterfallPixmap.fill(Qt::black); + + m_ScalePixmap = QPixmap(w, 30); + m_ScalePixmap.fill(Qt::white); + + m_lastWaterfallLine = 0; +} +*/ void CPlotter::setPalette(QString palette) //setPalette() { if(palette=="Linrad") { @@ -727,11 +811,6 @@ void CPlotter::setPalette(QString palette) //setPalette() } } -void CPlotter::setFsample(int n) -{ - m_fSample=n; -} - void CPlotter::setMode65(int n) { m_mode65=n; @@ -767,23 +846,156 @@ void CPlotter::setLockTxRx(bool b) void CPlotter::mouseMoveEvent (QMouseEvent * event) { int h = m_WaterfallPixmap.height(); - int x=event->x(); - int y=event->y(); + int x; + int y; +#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) + x = event->position().x(); + y = event->position().y(); +#else + x = event->pos().x(); + y = event->pos().y(); +#endif bool lower=(y > 30+h); float freq=FreqfromX(x); - float df=m_fSample/32768.0; - int ndf=x*df + m_ZoomStartFreq; + float df = float(g_sampleRate) / float(g_activeNfft); + int ndf = int(x * df + m_ZoomStartFreq + 0.5f); if(lower) { - QToolTip::showText(event->globalPos(),QString::number(ndf)); + QToolTip::showText( +#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) + event->globalPosition().toPoint() +#else + event->globalPos() +#endif + , QString::number(ndf)); } else { - QToolTip::showText(event->globalPos(),QString::number(freq,'f',3)); + QToolTip::showText( +#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) + event->globalPosition().toPoint() +#else + event->globalPos() +#endif + , QString::number(freq, 'f', 3)); } QWidget::mouseMoveEvent(event); } double CPlotter::rxFreq() { - return floor(datcom_.fcenter) + 0.001*m_fQSO + 0.000001*m_DF; + return floor(static_cast<int>(getFcenter())) + 0.001*m_fQSO + 0.000001*m_DF; +} + +void CPlotter::setDecodeLabels(const QList<DecodeLabel>& labels) +{ + m_decodeLabels = labels; + update(); +} + +void CPlotter::setDecodeLabelAlpha(int alpha) +{ + if (alpha < 0) alpha = 0; + if (alpha > 255) alpha = 255; + if (m_decodeLabelAlpha == alpha) return; + m_decodeLabelAlpha = alpha; + update(); +} + +void CPlotter::setDecodeLabelFontSize(DecodeLabelFontSize sz) +{ + if (m_decodeFontSize == sz) return; + m_decodeFontSize = sz; + update(); +} + +void CPlotter::setDecodeLabelPosition(DecodeLabelPosition p) +{ + if (m_decodeLabelPosition == p) return; + m_decodeLabelPosition = p; + update(); +} + +void CPlotter::paintDecodeLabels(QPainter& painter) +{ + // Sort left-to-right so the stacking pass below assigns rows in + // order of x-position. Same pattern as the QMAP/WSJT-X overlay. + QList<DecodeLabel> sorted = m_decodeLabels; + std::sort(sorted.begin(), sorted.end(), + [this](const DecodeLabel& a, const DecodeLabel& b) { + return XfromFreq(static_cast<float>(a.freq_khz)) + < XfromFreq(static_cast<float>(b.freq_khz)); + }); + + QFont font("Arial", static_cast<int>(m_decodeFontSize), QFont::Bold); + painter.setFont(font); + QFontMetrics metrics(font); + const int row_height = metrics.height() + 1; + + // Up to 5 stack rows — MAP65's wideband span typically shows fewer + // simultaneous decoded stations than FT8 so 5 is plenty. + constexpr int max_rows = 5; + // Upper-waterfall geometry mirrors QMAP: paint event uses y=30 for + // the top edge and height = (widget − 60)/2. Bottom edge = top + h. + constexpr int waterfall_top_y = 30; + const int waterfall_h = (m_Size.height() - 60) / 2; + const int waterfall_bottom_y = waterfall_top_y + waterfall_h; + const bool stack_from_bottom = (m_decodeLabelPosition == DecodeLabelPosition::Bottom); + int row_right_edge[max_rows]; + for (int i = 0; i < max_rows; ++i) row_right_edge[i] = -1000; + + for (const auto& l : sorted) { + const int x = XfromFreq(static_cast<float>(l.freq_khz)); + const int text_w = metrics.horizontalAdvance(l.callsign); + const int rect_w = text_w + 4; + const int rect_x = x - rect_w / 2; + + int row = 0; + for (; row < max_rows; ++row) { + if (rect_x > row_right_edge[row] + 4) break; + } + if (row >= max_rows) continue; + row_right_edge[row] = rect_x + rect_w; + + // Top-anchor: row 0 at the top of the upper waterfall, stacks down. + // Bottom-anchor: row 0 just above the divider, stacks up. + const int y_top = stack_from_bottom + ? (waterfall_bottom_y - row_height * (row + 1)) + : (waterfall_top_y + row_height * row); + const QRect rect(rect_x, y_top, rect_w, row_height); + // View-menu transparency selector. + // master == 255 ("None"): force every element to alpha 255, + // overriding the legacy semi-transparent + // background (180) and tick (200/220) so + // "None" really is no transparency. + // master < 255 (Medium/High): scale each element's base alpha + // proportionally so the relative + // layering is preserved as it fades. + const int master_alpha = m_decodeLabelAlpha; + auto applyAlpha = [master_alpha](QColor c) { + if (master_alpha >= 255) { + c.setAlpha(255); + } else { + c.setAlpha((c.alpha() * master_alpha) / 255); + } + return c; + }; + painter.fillRect(rect, applyAlpha(QColor(0, 0, 0, 180))); + // DG2YCB 2026-05-13 round 2: orange+yellow read as "both red/orange" + // on his display. Move JT65 to cyan — opposite hue from Q65 yellow, + // still legible on the dark waterfall. Q65 stays yellow to match + // the QMAP wide-mode overlay. + const QColor mode_col = l.is_jt65 ? QColor( 0, 255, 255) // cyan (JT65) + : QColor(255, 255, 0); // yellow (Q65) + const QColor tick_col = l.is_jt65 ? QColor( 0, 255, 255, 220) + : QColor(255, 255, 0, 200); + painter.setPen(applyAlpha(tick_col)); + // Tick points toward the visible spectrum side: down (toward the + // divider/signal trace below) when stacked from top; up (toward + // the freq scale at y=30) when stacked from bottom. + const int tick_y0 = stack_from_bottom ? y_top : y_top + row_height; + const int tick_y1 = stack_from_bottom ? y_top - 4 : y_top + row_height + 4; + painter.drawLine(x, tick_y0, x, tick_y1); + painter.setPen(applyAlpha(mode_col)); + painter.drawText(rect, Qt::AlignHCenter | Qt::AlignVCenter, l.callsign); + } } double CPlotter::txFreq() diff --git a/map65/plotter.h b/map65/plotter.h index 36f0bcd0..e7ff1f82 100644 --- a/map65/plotter.h +++ b/map65/plotter.h @@ -10,9 +10,12 @@ #include <QtGui> #include <QFrame> #include <QImage> +#include <QList> #include <QToolTip> #include <cstring> +#include <vector> #include "commons.h" +#include "decode_label.h" #define VERT_DIVS 7 //specify grid screen divisions #define HORZ_DIVS 20 @@ -66,15 +69,35 @@ public: int DF(); int autoZero(); void setPalette(QString palette); - void setFsample(int n); void setMode65(int n); void set2Dspec(bool b); double fGreen(); void setLockTxRx(bool b); double rxFreq(); double txFreq(); +// void resetWaterfall() // void updateFreqLabel(); + // Decoded-callsign overlay (N6NU 2026-05-12, ported from QMAP). + // WideGraph maintains the list and pushes it here; we render the + // callsigns as labels on top of the waterfall at the audio-offset + // x-position. Triggers update() to schedule a paintEvent. + void setDecodeLabels(const QList<DecodeLabel>& labels); + // Master alpha (0..255) scaling every label's background/tick/text + // alpha proportionally. 255 = no change to the legacy colours; lower + // values let more of the waterfall show through. View menu offers + // None=255, Medium=200, High=175. + void setDecodeLabelAlpha(int alpha); + // Font-size picker for the overlay (Small=7, Normal=8 default, + // Medium=10, Large=12). Triggers update() to repaint. + void setDecodeLabelFontSize(DecodeLabelFontSize sz); + DecodeLabelFontSize decodeLabelFontSize() const { return m_decodeFontSize; } + // Anchor position for the overlay (Top = legacy stack-down from + // waterfall top; Bottom = stack-up from the divider so fresh + // signals at the top of the waterfall remain visible). + void setDecodeLabelPosition(DecodeLabelPosition p); + DecodeLabelPosition decodeLabelPosition() const { return m_decodeLabelPosition; } + signals: void freezeDecode0(int n); void freezeDecode1(int n); @@ -92,11 +115,26 @@ private: int XfromFreq(float f); float FreqfromX(int x); qint64 RoundFreq(qint64 freq, int resolution); + void ensureWaterfallHistory(int rows); + // Render m_decodeLabels overlay on top of the waterfall pixmap. + // Stacks colliding labels vertically (max 5 rows) so a busy band + // doesn't paint labels on top of each other. + void paintDecodeLabels(QPainter& painter); + + QList<DecodeLabel> m_decodeLabels; + // Overlay master alpha. 255 = legacy (fully opaque colours). + int m_decodeLabelAlpha {255}; + // Overlay font size. Default Normal=8 pt. + DecodeLabelFontSize m_decodeFontSize {DecodeLabelFontSize::Normal}; + // Overlay anchor. Top = legacy stacking down from upper-waterfall top. + DecodeLabelPosition m_decodeLabelPosition {DecodeLabelPosition::Top}; QPixmap m_WaterfallPixmap; QPixmap m_ZoomWaterfallPixmap; QPixmap m_2DPixmap; - unsigned char m_zwf[32768*400]; + std::vector<unsigned char> m_zwf; + int m_waterfallStride {0}; + int m_waterfallRows {0}; QPixmap m_ScalePixmap; QPixmap m_ZoomScalePixmap; QSize m_Size; @@ -124,7 +162,6 @@ private: qint32 m_z1; qint32 m_z2; qint32 m_nkhz; - qint32 m_fSample; qint32 m_mode65; qint32 m_i0; qint32 m_xClick; diff --git a/map65/pskreporter_decode.cpp b/map65/pskreporter_decode.cpp new file mode 100644 index 00000000..85b51b58 --- /dev/null +++ b/map65/pskreporter_decode.cpp @@ -0,0 +1,120 @@ +#include "pskreporter_decode.h" + +#include "../validators/LiveCQCallsign.hpp" +#include "../Network/DecodedTime.hpp" + +#include <QtGlobal> + +namespace +{ + bool isReportableMessageType(QString const& messageType) + { + return messageType == "CQ" || messageType == "QRZ" + || messageType == "CQV" || messageType == "CQH" + || messageType == "QRT"; + } + + bool parseSpot(QStringList const& tokens, + QString const& receiverCallsign, + QString const& receiverLocator, + QDateTime const& nowUtc, + PSKReporterIPFIX::Spot& spot) + { + if (tokens.size() < 9 || receiverCallsign.length() < 3 + || receiverLocator.length() < 4 + || !isReportableMessageType(tokens.at(5).trimmed())) { + return false; + } + + bool ok = false; + auto const frequencyMHz = tokens.at(0).trimmed().toDouble(&ok); + if (!ok) { + return false; + } + + auto const spotTime = DecodedTime::spotTime(tokens.at(3).trimmed(), nowUtc, 60); + if (!spotTime.isValid()) { + return false; + } + + QString callsign; + QString locator = "--"; + QString mode; + QString modeToken; + + if (tokens.at(7).contains('.')) { + callsign = tokens.at(6).trimmed().toUpper(); + modeToken = tokens.at(8).trimmed(); + } else if (tokens.size() >= 10 && tokens.at(8).contains('.')) { + callsign = tokens.at(6).trimmed().toUpper(); + if (Map65PSKReporter::isValidMap65Callsign(callsign)) { + locator = tokens.at(7).trimmed(); + } else { + callsign = tokens.at(7).trimmed().toUpper(); + } + modeToken = tokens.at(9).trimmed(); + } else if (tokens.size() >= 11 && tokens.at(9).contains('.')) { + callsign = tokens.at(7).trimmed().toUpper(); + locator = tokens.at(8).trimmed(); + modeToken = tokens.at(10).trimmed(); + } else { + return false; + } + + if (!Map65PSKReporter::isValidMap65Callsign(callsign)) { + return false; + } + if (modeToken.contains('#')) { + mode = "JT65" + modeToken.back(); + } else if (modeToken.contains(':')) { + mode = "Q65-60" + modeToken.back(); + } else { + return false; + } + + spot = { + callsign, + locator, + -10, + static_cast<Radio::Frequency>(qRound64(frequencyMHz * 1000000)), + mode, + spotTime + }; + return true; + } +} + +namespace Map65PSKReporter +{ + bool isValidMap65Callsign(QString const& callsign) + { + return LiveCQ::isValidCallsign(callsign); + } + + QList<PSKReporterIPFIX::Spot> parseMap65PSKReporterSpots( + QStringList const& decodeLines, + QString const& receiverCallsign, + QString const& receiverLocator, + QDateTime const& nowUtc, + QStringList& seenDecodes) + { + QList<PSKReporterIPFIX::Spot> spots; + for (auto const& line : decodeLines) { + auto const tokens = line.split(' ', Qt::SkipEmptyParts); + if (tokens.size() < 6 + || !isReportableMessageType(tokens.at(5).trimmed()) + || receiverCallsign.length() < 3 + || receiverLocator.length() < 4 + || !seenDecodes.filter(line.left(53)).isEmpty()) { + continue; + } + + seenDecodes.append(line); + PSKReporterIPFIX::Spot spot; + if (parseSpot(tokens, receiverCallsign, receiverLocator, nowUtc, spot)) { + spots.append(spot); + } + } + return spots; + } +} diff --git a/map65/pskreporter_decode.h b/map65/pskreporter_decode.h new file mode 100644 index 00000000..55a47b6b --- /dev/null +++ b/map65/pskreporter_decode.h @@ -0,0 +1,23 @@ +#ifndef MAP65_PSKREPORTER_DECODE_H +#define MAP65_PSKREPORTER_DECODE_H + +#include <QDateTime> +#include <QList> +#include <QString> +#include <QStringList> + +#include "../Network/PSKReporterIPFIX.hpp" + +namespace Map65PSKReporter +{ + bool isValidMap65Callsign(QString const& callsign); + + QList<PSKReporterIPFIX::Spot> parseMap65PSKReporterSpots( + QStringList const& decodeLines, + QString const& receiverCallsign, + QString const& receiverLocator, + QDateTime const& nowUtc, + QStringList& seenDecodes); +} + +#endif diff --git a/map65/pskreporter_settings.cpp b/map65/pskreporter_settings.cpp new file mode 100644 index 00000000..0df138b7 --- /dev/null +++ b/map65/pskreporter_settings.cpp @@ -0,0 +1,11 @@ +#include "pskreporter_settings.h" + +#include <QSettings> + +Map65PSKReporterSettings readMap65PSKReporterSettings(QSettings const& settings) +{ + return { + settings.value ("Common/spotPSK", true).toBool (), + settings.value ("Common/PSKReporterTCPIP", false).toBool () + }; +} diff --git a/map65/pskreporter_settings.h b/map65/pskreporter_settings.h new file mode 100644 index 00000000..9e6e2d66 --- /dev/null +++ b/map65/pskreporter_settings.h @@ -0,0 +1,14 @@ +#ifndef MAP65_PSKREPORTER_SETTINGS_H +#define MAP65_PSKREPORTER_SETTINGS_H + +class QSettings; + +struct Map65PSKReporterSettings +{ + bool enabled; + bool use_tcpip; +}; + +Map65PSKReporterSettings readMap65PSKReporterSettings(QSettings const& settings); + +#endif diff --git a/map65/runtime_paths.cpp b/map65/runtime_paths.cpp new file mode 100644 index 00000000..eabf2296 --- /dev/null +++ b/map65/runtime_paths.cpp @@ -0,0 +1,132 @@ +#include "runtime_paths.h" + +#include <QDir> +#include <QFile> +#include <QFileInfo> +#include <QStandardPaths> +#include <QDebug> +#include <QStringList> +#include <QSettings> +#include <QVariant> + +namespace +{ + QStringList runtimeSourceCandidates(QString const& appDir, QString const& installedDataDir, + QString const& fileName) + { + QDir app {appDir}; + QDir cwd {QDir::currentPath()}; + + return { + QDir {installedDataDir}.absoluteFilePath(fileName), + app.absoluteFilePath(fileName), + app.absoluteFilePath("resources/" + fileName), + app.absoluteFilePath("../" + fileName), + app.absoluteFilePath("../map65/resources/" + fileName), + cwd.absoluteFilePath(fileName), + cwd.absoluteFilePath("map65/resources/" + fileName) + }; + } +} + +QString writableMap65DataDir() +{ + QString dataDir = QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation); + if (dataDir.isEmpty()) { + dataDir = QDir::home().absoluteFilePath(".map65"); + } + + if (!QDir{}.mkpath(dataDir)) { + qWarning() << "Unable to create MAP65 data directory:" << dataDir; + } + + QDir dir {dataDir}; + if (!dir.mkpath("save")) { + qWarning() << "Unable to create MAP65 save directory:" << dir.absoluteFilePath("save"); + } + return dataDir; +} + +QString map65SettingsFile(QString const& appDir, QString const& dataDir) +{ + QString settingsFile = QDir {dataDir}.absoluteFilePath("map65.ini"); + QString legacySettingsFile = QDir {appDir}.absoluteFilePath("map65.ini"); + if (!QFile::exists(settingsFile) && QFile::exists(legacySettingsFile)) { + if (QFile::copy(legacySettingsFile, settingsFile)) { + QFile::setPermissions(settingsFile, QFile::ReadOwner | QFile::WriteOwner + | QFile::ReadGroup | QFile::ReadOther); + } else { + qWarning() << "Unable to migrate MAP65 settings from" << legacySettingsFile + << "to" << settingsFile; + } + } + return settingsFile; +} + +int readFSam96000(QSettings const& settings, int defaultValue) +{ + QString text = settings.value("FSam96000", QString::number(defaultValue)).toString(); + if (text.compare("true", Qt::CaseInsensitive) == 0) return 1; // legacy bool: true == 96000 + if (text.compare("false", Qt::CaseInsensitive) == 0) return 0; // legacy bool: false == 95238 + bool ok = false; + int value = text.toInt(&ok); + if (ok && value >= 0 && value <= 2) return value; // current int: 0/1/2 + return defaultValue; +} + +QString map65RuntimeFile(QString const& dataDir, QString const& fileName) +{ + return QDir {dataDir}.absoluteFilePath(fileName); +} + +QString map65RuntimeSourceFile(QString const& appDir, QString const& installedDataDir, + QString const& writableDataDir, QString const& fileName) +{ + QString const writablePath = map65RuntimeFile(writableDataDir, fileName); + QString const writableCanonicalPath = QFileInfo {writablePath}.canonicalFilePath(); + auto const candidates = runtimeSourceCandidates(appDir, installedDataDir, fileName); + for (auto const& sourcePath : candidates) { + QFileInfo sourceInfo {sourcePath}; + if (!sourceInfo.exists() || !sourceInfo.isFile() || sourceInfo.size() == 0) { + continue; + } + if (sourceInfo.absoluteFilePath() == writablePath + || (!writableCanonicalPath.isEmpty() + && sourceInfo.canonicalFilePath() == writableCanonicalPath)) { + continue; + } + return sourceInfo.absoluteFilePath(); + } + + return candidates.front(); +} + +QString ensureMap65RuntimeFile(QString const& appDir, QString const& installedDataDir, + QString const& writableDataDir, QString const& fileName) +{ + QString const writablePath = map65RuntimeFile(writableDataDir, fileName); + QFileInfo writableInfo {writablePath}; + if (writableInfo.exists() && writableInfo.size() > 0) { + return writablePath; + } + + QString const sourcePath = map65RuntimeSourceFile(appDir, installedDataDir, + writableDataDir, fileName); + QFileInfo sourceInfo {sourcePath}; + if (sourceInfo.exists() && sourceInfo.isFile() && sourceInfo.size() > 0) { + if (writableInfo.exists()) { + QFile::remove(writablePath); + } + + if (QFile::copy(sourceInfo.absoluteFilePath(), writablePath)) { + QFile::setPermissions(writablePath, QFile::ReadOwner | QFile::WriteOwner + | QFile::ReadGroup | QFile::ReadOther); + return writablePath; + } + + qWarning() << "Unable to migrate MAP65 runtime file from" << sourcePath + << "to" << writablePath; + } + + return writablePath; +} diff --git a/map65/runtime_paths.h b/map65/runtime_paths.h new file mode 100644 index 00000000..4c786c4a --- /dev/null +++ b/map65/runtime_paths.h @@ -0,0 +1,24 @@ +#ifndef MAP65_RUNTIME_PATHS_H +#define MAP65_RUNTIME_PATHS_H + +#include <QString> + +class QSettings; + +QString writableMap65DataDir(); +QString map65SettingsFile(QString const& appDir, QString const& dataDir); +QString map65RuntimeFile(QString const& dataDir, QString const& fileName); +QString map65RuntimeSourceFile(QString const& appDir, QString const& installedDataDir, + QString const& writableDataDir, QString const& fileName); +QString ensureMap65RuntimeFile(QString const& appDir, QString const& installedDataDir, + QString const& writableDataDir, QString const& fileName); + +// Reads the "FSam96000" key (expected to already be scoped, e.g. via +// settings.beginGroup("Common") / SettingsGroup) as text and interprets it +// under both conventions that have shared a single map65.ini across +// versions: legacy MAP65 stored this as a bool (true==96000, false==95238); +// current MAP65 stores it as an integer (0==95238, 1==96000, 2==192000). +// Returns defaultValue if the stored text doesn't match either convention. +int readFSam96000(QSettings const& settings, int defaultValue = 1); + +#endif diff --git a/map65/set570.cpp b/map65/set570.cpp index a5683229..8d97a4ba 100644 --- a/map65/set570.cpp +++ b/map65/set570.cpp @@ -46,7 +46,7 @@ int to_freq; int increment_freq; int display_freq = -1; int delay; -static libusb_device_handle * global_si570usb_handle; +static libusb_device_handle *global_si570usb_handle; void si570_sleep(int us) { @@ -72,7 +72,7 @@ double current_time(void) //for delay measurements unsigned char Si570usbOpenDevice(libusb_device_handle **device, char *usbSerialID); void setLongWord( int value, char * bytes); -int setFreqByValue(libusb_device_handle * handle, double frequency); +int setFreqByValue(libusb_device_handle *handle, double frequency); void sweepa_freq(void); void sweepm_freq(void); diff --git a/map65/soundin.cpp b/map65/soundin.cpp index 46433d4e..ee1886e8 100644 --- a/map65/soundin.cpp +++ b/map65/soundin.cpp @@ -1,5 +1,8 @@ #include "soundin.h" +#include "commons.h" #include <math.h> +#include <complex> +#include "mainwindow.h" #ifdef Q_OS_WIN32 #include <windows.h> @@ -7,48 +10,11 @@ #include <sys/socket.h> #endif -#define NFFT 32768 #define FRAMES_PER_BUFFER 1024 #include <portaudio.h> -extern "C" -{ - struct - { - double d8[2*60*96000]; //This is "common/datcom/..." in fortran - float ss[4*322*NFFT]; - float savg[4*NFFT]; - double fcenter; - int nutc; - int idphi; //Phase correction for Y pol'n, degrees - int mousedf; //User-selected DF - int mousefqso; //User-selected QSO freq (kHz) - int nagain; //1 ==> decode only at fQSO +/- Tol - int ndepth; //How much hinted decoding to do? - int ndiskdat; //1 ==> data read from *.tf2 or *.iq file - int neme; //Hinted decoding tries only for EME calls - int newdat; //1 ==> new data, must do long FFT - int nfa; //Low decode limit (kHz) - int nfb; //High decode limit (kHz) - int nfcal; //Frequency correction, for calibration (Hz) - int nfshift; //Shift of displayed center freq (kHz) - int mcall3; //1 ==> CALL3.TXT has been modified - int ntimeout; //Max for timeouts in Messages and BandMap - int ntol; //+/- decoding range around fQSO (Hz) - int nxant; //1 ==> add 45 deg to measured pol angle - int map65RxLog; //Flags to control log files - int nfsample; //Input sample rate - int nxpol; //1 if using xpol antennas, 0 otherwise - int mode65; //JT65 sub-mode: A=1, B=2, C=4 - int nfast; //1No longer used - int nsave; //Number of s3(64,63) spectra saved - char mycall[12]; - char mygrid[6]; - char hiscall[12]; - char hisgrid[6]; - char datetime[20]; - } datcom_; -} +#include <QDebug> + typedef struct { @@ -60,113 +26,133 @@ typedef struct } paUserData; //--------------------------------------------------------------- a2dCallback -extern "C" int a2dCallback( const void *inputBuffer, void *outputBuffer, - unsigned long framesToProcess, - const PaStreamCallbackTimeInfo* timeInfo, - PaStreamCallbackFlags statusFlags, - void *userData ) - -// This routine called by the PortAudio engine when samples are available. -// It may be called at interrupt level, so don't do anything -// that could mess up the system like calling malloc() or free(). - +extern "C" int a2dCallback(const void* inputBuffer, void* outputBuffer, + unsigned long framesToProcess, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void* userData) { - paUserData *udata=(paUserData*)userData; - (void) outputBuffer; //Prevent unused variable warnings. - (void) timeInfo; - (void) userData; - int nbytes,i,j; - float d4[4*FRAMES_PER_BUFFER]; - float d4a[4*FRAMES_PER_BUFFER]; - float tmp; - float fac; - - if( (statusFlags&paInputOverflow) != 0) { - qDebug() << "Input Overflow"; - } - if(udata->bzero) { //Start of a new minute - udata->kin=0; //Reset buffer pointer - udata->bzero=false; - } + paUserData* udata = static_cast<paUserData*>(userData); - nbytes=udata->nrx*8*framesToProcess; //Bytes per frame - memcpy(d4,inputBuffer,nbytes); //Copy all samples to d4 + (void) outputBuffer; + (void) timeInfo; + (void) userData; - fac=32767.0 * pow(10.0,0.05*udata->dB); + int nbytes,i,j; + float d4[4 * FRAMES_PER_BUFFER]; + float d4a[4 * FRAMES_PER_BUFFER]; + float tmp; + float fac; - if(udata->nrx==2) { - for(i=0; i<4*int(framesToProcess); i++) { //Negate odd-numbered frames - d4[i]=fac*d4[i]; - j=i/4; - if((j%2)==1) d4[i]=-d4[i]; + if ((statusFlags & paInputOverflow) != 0) { + qDebug() << "Input Overflow"; } - if(!udata->iqswap) { - for(i=0; i<int(framesToProcess); i++) { - j=4*i; - tmp=d4[j]; - d4[j]=d4[j+1]; - d4[j+1]=tmp; - tmp=d4[j+2]; - d4[j+2]=d4[j+3]; - d4[j+3]=tmp; - } - } - memcpy(&datcom_.d8[2*udata->kin],d4,nbytes); //Copy from d4 to dd() - } else { - int k=0; - for(i=0; i<2*int(framesToProcess); i+=2) { //Negate odd-numbered frames - j=i/2; - if(j%2==0) { - d4a[k++]=fac*d4[i]; - d4a[k++]=fac*d4[i+1]; - } else { - d4a[k++]=-fac*d4[i]; - d4a[k++]=-fac*d4[i+1]; - } - d4a[k++]=0.0; - d4a[k++]=0.0; + + if (udata->bzero) { // Start of a new minute + advance_live_input_generation(); + udata->kin = 0; // Reset buffer pointer + udata->bzero = false; } - if(!udata->iqswap) { - for(i=0; i<int(framesToProcess); i++) { - j=4*i; - tmp=d4a[j]; - d4a[j]=d4a[j+1]; - d4a[j+1]=tmp; - } + + // Bytes per frame, mirroring legacy intent but for float32 + // legacy used: nbytes = udata->nrx * 8 * framesToProcess; + // here: nrx * 8 bytes per frame (4 floats per frame, each 4 bytes) + nbytes = udata->nrx * 8 * framesToProcess; + + memcpy(d4, inputBuffer, nbytes); + + fac = 32767.0f * pow(10.0f, 0.05f * float(udata->dB)); + + if (udata->nrx == 2) { + // Two RF channels, r*4 data (complex I/Q for X and Y) + for (i = 0; i < 4 * int(framesToProcess); i++) { + d4[i] = fac * d4[i]; + j = i / 4; + if ((j % 2) == 1) d4[i] = -d4[i]; + } + + if (!udata->iqswap) { + for (i = 0; i < int(framesToProcess); i++) { + j = 4 * i; + tmp = d4[j]; d4[j] = d4[j+1]; d4[j+1] = tmp; + tmp = d4[j+2]; d4[j+2] = d4[j+3]; d4[j+3] = tmp; + } + } + + memcpy(&dd[4 * udata->kin], d4, nbytes); + + } else { + // One RF channel + int k = 0; + for (i = 0; i < 2 * int(framesToProcess); i += 2) { + j = i / 2; + if (j % 2 == 0) { + d4a[k++] = fac * d4[i]; + d4a[k++] = fac * d4[i+1]; + } else { + d4a[k++] = -fac * d4[i]; + d4a[k++] = -fac * d4[i+1]; + } + d4a[k++] = 0.0; + d4a[k++] = 0.0; + } + + if (!udata->iqswap) { + for (i = 0; i < int(framesToProcess); i++) { + j = 4 * i; + tmp = d4a[j]; d4a[j] = d4a[j+1]; d4a[j+1] = tmp; + } + } + + // Legacy wrote 2*nbytes into datcom_.d8 for this case (4 floats per frame) + memcpy(&dd[4 * udata->kin], d4a, 2 * nbytes); } - memcpy(&datcom_.d8[2*udata->kin],d4a,2*nbytes); //Copy from d4a to dd() - } - udata->kin += framesToProcess; - return paContinue; + + udata->kin += framesToProcess; + return paContinue; } namespace { + constexpr int symspecLookaheadSamples = 512; + + int symspecReadyPointer(int acquiredSamples) + { + // symspec's final 1024-sample window extends one 512-sample hop past k. + return acquiredSamples - symspecLookaheadSamples; + } + struct COMWrapper { explicit COMWrapper () { -#ifdef Q_OS_WIN32 - // required because Qt only does this for GUI thread - CoInitializeEx (nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); +#ifdef _WIN32 + CoInitializeEx (nullptr, + COINIT_APARTMENTTHREADED | + COINIT_DISABLE_OLE1DDE); #endif } ~COMWrapper () { -#ifdef Q_OS_WIN32 +#ifdef _WIN32 CoUninitialize (); #endif } }; } +//SoundInThread::SoundInThread(MainWindow* mw, QObject* parent) +// : QThread(parent), m_mainWindow(mw) {} + void SoundInThread::run() //SoundInThread::run() { quitExecution = false; - + if (m_net) { // qDebug() << "Start inputUDP()"; inputUDP(); + return; + // qDebug() << "Finished inputUDP()"; return; } @@ -174,13 +160,13 @@ void SoundInThread::run() //SoundInThread::run() COMWrapper c; //---------------------------------------------------- Soundcard Setup - // qDebug() << "Start souncard input"; + qDebug() << "START SOUNDCARD INPUT "; PaError paerr; PaStreamParameters inParam; PaStream *inStream; paUserData udata; - + udata.kin=0; //Buffer pointer udata.bzero=false; //Flag to request reset of kin udata.nrx=m_nrx; //Number of polarizations @@ -195,7 +181,7 @@ void SoundInThread::run() //SoundInThread::run() inParam.suggestedLatency=device_info->defaultHighInputLatency; inParam.hostApiSpecificStreamInfo=NULL; - paerr=Pa_IsFormatSupported(&inParam,NULL,96000.0); + paerr=Pa_IsFormatSupported(&inParam,NULL,double(g_sampleRate)); if(paerr<0) { QString error_message; if (paUnanticipatedHostError == paerr) @@ -208,70 +194,66 @@ void SoundInThread::run() //SoundInThread::run() error_message = "PortAudio says requested soundcard format not supported."; } emit error(error_message); -// return; } - paerr=Pa_OpenStream(&inStream, //Input stream - &inParam, //Input parameters - NULL, //No output parameters - 96000.0, //Sample rate - FRAMES_PER_BUFFER, //Frames per buffer -// paClipOff+paDitherOff, //No clipping or dithering - paClipOff, //No clipping - a2dCallback, //Input callbeck routine - &udata); //userdata - - paerr=Pa_StartStream(inStream); - if(paerr<0) { - emit error("Failed to start audio input stream."); - return; - } -// const PaStreamInfo* p=Pa_GetStreamInfo(inStream); + paerr = Pa_OpenStream( + &inStream, + &inParam, + NULL, + double(g_sampleRate), + FRAMES_PER_BUFFER, + paClipOff, + a2dCallback, + &udata); + + paerr=Pa_StartStream(inStream); + if(paerr<0) { + emit error("Failed to start audio input stream."); + return; + } bool qe = quitExecution; int ntr0=99; int k=0; int nsec; int ntr; - int nBusy=0; - int nhsym0=0; + Map65HalfSymbolScheduler spectrumScheduler; //---------------------------------------------- Soundcard input loop while (!qe) { qe = quitExecution; if (qe) break; + qint64 ms = QDateTime::currentMSecsSinceEpoch() % 86400000; - nsec = ms/1000; // Time according to this computer + nsec = ms/1000; ntr = nsec % m_TRperiod; -// Reset buffer pointer and symbol number at start of minute if(ntr < ntr0 or !m_monitoring or m_TRperiod!=m_TRperiod0) { - nhsym0=0; + spectrumScheduler.reset (); udata.bzero=true; m_TRperiod0=m_TRperiod; } + k=udata.kin; - udata.iqswap=m_IQswap; + + udata.iqswap= (m_IQswap != 0); udata.dB=m_dB; + if(m_monitoring) { - if(m_bForceCenterFreq) { - datcom_.fcenter=m_dForceCenterFreq; - } else { - datcom_.fcenter=144.125; - } - m_hsym=(k-2048)*11025.0/(2048.0*m_rate); - if(m_hsym != nhsym0) { - if(m_dataSinkBusy) { - nBusy++; - } else { - m_dataSinkBusy=true; - emit readyForFFT(k); //Signal to compute new FFTs - } - nhsym0=m_hsym; + double fcenter = m_bForceCenterFreq ? m_dForceCenterFreq : 144.125; + set_fcenter(fcenter); + + int const fftPointer=symspecReadyPointer(k); + m_hsym=(fftPointer-2048)*11025.0/(2048.0*m_rate); + + if (spectrumScheduler.claim_next (m_hsym, m_dataSinkBusy)) { + emit readyForFFT(fftPointer); } } + msleep(100); ntr0=ntr; } + Pa_StopStream(inStream); Pa_CloseStream(inStream); } @@ -314,7 +296,6 @@ void SoundInThread::setFadd(double x) m_fAdd=x; } - void SoundInThread::quit() //quit() { quitExecution = true; @@ -328,12 +309,15 @@ void SoundInThread::setNetwork(bool b) //setNetwork() void SoundInThread::setMonitoring(bool b) //setMonitoring() { m_monitoring = b; + qDebug() << "m_monitoring set to" << m_monitoring << "at" << Q_FUNC_INFO; + } void SoundInThread::setForceCenterFreqBool(bool b) { m_bForceCenterFreq=b; + } void SoundInThread::setForceCenterFreqMHz(double d) @@ -344,10 +328,12 @@ void SoundInThread::setForceCenterFreqMHz(double d) void SoundInThread::setNrx(int n) //setNrx() { m_nrx = n; + //qDebug() << "soundin line 333 SET m_nrx = " << n; } int SoundInThread::nrx() { + //qDebug() << "soundin line 338 RETURNED m_nrx = " << m_nrx; return m_nrx; } @@ -380,7 +366,7 @@ void SoundInThread::inputUDP() int msec; float userfreq; int iptr; - quint16 iblk; + quint16 iblk; //was quint16 qint8 nrx; char iusb; double d8[174]; @@ -390,9 +376,8 @@ void SoundInThread::inputUDP() int k=0; int nsec; int ntr; - int nhsym0=0; + Map65HalfSymbolScheduler spectrumScheduler; int iz=174; - int nBusy=0; // Main loop for input of UDP packets over the network: while (!qe) { @@ -401,8 +386,11 @@ void SoundInThread::inputUDP() if (!udpSocket->hasPendingDatagrams()) { msleep(2); // Sleep if no packet available } else { - int nBytesRead = udpSocket->readDatagram((char *)&b,1416); - if (nBytesRead != 1416) qDebug() << "UDP Read Error:" << nBytesRead; + int nBytesRead = udpSocket->readDatagram(reinterpret_cast<char*>(&b), 1416); + if (nBytesRead != 1416) { + qDebug() << "UDP Read Error:" << nBytesRead; + } + qint64 ms = QDateTime::currentMSecsSinceEpoch() % 86400000; nsec = ms/1000; // Time according to this computer @@ -410,8 +398,9 @@ void SoundInThread::inputUDP() // Reset buffer pointer and symbol number at start of minute if(ntr < ntr0 or !m_monitoring or m_TRperiod!=m_TRperiod0) { + advance_live_input_generation(); k=0; - nhsym0=0; + spectrumScheduler.reset (); m_TRperiod0=m_TRperiod; } ntr0=ntr; @@ -424,28 +413,28 @@ void SoundInThread::inputUDP() if(m_nrx == -2) iz=87; // Two RF channels, r*4 data // If buffer will not overflow, move data into datcom_ - if ((k+iz) <= 60*96000) { + if ((k + iz) <= 60 * m_rate) { int nsam=-1; recvpkt_(&nsam, &b.iblk, &b.nrx, &k, b.d8, b.d8, b.d8); + double fcenter; if(m_bForceCenterFreq) { - datcom_.fcenter=m_dForceCenterFreq; + fcenter = m_dForceCenterFreq; } else { - datcom_.fcenter=b.cfreq + m_fAdd; + fcenter = b.cfreq + m_fAdd; } + set_fcenter(fcenter); } - m_hsym=(k-2048)*11025.0/(2048.0*m_rate); - if(m_hsym != nhsym0) { - if(m_dataSinkBusy) { - nBusy++; - } else { - m_dataSinkBusy=true; - emit readyForFFT(k); //Signal to compute new FFTs - } - nhsym0=m_hsym; - } +double hsym = 2048.0 * m_rate / 11025.0; +int const fftPointer=symspecReadyPointer(k); +m_hsym = (fftPointer - 2048) / hsym; +if (spectrumScheduler.claim_next (m_hsym, m_dataSinkBusy)) { + emit readyForFFT(fftPointer); +} + } } } delete udpSocket; + udpSocket = nullptr; } diff --git a/map65/soundin.h b/map65/soundin.h index 78947338..0f45acea 100644 --- a/map65/soundin.h +++ b/map65/soundin.h @@ -4,8 +4,13 @@ #include <QtCore> #include <QtNetwork/QUdpSocket> #include <QDebug> +#include <atomic> #include <valarray> +#include "half_symbol_scheduler.h" + +class MainWindow; //Forward declaration + // Thread gets audio data from soundcard and signals when a buffer of // specified size is available. class SoundInThread : public QThread @@ -19,7 +24,7 @@ protected: virtual void run(); public: - bool m_dataSinkBusy; + std::atomic_bool m_dataSinkBusy; SoundInThread(): quitExecution(false), @@ -55,6 +60,7 @@ public slots: void quit(); private: + MainWindow* m_mainWindow; void inputUDP(); double m_fAdd; diff --git a/map65/soundout.cpp b/map65/soundout.cpp index e74d0549..baa0d129 100644 --- a/map65/soundout.cpp +++ b/map65/soundout.cpp @@ -4,13 +4,10 @@ #include <windows.h> #endif -#define FRAMES_PER_BUFFER 256 - #include <portaudio.h> -extern float gran(); //Noise generator (for tests only) - -extern short int iwave[2*60*11025]; //Wave file for Tx audio +extern float gran(); +extern short int iwave[2*60*12000]; //was 11025 extern int nwave; extern bool btxok; extern bool bTune; @@ -20,9 +17,11 @@ extern int iqPhase; extern int txPower; extern double outputLatency; -typedef struct //Parameters sent to or received from callback function +typedef struct { int nTRperiod; + int actualChannelCount; + double streamSampleRate; // Added to help callback calculate pitch } paUserData; //--------------------------------------------------------------- d2aCallback @@ -32,94 +31,111 @@ extern "C" int d2aCallback(const void * /*inputBuffer*/, void *outputBuffer, PaStreamCallbackFlags /*statusFlags*/, void *userData ) { - paUserData *udata=(paUserData*)userData; + paUserData *udata = (paUserData*)userData; short *wptr = (short*)outputBuffer; - unsigned int i; - static int n; - static int ic=0; - static bool btxok0=false; - static bool bTune0=false; - static int nStart=0; - static double phi=0.; - double tsec,tstart,dphi; + int channels = udata->actualChannelCount; + + // step is ~0.229 for 48k ASIO, and exactly 1.0 for 11k MME + // Calculate step once outside the loop + double step = 11025.0 / udata->streamSampleRate; + const int waveCapacity = sizeof(iwave) / sizeof(iwave[0]); + + static double ic_exact = 0.0; + static bool btxok0 = false; + static bool bTune0 = false; + static int nStart = 0; + static double phi = 0.; + + double tsec, tstart; + double dphi = 0.0; int nsec; - int nTRperiod=udata->nTRperiod; + int nTRperiod = udata->nTRperiod; - // Get System time qint64 ms = QDateTime::currentMSecsSinceEpoch() % 86400000; - tsec = 0.001*ms; - nsec = ms/1000; - qreal dPhase=iqPhase/5729.57795131; - qreal amp=1.0 + 0.0001*iqAmp; - qreal xAmp=txPower*295.00*qSqrt(2.0 - amp*amp); - qreal yAmp=txPower*295.00*amp; - static int nsec0=0; + tsec = 0.001 * ms; + nsec = ms / 1000; + + qreal dPhase = iqPhase / 5729.57795131; + qreal amp = 1.0 + 0.0001 * iqAmp; + qreal xAmp = txPower * 295.00 * qSqrt(2.0 - amp * amp); + qreal yAmp = txPower * 295.00 * amp; + static int nsec0 = 0; if(bTune) { - ic=0; - dphi=6.28318530718*1270.46/11025.0; + ic_exact = 0; + // Use the actual stream sample rate, not 11025 + dphi = 6.28318530718 * 1270.46 / udata->streamSampleRate; } - if(bTune0 and !bTune) btxok=false; - bTune0=bTune; - - if(nsec!=nsec0) { -// qDebug() << txPower << iqAmp << iqPhase << amp << xAmp << yAmp << dPhase << bTune; -// qDebug() << "A" << nsec%60 << bTune << btxok; -// ic=0; - nsec0=nsec; - } - - if(btxok and !btxok0) { //Start (or re-start) a transmission - n=nsec/nTRperiod; - tstart=tsec - n*nTRperiod - 1.0; - if(tstart<1.0) { - ic=0; //Start of Tx cycle, set starting index to 0 - nStart=n; + if(bTune0 && !bTune) btxok = false; + bTune0 = bTune; + if(nsec != nsec0) nsec0 = nsec; + + // Handle Tx Start/Restart logic + if(btxok && !btxok0) { + int n = nsec / nTRperiod; + tstart = tsec - n * nTRperiod - 1.0; + if(tstart < 1.0) { + ic_exact = 0; + nStart = n; } else { - if(n != nStart) { //Late start in new Tx cycle: compute starting index - ic=(int)(tstart*11025.0); - ic=2*ic; - nStart=n; + if(n != nStart) { + ic_exact = (tstart * 11025.0); + nStart = n; } } } - btxok0=btxok; - - if(btxok) { - for(i=0 ; i<framesToProcess; i++ ) { - short int i2a=iwave[ic++]; - short int i2b=iwave[ic++]; - if(ic > nwave) {i2a=0; i2b=0;} -// i2 = 500.0*(i2/32767.0 + 5.0*gran()); //Add noise (tests only!) -// if(bIQxt) { - if(1) { - if(bTune) { - phi += dphi; - } else { - phi=qAtan2(qreal(i2b),qreal(i2a)); - } - i2a=xAmp*qCos(phi); - i2b=yAmp*qSin(phi + dPhase); -// qDebug() << xAmp << yAmp << phi << i2a << i2b; - } -// i2a=0.01*txPower*i2a; -// i2b=0.01*txPower*i2b; - *wptr++ = i2b; //left - *wptr++ = i2a; //right + btxok0 = btxok; + + + for(unsigned int i = 0; i < framesToProcess; i++) { + // 1. Get current fractional position + int i0 = (int)ic_exact; + int i1 = i0 + 1; + double frac = ic_exact - (double)i0; + + short int i2a = 0; + short int i2b = 0; + + int i0a = 2 * i0; + int i0b = i0a + 1; + int i1a = 2 * i1; + int i1b = i1a + 1; + bool haveWaveformSample = i1b < nwave && i1b < waveCapacity; + + if(btxok && (bTune || haveWaveformSample)) { + + if(bTune) { + phi += dphi; + } else { + // 2. Linear Interpolation to clean up the noise + // Blend current sample (i0) and next sample (i1) based on frac + i2a = (short int)((1.0 - frac) * iwave[i0a] + frac * iwave[i1a]); + i2b = (short int)((1.0 - frac) * iwave[i0b] + frac * iwave[i1b]); + phi = qAtan2(qreal(i2b), qreal(i2a)); + } + i2a = xAmp * qCos(phi); + i2b = yAmp * qSin(phi + dPhase); } - } else { - for(i=0 ; i<framesToProcess; i++ ) { - *wptr++ = 0; + + *wptr++ = i2b; // Left + *wptr++ = i2a; // Right + + // Pad remaining 6 channels for Voicemeeter + for(int c = 2; c < channels; c++) { *wptr++ = 0; - ic++; ic++; + } + + // Advance index by the ratio (0.229) + ic_exact += step; + + if((2 * (int)ic_exact) >= nwave) { + btxok = false; + ic_exact = 0; } } - if(ic > nwave) { - btxok=0; - ic=0; - } - return 0; + + return paContinue; } namespace @@ -128,14 +144,15 @@ namespace { explicit COMWrapper () { -#ifdef Q_OS_WIN32 - // required because Qt only does this for GUI thread - CoInitializeEx (nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); +#ifdef _WIN32 + CoInitializeEx (nullptr, + COINIT_APARTMENTTHREADED | + COINIT_DISABLE_OLE1DDE); #endif } ~COMWrapper () { -#ifdef Q_OS_WIN32 +#ifdef _WIN32 CoUninitialize (); #endif } @@ -145,63 +162,85 @@ namespace void SoundOutThread::run() { COMWrapper c; - PaError paerr; PaStreamParameters outParam; PaStream *outStream; paUserData udata; quitExecution = false; - auto device_info = Pa_GetDeviceInfo (m_nDevOut); + // --- SAFETY CHECK 1: Ensure device index is valid --- + auto device_info = Pa_GetDeviceInfo(m_nDevOut); + if (!device_info) { + qDebug() << "ASIO Error: Could not get info for device index" << m_nDevOut; + return; + } + + // --- SAFETY CHECK 2: Ensure Host API is valid --- + auto host_api_info = Pa_GetHostApiInfo(device_info->hostApi); + if (!host_api_info) { + qDebug() << "ASIO Error: Could not get host API info for device" << m_nDevOut; + return; + } + + bool isASIO = (host_api_info->type == paASIO); + + // Setup defaults for non-ASIO (MME, DirectSound, etc) + double outRate = 11025.0; + udata.actualChannelCount = 2; + unsigned long framesPerBuffer = 256; + + if(isASIO) { + outRate = 48000.0; + udata.actualChannelCount = 8; + framesPerBuffer = paFramesPerBufferUnspecified; + } - outParam.device=m_nDevOut; //Output device number - outParam.channelCount=2; //Number of analog channels - outParam.sampleFormat=paInt16; //Send short ints to PortAudio - outParam.suggestedLatency=device_info->defaultLowOutputLatency; - outParam.hostApiSpecificStreamInfo=NULL; + udata.nTRperiod = m_TRperiod; + udata.streamSampleRate = outRate; + + outParam.device = m_nDevOut; + outParam.channelCount = udata.actualChannelCount; + outParam.sampleFormat = paInt16; + + // --- SAFETY CHECK 3: Guard latency access --- + outParam.suggestedLatency = device_info->defaultLowOutputLatency; + outParam.hostApiSpecificStreamInfo = NULL; + + // ASIO Fallback Logic + paerr = Pa_IsFormatSupported(NULL, &outParam, outRate); + if(paerr < 0 && isASIO) { + udata.actualChannelCount = 2; + outParam.channelCount = 2; + paerr = Pa_IsFormatSupported(NULL, &outParam, outRate); + } + + // --- SAFETY CHECK 4: Final guard before opening --- + paerr = Pa_OpenStream(&outStream, NULL, &outParam, outRate, + framesPerBuffer, paClipOff, + d2aCallback, &udata); - udata.nTRperiod=m_TRperiod; - paerr=Pa_IsFormatSupported(NULL,&outParam,11025.0); - if(paerr<0) { - qDebug() << "PortAudio says requested output format not supported."; - qDebug() << paerr; - return; + if(paerr != paNoError) { + qDebug() << "Pa_OpenStream failed:" << Pa_GetErrorText(paerr); + return; } - paerr=Pa_OpenStream(&outStream, //Output stream - NULL, //No input parameters - &outParam, //Output parameters - 11025.0, //Sample rate - FRAMES_PER_BUFFER, //Frames per buffer - paClipOff, //No clipping - d2aCallback, //output callbeck routine - &udata); //userdata - - paerr=Pa_StartStream(outStream); - if(paerr<0) { - qDebug() << "Failed to start audio output stream."; - return; + + paerr = Pa_StartStream(outStream); + if(paerr != paNoError) { + qDebug() << "Pa_StartStream failed:" << Pa_GetErrorText(paerr); + return; } - const PaStreamInfo* p=Pa_GetStreamInfo(outStream); - outputLatency = p->outputLatency; - bool qe = quitExecution; - -//---------------------------------------------- Soundcard output loop - while (!qe) { - qe = quitExecution; - if (qe) break; - msleep(100); + + // --- SAFETY CHECK 5: Final stream info guard --- + const PaStreamInfo* p = Pa_GetStreamInfo(outStream); + if (p) { + outputLatency = p->outputLatency; } + + while (!quitExecution) { msleep(100); } + Pa_StopStream(outStream); Pa_CloseStream(outStream); } -void SoundOutThread::setOutputDevice(int n) //setOutputDevice() -{ - if (isRunning()) return; - this->m_nDevOut=n; -} - -void SoundOutThread::setPeriod(int n) -{ - m_TRperiod=n; -} +void SoundOutThread::setOutputDevice(int n) { this->m_nDevOut = n; } +void SoundOutThread::setPeriod(int n) { m_TRperiod = n; } diff --git a/map65/stdout_channel.h b/map65/stdout_channel.h new file mode 100644 index 00000000..21795986 --- /dev/null +++ b/map65/stdout_channel.h @@ -0,0 +1,43 @@ +// stdout_channel.h +#pragma once +#include "stdout_shared_memory.h" +#include <string> +#include <stdexcept> + +// Cross-platform event API implemented in win_event_shim.c or posix_event_shim.c +extern "C" { + void* win_create_event(); + int win_set_event(void*); + int win_reset_event(void*); + int win_wait_for_single_object(void*); + void win_close_event(void*); +} + +struct StdoutChannel +{ + StdoutSharedMemory shared; + void* eventHandle; + + StdoutChannel(const std::wstring &mappingName, + const std::wstring & /*eventName*/, + std::size_t bufferBytes) + : shared(mappingName, sizeof(StdoutSharedHeader) + bufferBytes), + eventHandle(nullptr) + { + // Cross-platform event creation + eventHandle = win_create_event(); + if (!eventHandle) + throw std::runtime_error("win_create_event failed for stdout channel"); + } + + ~StdoutChannel() + { + if (eventHandle) { + win_close_event(eventHandle); + eventHandle = nullptr; + } + } + + StdoutChannel(const StdoutChannel&) = delete; + StdoutChannel& operator=(const StdoutChannel&) = delete; +}; diff --git a/map65/txtune.cpp b/map65/txtune.cpp index b1d7fb71..4561cd23 100644 --- a/map65/txtune.cpp +++ b/map65/txtune.cpp @@ -1,11 +1,13 @@ #include "txtune.h" #include "ui_txtune.h" #include <QDebug> +#include <QByteArray> extern int txPower; extern int iqAmp; extern int iqPhase; extern bool bTune; +extern QByteArray g_TxTuneGeometry; TxTune::TxTune(QWidget *parent) : QDialog(parent), @@ -114,3 +116,10 @@ void TxTune::on_pbTune_clicked() ui->pbTune->setStyleSheet(""); } } + +void TxTune::closeEvent(QCloseEvent *e) +{ + g_TxTuneGeometry = saveGeometry(); + QWidget::closeEvent(e); +} + diff --git a/map65/txtune.h b/map65/txtune.h index e6001572..9fba45d9 100644 --- a/map65/txtune.h +++ b/map65/txtune.h @@ -16,8 +16,8 @@ public: ~TxTune(); public slots: - void accept(); - void reject(); + void accept() override; + void reject() override; private slots: void on_pwrSlider_valueChanged(int n); @@ -34,6 +34,7 @@ public: void set_txPower(int n); private: + virtual void closeEvent (QCloseEvent *) override; qint32 m_iqAmp1; qint32 m_iqAmp2; qint32 m_iqPha1; diff --git a/map65/widegraph.cpp b/map65/widegraph.cpp index 0004059e..ff3650b0 100644 --- a/map65/widegraph.cpp +++ b/map65/widegraph.cpp @@ -1,10 +1,18 @@ #include "widegraph.h" -#include <QSettings> +#include <algorithm> +#include <QCheckBox> +#include <QDateTime> +#include <QHBoxLayout> #include <QMessageBox> +#include <QPushButton> +#include <QSettings> +#include <QSpinBox> +#include <QVBoxLayout> #include "SettingsGroup.hpp" #include "ui_widegraph.h" +#include "globals.h" -#define NFFT 32768 +extern int g_sampleRate; WideGraph::WideGraph (QString const& settings_filename, QWidget * parent) : QDialog {parent}, @@ -37,8 +45,20 @@ WideGraph::WideGraph (QString const& settings_filename, QWidget * parent) int n = settings.value("FreqSpan",60).toInt(); int w = settings.value("PlotWidth",1000).toInt(); ui->freqSpanSpinBox->setValue(n); + + if (g_sampleRate == 96000 || g_sampleRate == 95238) + setFreqSpanLimits(60, 90); + else + setFreqSpanLimits(60, 190); + updateSpanFromSpinbox(); + + extern int g_sampleRate; // at top of widegraph.cpp ui->widePlot->setNSpan(n); - int nbpp = n * 32768.0/(w*96.0) + 0.5; + double sr_kHz = g_sampleRate / 1000.0; // 96.0 or 192.0 + int sr_display = int(sr_kHz + 0.5); + ui->srValueLabel->setText(QString::number(sr_display)); + int nbpp = int(n * g_activeNfft / (w * sr_kHz) + 0.5); + if (nbpp < 1) nbpp = 1; // safety ui->widePlot->setBinsPerPixel(nbpp); m_waterfallAvg = settings.value("WaterfallAvg",10).toInt(); ui->waterfallAvgSpinBox->setValue(m_waterfallAvg); @@ -49,6 +69,108 @@ WideGraph::WideGraph (QString const& settings_filename, QWidget * parent) ui->fCenterLineEdit->setText(QString::number(m_dForceCenterFreq)); m_bLockTxRx=settings.value("LockTxRx",false).toBool(); ui->cbLockTxRx->setChecked(m_bLockTxRx); + + // Decoded-callsign overlay (N6NU 2026-05-12). Mirrors QMAP feature. + // INI keys: WideGraph/decode_labels_enabled (default true), + // WideGraph/decode_label_periods (default 5). + m_decodeLabelsEnabled = settings.value("decode_labels_enabled", true).toBool(); + m_decodeLabelPeriods = settings.value("decode_label_periods", 5).toInt(); + if (m_decodeLabelPeriods < 1) m_decodeLabelPeriods = 1; + if (m_decodeLabelPeriods > 5) m_decodeLabelPeriods = 5; + // Overlay transparency preset. Snap stored value to one of the + // three offered presets so a hand-edited INI can't desync the + // View menu's checked state. + m_decodeLabelAlpha = settings.value("decode_label_alpha", 255).toInt(); + if (m_decodeLabelAlpha <= 187) m_decodeLabelAlpha = 175; + else if (m_decodeLabelAlpha <= 210) m_decodeLabelAlpha = 200; + else if (m_decodeLabelAlpha <= 237) m_decodeLabelAlpha = 220; + else m_decodeLabelAlpha = 255; + if (ui && ui->widePlot) ui->widePlot->setDecodeLabelAlpha(m_decodeLabelAlpha); + { + const int fs = settings.value("decode_label_font_size", + static_cast<int>(DecodeLabelFontSize::Normal)).toInt(); + if (fs == 7 || fs == 8 || fs == 10 || fs == 12) { + m_decodeFontSize = static_cast<DecodeLabelFontSize>(fs); + } else { + m_decodeFontSize = DecodeLabelFontSize::Normal; + } + if (ui && ui->widePlot) ui->widePlot->setDecodeLabelFontSize(m_decodeFontSize); + } + { + const int pos = settings.value("decode_label_position", + static_cast<int>(DecodeLabelPosition::Top)).toInt(); + m_decodeLabelPosition = (pos == static_cast<int>(DecodeLabelPosition::Bottom)) + ? DecodeLabelPosition::Bottom + : DecodeLabelPosition::Top; + if (ui && ui->widePlot) ui->widePlot->setDecodeLabelPosition(m_decodeLabelPosition); + } + connect(&m_ageTimer, &QTimer::timeout, this, &WideGraph::ageDecodeLabels); + m_ageTimer.start(1000); // 1 Hz prune + + // -- Decoded-callsign overlay controls -- QMAP port (DG2YCB 2026-05-13) + // Three widgets appended to the existing horizontalLayout_3 row + // (FreqSpan / WaterfallAvg / etc.) so they share the same line: + // [? Show callsigns] [age N x TR] [Clear] + // Persisted to the .ini under [WideGraph]/{decode_labels_enabled, + // decode_label_periods}. + { + auto* showCb = new QCheckBox("Show callsigns", this); + showCb->setObjectName("decodeLabelShowCb"); + showCb->setChecked(m_decodeLabelsEnabled); + showCb->setToolTip("Overlay decoded callsigns on the waterfall at " + "their decoded frequency. Q65 labels render " + "yellow, JT65 labels cyan. Uncheck to hide all " + "labels (existing entries are cleared)."); + connect(showCb, &QCheckBox::toggled, + this, &WideGraph::setDecodeLabelsEnabled); + // Keep the row checkbox in sync when the View-menu mirror flips it. + connect(this, &WideGraph::decodeLabelsEnabledChanged, + showCb, &QCheckBox::setChecked); + + auto* ageSpin = new QSpinBox(this); + ageSpin->setObjectName("decodeLabelAgeSpin"); + ageSpin->setRange(1, 5); + ageSpin->setValue(m_decodeLabelPeriods); + ageSpin->setSuffix(" x TR"); + ageSpin->setToolTip("How many TR periods a decoded callsign label " + "stays on the waterfall after its last fresh " + "decode. Default 5 = 5 minutes for Q65-60."); + connect(ageSpin, QOverload<int>::of(&QSpinBox::valueChanged), + this, [this](int v) { + m_decodeLabelPeriods = v; + ageDecodeLabels(); // immediate sweep with new lifetime + }); + + auto* clearBtn = new QPushButton("Clear", this); + clearBtn->setObjectName("decodeLabelClearBtn"); + clearBtn->setToolTip("Remove all decoded callsign labels from the " + "waterfall. Existing decodes will re-appear " + "if MAP65 decodes them again."); + connect(clearBtn, &QPushButton::clicked, this, [this]() { + m_decodeLabels.clear(); + if (ui && ui->widePlot) ui->widePlot->setDecodeLabels(m_decodeLabels); + }); + + // Insert into the existing controls row (horizontalLayout_3) just + // before its trailing stretch, so the new widgets share the line + // with FreqSpan/WaterfallAvg instead of wrapping below. + if (auto* row = findChild<QHBoxLayout*>("horizontalLayout_3")) { + row->addWidget(showCb); + row->addWidget(ageSpin); + row->addWidget(clearBtn); + } else { + // Fallback: own row appended to inner verticalLayout. + auto* row2 = new QHBoxLayout; + row2->setContentsMargins(0, 0, 0, 0); + row2->addWidget(showCb); + row2->addWidget(ageSpin); + row2->addWidget(clearBtn); + row2->addStretch(); + if (auto* inner = findChild<QVBoxLayout*>("verticalLayout")) { + inner->addLayout(row2); + } + } + } } WideGraph::~WideGraph() @@ -63,6 +185,7 @@ void WideGraph::resizeEvent(QResizeEvent* ) //resizeEvent() int w = size().width(); int h = size().height(); ui->labFreq->setGeometry(QRect(w-256,h-100,227,41)); + updateSpanFromSpinbox(); } void WideGraph::saveSettings() @@ -83,12 +206,126 @@ void WideGraph::saveSettings() settings.setValue("ForceCenterFreqBool",m_bForceCenterFreq); settings.setValue("ForceCenterFreqMHz",m_dForceCenterFreq); settings.setValue("LockTxRx",m_bLockTxRx); + settings.setValue("decode_labels_enabled", m_decodeLabelsEnabled); + settings.setValue("decode_label_periods", m_decodeLabelPeriods); + settings.setValue("decode_label_alpha", m_decodeLabelAlpha); + settings.setValue("decode_label_font_size", static_cast<int>(m_decodeFontSize)); + settings.setValue("decode_label_position", static_cast<int>(m_decodeLabelPosition)); +} + +void WideGraph::addDecodeLabel(double freq_khz, const QString& callsign, + bool is_jt65, bool mode_reliable, + bool freq_reliable) +{ + if (callsign.isEmpty()) return; + if (!m_decodeLabelsEnabled) return; + const qint64 now = QDateTime::currentMSecsSinceEpoch(); + for (auto& lab : m_decodeLabels) { + if (lab.callsign == callsign) { + lab.last_seen_ms = now; + // Only overwrite freq when the caller has sub-kHz precision. + // The "&" bandmap tap only has 3-char integer-kHz precision + // (display.f90 cfreq0 is character(3) � no ndf field), so it + // would otherwise stomp on a precise "!" tick that already + // includes ndf, leaving the tick up to ~500 Hz off the signal. + if (freq_reliable) lab.freq_khz = freq_khz; + // Only overwrite the mode flag when the caller knows for sure. + // The "&" bandmap-line tap has no cmode in its payload, so it + // would otherwise stomp on an authoritative JT65 mark from the + // "!" decoder tap and flip the label color. + if (mode_reliable) lab.is_jt65 = is_jt65; + ++lab.hits; + if (ui && ui->widePlot) ui->widePlot->setDecodeLabels(m_decodeLabels); + return; + } + } + if (m_decodeLabels.size() >= kDecodeLabelMax) { + m_decodeLabels.removeFirst(); + } + m_decodeLabels.append(DecodeLabel{freq_khz, callsign, now, 1, is_jt65}); + if (ui && ui->widePlot) ui->widePlot->setDecodeLabels(m_decodeLabels); +} + +void WideGraph::clearDecodeLabels() +{ + if (m_decodeLabels.isEmpty()) return; + m_decodeLabels.clear(); + if (ui && ui->widePlot) ui->widePlot->setDecodeLabels(m_decodeLabels); +} + +void WideGraph::ageDecodeLabels() +{ + if (m_decodeLabels.isEmpty()) return; + const double trp = (m_TRperiod > 0) ? m_TRperiod : 60.0; + const qint64 ttl_ms = static_cast<qint64>(trp * m_decodeLabelPeriods * 1000.0); + const qint64 cutoff = QDateTime::currentMSecsSinceEpoch() - ttl_ms; + const int before = m_decodeLabels.size(); + m_decodeLabels.erase( + std::remove_if(m_decodeLabels.begin(), m_decodeLabels.end(), + [cutoff](const DecodeLabel& l) { + return l.last_seen_ms < cutoff; + }), + m_decodeLabels.end()); + if (m_decodeLabels.size() != before && ui && ui->widePlot) { + ui->widePlot->setDecodeLabels(m_decodeLabels); + } +} + +void WideGraph::setDecodeLabelsEnabled(bool on) +{ + if (m_decodeLabelsEnabled == on) return; + m_decodeLabelsEnabled = on; + if (!on) { + m_decodeLabels.clear(); + if (ui && ui->widePlot) ui->widePlot->setDecodeLabels(m_decodeLabels); + } + // Persist immediately so the choice survives a crash before saveSettings runs. + QSettings settings {m_settings_filename, QSettings::IniFormat}; + SettingsGroup g {&settings, "WideGraph"}; + settings.setValue("decode_labels_enabled", on); + emit decodeLabelsEnabledChanged(on); +} + +void WideGraph::setDecodeLabelAlpha(int alpha) +{ + // Snap to the three offered presets so a stale or hand-edited INI + // can't break the View menu's exclusive group. + if (alpha <= 187) alpha = 175; + else if (alpha <= 210) alpha = 200; + else if (alpha <= 237) alpha = 220; + else alpha = 255; + if (m_decodeLabelAlpha == alpha) return; + m_decodeLabelAlpha = alpha; + if (ui && ui->widePlot) ui->widePlot->setDecodeLabelAlpha(alpha); + QSettings settings {m_settings_filename, QSettings::IniFormat}; + SettingsGroup g {&settings, "WideGraph"}; + settings.setValue("decode_label_alpha", alpha); +} + +void WideGraph::setDecodeLabelFontSize(DecodeLabelFontSize sz) +{ + if (m_decodeFontSize == sz) return; + m_decodeFontSize = sz; + if (ui && ui->widePlot) ui->widePlot->setDecodeLabelFontSize(sz); + QSettings settings {m_settings_filename, QSettings::IniFormat}; + SettingsGroup g {&settings, "WideGraph"}; + settings.setValue("decode_label_font_size", static_cast<int>(sz)); +} + +void WideGraph::setDecodeLabelPosition(DecodeLabelPosition p) +{ + if (m_decodeLabelPosition == p) return; + m_decodeLabelPosition = p; + if (ui && ui->widePlot) ui->widePlot->setDecodeLabelPosition(p); + QSettings settings {m_settings_filename, QSettings::IniFormat}; + SettingsGroup g {&settings, "WideGraph"}; + settings.setValue("decode_label_position", static_cast<int>(p)); } void WideGraph::dataSink2(float s[], int nkhz, int ihsym, int ndiskdata, - uchar lstrong[]) + uchar lstrong[], int lstrongSize) { - static float splot[NFFT]; + static std::vector<float> splot; float swide[2048]; float smax; double df; @@ -96,8 +333,10 @@ void WideGraph::dataSink2(float s[], int nkhz, int ihsym, int ndiskdata, static int n=0; static int nkhz0=-999; static int ntrz=0; - - df = m_fSample/32768.0; + + if ((int)splot.size() != g_activeNfft) + splot.assign(g_activeNfft, 0.0f); + df = double(g_sampleRate) / double(g_activeNfft); if(nkhz != nkhz0) { ui->widePlot->setNkhz(nkhz); //Why do we need both? ui->widePlot->SetCenterFreq(nkhz); //Why do we need both? @@ -107,35 +346,59 @@ void WideGraph::dataSink2(float s[], int nkhz, int ihsym, int ndiskdata, //Average spectra over specified number, m_waterfallAvg if (n==0) { - for (int i=0; i<NFFT; i++) + for (int i=0; i<g_activeNfft; i++) splot[i]=s[i]; } else { - for (int i=0; i<NFFT; i++) + for (int i=0; i<g_activeNfft; i++) splot[i] += s[i]; } n++; if (n>=m_waterfallAvg) { - for (int i=0; i<NFFT; i++) + for (int i=0; i<g_activeNfft; i++) splot[i] /= n; //Normalize the average n=0; int w=ui->widePlot->plotWidth(); qint64 sf = nkhz + ui->widePlot->freqOffset() - 0.5*w*nbpp*df/1000.0; - if(sf != ui->widePlot->startFreq()) ui->widePlot->SetStartFreq(sf); - int i0=16384.0+(ui->widePlot->startFreq()-nkhz+1.27046+0.001*m_fCal) * - 1000.0/df + 0.5; + if (sf != ui->widePlot->startFreq()) + ui->widePlot->SetStartFreq(sf); + + int i0 = (g_activeNfft/2) + + (ui->widePlot->startFreq() - nkhz + 1.27046 + 0.001*m_fCal) * 1000.0/df + + 0.5; + + // Clamp i0 into [0, g_activeNfft-1] + if (i0 < 0) i0 = 0; + if (i0 > g_activeNfft-1) i0 = g_activeNfft-1; + int i=i0; - for (int j=0; j<2048; j++) { - smax=0; - for (int k=0; k<nbpp; k++) { - i++; + + // How many bins can we safely consume? + int maxBins = g_activeNfft - 1 - i0; + int maxCols = maxBins > 0 ? maxBins / nbpp : 0; + if (maxCols > 2048) maxCols = 2048; + + for (int j = 0; j < maxCols; ++j) { + smax = 0.0f; + for (int k = 0; k < nbpp; ++k) { + ++i; + if (i >= g_activeNfft) break; if(splot[i]>smax) smax=splot[i]; } swide[j]=smax; - if(lstrong[1 + i/32]!=0) swide[j]=-smax; //Tag strong signals + + int binsPerStrongFlag = std::max(1, g_activeNfft / lstrongSize); + int li = 1 + i / binsPerStrongFlag; + if (li >= 0 && li < lstrongSize && lstrong[li] != 0) + swide[j] = -smax; } + // Optionally zero any remaining swide entries if j < 2048 + for (int j = maxCols; j < 2048; ++j) + swide[j] = 0.0f; + + // Time according to this computer qint64 ms = QDateTime::currentMSecsSinceEpoch() % 86400000; int ntr = (ms/1000) % m_TRperiod; @@ -144,12 +407,12 @@ void WideGraph::dataSink2(float s[], int nkhz, int ihsym, int ndiskdata, for (int i=0; i<2048; i++) { swide[i] = 1.e30; } - for (int i=0; i<32768; i++) { + for (int i=0; i<g_activeNfft; i++) { splot[i] = 1.e30; } } ntrz=ntr; - ui->widePlot->draw(swide,i0,splot); + ui->widePlot->draw(swide,i0,splot.data()); } } @@ -158,15 +421,19 @@ void WideGraph::on_freqOffsetSpinBox_valueChanged(int f) ui->widePlot->SetFreqOffset(f); } -void WideGraph::on_freqSpanSpinBox_valueChanged(int n) +void WideGraph::on_freqSpanSpinBox_valueChanged(int) { - ui->widePlot->setNSpan(n); - int w = ui->widePlot->plotWidth(); - int nbpp = n * 32768.0/(w*96.0) + 0.5; - if(nbpp < 1) nbpp=1; - if(w > 0) { - ui->widePlot->setBinsPerPixel(nbpp); - } + updateSpanFromSpinbox(); +} + +void WideGraph::setFreqSpanLimits(int min, int max) +{ + ui->freqSpanSpinBox->setMinimum(min); + ui->freqSpanSpinBox->setMaximum(max); + + int v = ui->freqSpanSpinBox->value(); + if (v < min) ui->freqSpanSpinBox->setValue(min); + if (v > max) ui->freqSpanSpinBox->setValue(max); } void WideGraph::on_waterfallAvgSpinBox_valueChanged(int n) @@ -269,11 +536,6 @@ void WideGraph::setPalette(QString palette) { ui->widePlot->setPalette(palette); } -void WideGraph::setFsample(int n) -{ - m_fSample=n; - ui->widePlot->setFsample(n); -} void WideGraph::setMode65(int n) { @@ -357,7 +619,7 @@ void WideGraph::rx570() void WideGraph::tx570() { - if(m_bForceCenterFreq) datcom_.fcenter=m_dForceCenterFreq; + if(m_bForceCenterFreq) setFcenter(m_dForceCenterFreq); m_bIQxt=true; double f=ui->widePlot->txFreq(); // double f1=m_mult570Tx*(1.0+0.000001*m_cal570) * f; @@ -385,3 +647,21 @@ void WideGraph::enableSetRxHardware(bool b) { ui->pbSetRxHardware->setEnabled(b); } + +void WideGraph::updateSpanFromSpinbox() +{ + int n = ui->freqSpanSpinBox->value(); + + // Update NSpan + ui->widePlot->setNSpan(n); + + // Recompute bins-per-pixel + int w = ui->widePlot->plotWidth(); + int nbpp = int(n * g_activeNfft / (w * (g_sampleRate / 1000.0)) + 0.5); + if (nbpp < 1) nbpp = 1; + + if (w > 0) + ui->widePlot->setBinsPerPixel(nbpp); +} + + diff --git a/map65/widegraph.h b/map65/widegraph.h index ea740bb5..e96cb2c2 100644 --- a/map65/widegraph.h +++ b/map65/widegraph.h @@ -2,6 +2,11 @@ #define WIDEGRAPH_H #include <QDialog> +#include <QList> +#include <QString> +#include <QTimer> + +#include "decode_label.h" namespace Ui { class WideGraph; @@ -16,7 +21,7 @@ public: ~WideGraph(); void dataSink2(float s[], int nkhz, int ihsym, int ndiskdata, - uchar lstrong[]); + uchar lstrong[], int lstrongSize); int QSOfreq(); int nSpan(); int nStartFreq(); @@ -28,7 +33,6 @@ public: void setTol(int n); void setFcal(int n); void setPalette(QString palette); - void setFsample(int n); void setMode65(int n); void setPeriod(int n); void setDecodeFinished(); @@ -37,17 +41,59 @@ public: void tx570(); void updateFreqLabel(); void enableSetRxHardware(bool b); + void setFreqSpanLimits(int min, int max); + void updateSpanFromSpinbox(); + + + // Decoded-callsign overlay (N6NU 2026-05-12, port of QMAP feature). + // mainwindow calls addDecodeLabel for each decoded line (after + // parsing the freq + sender callsign out of the "!"-prefix line); + // the list ages out after m_decodeLabelPeriods ? TR period of no + // refresh and gets pushed to the plotter for rendering. + // mode_reliable=false: caller has no authoritative mode (e.g. "&" + // bandmap line, where display.f90 writes no cmode). On dedup, the + // existing label's is_jt65 is preserved. For brand-new labels the + // caller's is_jt65 is used as a best-guess seed. + // freq_reliable=false: caller only has integer-kHz precision (e.g. + // "&" bandmap line — cfreq0 is 3 chars, no ndf). On dedup, the + // existing label's freq_khz is preserved so a precise "!" tick + // is not stomped by a later imprecise "&" refresh. + void addDecodeLabel(double freq_khz, const QString& callsign, + bool is_jt65, bool mode_reliable = true, + bool freq_reliable = true); + void clearDecodeLabels(); + bool decodeLabelsEnabled() const { return m_decodeLabelsEnabled; } + void setDecodeLabelsEnabled(bool on); + // Overlay transparency. View menu offers None=255 / Medium=200 / + // High=175; persisted in [WideGraph]/decode_label_alpha. + int decodeLabelAlpha() const { return m_decodeLabelAlpha; } + void setDecodeLabelAlpha(int alpha); + + // Overlay font size. View menu offers Small=7 / Normal=8 (default) / + // Medium=10 / Large=12; persisted in [WideGraph]/decode_label_font_size. + DecodeLabelFontSize decodeLabelFontSize() const { return m_decodeFontSize; } + void setDecodeLabelFontSize(DecodeLabelFontSize sz); + + // Overlay anchor position. View menu offers Top (legacy) and Bottom + // (above divider); persisted in [WideGraph]/decode_label_position. + DecodeLabelPosition decodeLabelPosition() const { return m_decodeLabelPosition; } + void setDecodeLabelPosition(DecodeLabelPosition p); qint32 m_qsoFreq; signals: void freezeDecode2(int n); void f11f12(int n); + // Mirror toggle: WideGraph row checkbox ? MainWindow View menu. + void decodeLabelsEnabledChanged(bool on); public slots: void wideFreezeDecode(int n); void initIQplus(); +private slots: + void ageDecodeLabels(); + protected: virtual void keyPressEvent( QKeyEvent *e ); void resizeEvent(QResizeEvent* event); @@ -81,9 +127,21 @@ private: bool m_bIQxt; qint32 m_waterfallAvg; qint32 m_fCal; - qint32 m_fSample; qint32 m_mode65; qint32 m_TRperiod=60; + + // Decoded-callsign overlay state. + QList<DecodeLabel> m_decodeLabels; + bool m_decodeLabelsEnabled {true}; + int m_decodeLabelPeriods {5}; // disappear after N×TRperiod of no decode + // Overlay opacity preset (0..255). UI offers None=255 / Medium=200 / + // High=175 in the View menu. + int m_decodeLabelAlpha {255}; + // Overlay font size (Small=7 / Normal=8 default / Medium=10 / Large=12). + DecodeLabelFontSize m_decodeFontSize {DecodeLabelFontSize::Normal}; + DecodeLabelPosition m_decodeLabelPosition {DecodeLabelPosition::Top}; + QTimer m_ageTimer; + static constexpr int kDecodeLabelMax = 200; }; extern int set570(double freq_MHz); diff --git a/map65/widegraph.ui b/map65/widegraph.ui index 38f90d47..ca14671a 100644 --- a/map65/widegraph.ui +++ b/map65/widegraph.ui @@ -74,6 +74,32 @@ Tx: 144.127.317</string> <layout class="QVBoxLayout" name="verticalLayout"> <item> <layout class="QHBoxLayout" name="horizontalLayout_3"> + <item> + <widget class="QLabel" name="srLabel"> + <property name="text"> + <string>SR</string> + </property> + <property name="alignment"> + <set>Qt::AlignRight|Qt::AlignVCenter</set> + </property> + </widget> + </item> + <item> + <widget class="QLabel" name="srValueLabel"> + <property name="minimumSize"> + <size> + <width>30</width> + <height>0</height> + </size> + </property> + <property name="text"> + <string>96</string> + </property> + <property name="alignment"> + <set>Qt::AlignLeft|Qt::AlignVCenter</set> + </property> + </widget> + </item> <item> <spacer name="horizontalSpacer_2"> <property name="orientation"> @@ -157,7 +183,7 @@ Tx: 144.127.317</string> <number>5</number> </property> <property name="maximum"> - <number>90</number> + <number>190</number> </property> <property name="singleStep"> <number>5</number> diff --git a/map65/wsjt.ico b/map65/wsjt.ico Binary files differindex 8a55550f..3f736a9c 100644 --- a/map65/wsjt.ico +++ b/map65/wsjt.ico |
