diff options
259 files changed, 16430 insertions, 8734 deletions
diff --git a/.github/scripts/audit-staged-dll-imports-windows.sh b/.github/scripts/audit-staged-dll-imports-windows.sh new file mode 100644 index 00000000..b16adaca --- /dev/null +++ b/.github/scripts/audit-staged-dll-imports-windows.sh @@ -0,0 +1,74 @@ +#!/usr/bin/env bash +set -u + +stage_bin="${1:?usage: audit-staged-dll-imports-windows.sh <stage-bin> <exe> [exe...]}" +shift + +if [ ! -d "$stage_bin" ]; then + echo "::error::staged bin directory not found: $stage_bin" + exit 1 +fi + +if [ "$#" -eq 0 ]; then + echo "::error::no executables supplied for DLL import audit" + exit 1 +fi + +fail=0 + +staged_lower=$( + for dll in "$stage_bin"/*.dll "$stage_bin"/*.DLL; do + [ -e "$dll" ] || continue + basename "$dll" | tr '[:upper:]' '[:lower:]' + done | sort -u +) + +echo "staged DLLs in $stage_bin:" +if [ -n "$staged_lower" ]; then + echo "$staged_lower" +else + echo "(none)" +fi + +for exe in "$@"; do + if [ ! -f "$exe" ]; then + echo "::error::executable not found for DLL import audit: $exe" + fail=1 + continue + fi + + echo "::group::DLL imports for $exe" + imports=$( + objdump -p "$exe" | + awk '/DLL Name:/ {print $3}' | + sort -u + ) + + if [ -n "$imports" ]; then + echo "$imports" + else + echo "(none)" + fi + + high_risk=$( + echo "$imports" | + awk '{ lower=tolower($0); if (lower ~ /^(libgomp|libgfortran|libgcc_s|libquadmath|libportaudio|libhamlib|libfftw|qt5.*\.dll)/) print lower }' | + sort -u + ) + + for dll in $high_risk; do + if ! printf '%s\n' "$staged_lower" | awk -v wanted="$dll" '$0 == wanted { found=1 } END { exit found ? 0 : 1 }'; then + echo "::error::$exe imports $dll, but $dll is missing from $stage_bin" + fail=1 + fi + done + echo "::endgroup::" +done + +if [ "$fail" -ne 0 ]; then + echo "::group::staged bin contents" + ls -la "$stage_bin" + echo "::endgroup::" +fi + +exit "$fail" diff --git a/.github/scripts/build-boost-macos.sh b/.github/scripts/build-boost-macos.sh new file mode 100755 index 00000000..06e9de1a --- /dev/null +++ b/.github/scripts/build-boost-macos.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [ "$#" -ne 4 ]; then + echo "Usage: build-boost-macos.sh VERSION ARCH DEPLOYMENT_TARGET PREFIX" >&2 + exit 2 +fi + +version="$1" +arch="$2" +deployment_target="$3" +prefix="$4" +version_underscores=${version//./_} +boost_arch=x86 + +if [ "$arch" = "arm64" ]; then + boost_arch=arm +fi + +curl -L --fail --retry 5 --retry-delay 10 -o boost.tar.bz2 "https://archives.boost.io/release/${version}/source/boost_${version_underscores}.tar.bz2" +tar -xjf boost.tar.bz2 +cd "boost_${version_underscores}" + +./bootstrap.sh --prefix="$prefix" --with-libraries=log +./b2 -j"$(sysctl -n hw.ncpu)" \ + toolset=clang \ + variant=release \ + link=shared \ + runtime-link=shared \ + threading=multi \ + cxxstd=11 \ + cflags="-mmacosx-version-min=${deployment_target}" \ + cxxflags="-mmacosx-version-min=${deployment_target}" \ + linkflags="-mmacosx-version-min=${deployment_target}" \ + architecture="$boost_arch" \ + address-model=64 \ + install diff --git a/.github/scripts/build-fftw-macos.sh b/.github/scripts/build-fftw-macos.sh new file mode 100755 index 00000000..6ae1505d --- /dev/null +++ b/.github/scripts/build-fftw-macos.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [ "$#" -ne 3 ]; then + echo "Usage: build-fftw-macos.sh VERSION DEPLOYMENT_TARGET PREFIX" >&2 + exit 2 +fi + +version="$1" +deployment_target="$2" +prefix="$3" + +curl -L --fail --retry 5 --retry-delay 10 -o fftw.tar.gz "https://www.fftw.org/fftw-${version}.tar.gz" +tar -xzf fftw.tar.gz +cd "fftw-${version}" + +./configure \ + --prefix="$prefix" \ + --enable-single \ + --enable-threads \ + --enable-shared --disable-static \ + CFLAGS="-mmacosx-version-min=${deployment_target}" \ + LDFLAGS="-mmacosx-version-min=${deployment_target}" +make -j"$(sysctl -n hw.ncpu)" +make install diff --git a/.github/scripts/build-hamlib-macos.sh b/.github/scripts/build-hamlib-macos.sh new file mode 100755 index 00000000..637492e4 --- /dev/null +++ b/.github/scripts/build-hamlib-macos.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [ "$#" -ne 3 ]; then + echo "Usage: build-hamlib-macos.sh BRANCH DEPLOYMENT_TARGET PREFIX" >&2 + exit 2 +fi + +branch="$1" +deployment_target="$2" +prefix="$3" + +git clone --depth 1 --branch "$branch" \ + https://github.com/Hamlib/Hamlib.git hamlib-src +cd hamlib-src +./bootstrap +./configure \ + --prefix="$prefix" \ + --disable-shared --enable-static \ + --without-cxx-binding \ + CFLAGS="-mmacosx-version-min=${deployment_target}" \ + LDFLAGS="-mmacosx-version-min=${deployment_target}" +make -j"$(sysctl -n hw.ncpu)" +make install diff --git a/.github/scripts/build-libusb-macos.sh b/.github/scripts/build-libusb-macos.sh new file mode 100755 index 00000000..928962db --- /dev/null +++ b/.github/scripts/build-libusb-macos.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [ "$#" -ne 3 ]; then + echo "Usage: build-libusb-macos.sh VERSION DEPLOYMENT_TARGET PREFIX" >&2 + exit 2 +fi + +version="$1" +deployment_target="$2" +prefix="$3" + +curl -L --fail --retry 5 --retry-delay 10 -o libusb.tar.bz2 "https://github.com/libusb/libusb/releases/download/v${version}/libusb-${version}.tar.bz2" +tar -xjf libusb.tar.bz2 +cd "libusb-${version}" + +./configure \ + --prefix="$prefix" \ + --enable-shared --disable-static \ + CFLAGS="-mmacosx-version-min=${deployment_target}" \ + LDFLAGS="-mmacosx-version-min=${deployment_target}" +make -j"$(sysctl -n hw.ncpu)" +make install diff --git a/.github/scripts/build-portaudio-macos.sh b/.github/scripts/build-portaudio-macos.sh new file mode 100755 index 00000000..c3a31b4d --- /dev/null +++ b/.github/scripts/build-portaudio-macos.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [ "$#" -ne 3 ]; then + echo "Usage: build-portaudio-macos.sh VERSION DEPLOYMENT_TARGET PREFIX" >&2 + exit 2 +fi + +version="$1" +deployment_target="$2" +prefix="$3" + +case "$version" in + 19.7.0) + archive_name="pa_stable_v190700_20210406" + source_url="https://files.portaudio.com/archives/${archive_name}.tgz" + source_dir="portaudio" + ;; + *) + echo "Unsupported PortAudio version: $version" >&2 + exit 2 + ;; +esac + +curl -L --fail --retry 5 --retry-delay 10 -o portaudio.tgz "$source_url" +tar -xzf portaudio.tgz +cd "$source_dir" + +# PortAudio 19.7.0's generated configure script overwrites caller CFLAGS on +# macOS, hardcodes a host-derived deployment target, and enables -Werror. +# Patch the generated script so CI controls the deployment target and modern +# Apple Clang warnings do not break a pinned third-party runtime build. +sed \ + -e 's/ -Wno-deprecated -Werror/ -Wno-deprecated/g' \ + -e "s/mac_version_min=\"-mmacosx-version-min=[0-9.]*\"/mac_version_min=\"-mmacosx-version-min=${deployment_target}\"/g" \ + configure > configure.tmp +mv configure.tmp configure +chmod +x configure + +./configure \ + --prefix="$prefix" \ + --enable-shared --disable-static +make -j"$(sysctl -n hw.ncpu)" +make install diff --git a/.github/scripts/build-qt-macos.sh b/.github/scripts/build-qt-macos.sh new file mode 100755 index 00000000..3bc0434b --- /dev/null +++ b/.github/scripts/build-qt-macos.sh @@ -0,0 +1,169 @@ +#!/usr/bin/env bash +set -euo pipefail + +script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)" +# shellcheck source=macos-qt-cache-key.sh +. "${script_dir}/macos-qt-cache-key.sh" + +usage() { + cat <<'USAGE' +Usage: build-qt-macos.sh --arch ARCH --deployment-target VERSION --prefix PATH + +Builds the pinned dynamic Qt 5 source package for the requested macOS tuple. +USAGE +} + +arch="" +deployment_target="" +prefix="" + +while [ "$#" -gt 0 ]; do + case "$1" in + --arch) + arch="$2" + shift 2 + ;; + --deployment-target) + deployment_target="$2" + shift 2 + ;; + --prefix) + prefix="$2" + shift 2 + ;; + --help|-h) + usage + exit 0 + ;; + *) + echo "Unknown argument: $1" >&2 + usage >&2 + exit 2 + ;; + esac +done + +if [ -z "$arch" ] || [ -z "$deployment_target" ] || [ -z "$prefix" ]; then + usage >&2 + exit 2 +fi + +case "$arch" in + arm64|x86_64) + ;; + *) + echo "Unsupported macOS Qt architecture: $arch" >&2 + exit 2 + ;; +esac + +case "${arch}:${deployment_target}" in + arm64:11.0|x86_64:10.13) + ;; + *) + echo "Unsupported macOS Qt deployment tuple: arch=${arch}, deployment_target=${deployment_target}" >&2 + exit 2 + ;; +esac + +if [ -e "$prefix" ] && [ -n "$(ls -A "$prefix")" ]; then + echo "Qt install prefix already exists and is not empty: $prefix" >&2 + exit 1 +fi + +build_root="${RUNNER_TEMP:-${PWD}}/qt-${QT_VERSION}-${arch}-build" +archive="${build_root}/qt-everywhere-opensource-src-${QT_VERSION}.tar.xz" + +mkdir -p "$build_root" "$prefix" + +echo "Downloading Qt ${QT_VERSION} from ${QT_SOURCE_URL}" +curl -L --fail --retry 5 --retry-delay 10 -o "$archive" "$QT_SOURCE_URL" + +actual_sha256="$(macos_qt_sha256_file "$archive")" +if [ "$actual_sha256" != "$QT_SOURCE_SHA256" ]; then + echo "Qt source SHA-256 mismatch" >&2 + echo "Expected: $QT_SOURCE_SHA256" >&2 + echo "Actual: $actual_sha256" >&2 + exit 1 +fi + +tar -xf "$archive" -C "$build_root" +source_dir="${build_root}/qt-everywhere-src-${QT_VERSION}" +if [ ! -d "$source_dir" ]; then + source_dir="${build_root}/qt-everywhere-opensource-src-${QT_VERSION}" +fi +if [ ! -d "$source_dir" ]; then + echo "Could not locate extracted Qt source directory under $build_root" >&2 + exit 1 +fi +cd "$source_dir" + +export MACOSX_DEPLOYMENT_TARGET="$deployment_target" +export QMAKE_MACOSX_DEPLOYMENT_TARGET="$deployment_target" + +configure_args=( + -opensource + -confirm-license + -release + -shared + -prefix "$prefix" + -nomake examples + -nomake tests + -qt-zlib + -qt-libpng + -qt-libjpeg + -qt-pcre + -qt-harfbuzz + -qt-sqlite + -securetransport + -skip qt3d + -skip qtactiveqt + -skip qtandroidextras + -skip qtcharts + -skip qtconnectivity + -skip qtdatavis3d + -skip qtdeclarative + -skip qtdoc + -skip qtgamepad + -skip qtgraphicaleffects + -skip qtimageformats + -skip qtlocation + -skip qtlottie + -skip qtmacextras + -skip qtnetworkauth + -skip qtpurchasing + -skip qtquick3d + -skip qtquickcontrols + -skip qtquickcontrols2 + -skip qtquicktimeline + -skip qtremoteobjects + -skip qtscript + -skip qtscxml + -skip qtsensors + -skip qtserialbus + -skip qtspeech + -skip qtvirtualkeyboard + -skip qtwayland + -skip qtwebchannel + -skip qtwebengine + -skip qtwebglplugin + -skip qtwebview + -skip qtx11extras + -skip qtxmlpatterns + "QMAKE_MACOSX_DEPLOYMENT_TARGET=${deployment_target}" + "QMAKE_APPLE_DEVICE_ARCHS=${arch}" +) + +echo "Configuring Qt ${QT_VERSION} for ${arch}, deployment target ${deployment_target}" +./configure "${configure_args[@]}" + +jobs="$(sysctl -n hw.ncpu)" +make -j"$jobs" +make install + +"${prefix}/bin/qmake" -query +"${prefix}/bin/qmake" -query QT_VERSION | awk -v expected="$QT_VERSION" ' + $0 != expected { + printf "Expected qmake QT_VERSION %s, got %s\n", expected, $0 > "/dev/stderr" + exit 1 + }' diff --git a/.github/scripts/install-r-macos-gfortran.sh b/.github/scripts/install-r-macos-gfortran.sh new file mode 100755 index 00000000..d6722d4a --- /dev/null +++ b/.github/scripts/install-r-macos-gfortran.sh @@ -0,0 +1,156 @@ +#!/usr/bin/env bash +set -euo pipefail + +usage() { + cat <<'USAGE' +Usage: install-r-macos-gfortran.sh --target VERSION --arch ARCH --work-dir PATH --prefix PATH [--github-output] + +Downloads the R/macOS GNU Fortran package selected for the requested macOS +build tuple, expands it without using the macOS installer, and prepares a +relocated compiler prefix for CI. +USAGE +} + +target="" +arch="" +work_dir="" +prefix="" +github_output=0 +pkg_url="https://mac.r-project.org/tools/gfortran-14.2-universal.pkg" +pkg_sha256="ec462d465f093eeee0623d2b5d327bd1038313b985034b766462957e36d7aadd" +version="14.2.0" + +while [ "$#" -gt 0 ]; do + case "$1" in + --target) + target="$2" + shift 2 + ;; + --arch) + arch="$2" + shift 2 + ;; + --work-dir) + work_dir="$2" + shift 2 + ;; + --prefix) + prefix="$2" + shift 2 + ;; + --github-output) + github_output=1 + shift + ;; + --help|-h) + usage + exit 0 + ;; + *) + echo "Unknown option: $1" >&2 + usage >&2 + exit 2 + ;; + esac +done + +if [ -z "$target" ] || [ -z "$arch" ] || [ -z "$work_dir" ] || [ -z "$prefix" ]; then + usage >&2 + exit 2 +fi + +case "${arch}:${target}" in + arm64:11.0) + triplet="aarch64-apple-darwin20.0" + ;; + *) + echo "::error::Unsupported R/macOS gfortran tuple: arch=${arch}, target=${target}" + exit 2 + ;; +esac + +pkg="${work_dir}/gfortran-14.2-universal.pkg" +expanded="${work_dir}/gfortran-14.2-expanded" +payload_prefix="${expanded}/gfortran.pkg/Payload/opt/gfortran" +runtime_dir="${prefix}/lib/gcc/${triplet}/${version}" + +mkdir -p "$work_dir" + +echo "R/macOS GNU Fortran install" +echo "Package URL: ${pkg_url}" +echo "Expected SHA-256: ${pkg_sha256}" +echo "Requested tuple: arch=${arch}, target=${target}, triplet=${triplet}" +echo "Install prefix: ${prefix}" + +curl -fsSL --retry 3 --retry-delay 5 -o "$pkg" "$pkg_url" +actual_sha256="$(shasum -a 256 "$pkg" | awk '{print $1}')" +echo "Actual SHA-256: ${actual_sha256}" +if [ "$actual_sha256" != "$pkg_sha256" ]; then + echo "::error::Unexpected R/macOS gfortran package checksum" + exit 1 +fi + +pkgutil --expand-full "$pkg" "$expanded" +if [ ! -d "$payload_prefix" ]; then + echo "::error::Expanded package does not contain expected /opt/gfortran payload" + exit 1 +fi + +mkdir -p "$(dirname "$prefix")" +ditto "$payload_prefix" "$prefix" + +target_compiler="${prefix}/bin/${triplet}-gfortran" +if [ ! -x "$target_compiler" ]; then + echo "::error::Expected target gfortran compiler not found: ${target_compiler}" + exit 1 +fi +compiler="$target_compiler" +if [ ! -d "$runtime_dir" ]; then + echo "::error::Runtime archive directory not found: ${runtime_dir}" + exit 1 +fi + +sdkroot="$(xcrun --sdk macosx --show-sdk-path)" +libgfortran="${runtime_dir}/libgfortran.a" +libquadmath="${runtime_dir}/libquadmath.a" +libgcc="${runtime_dir}/libgcc.a" +libgomp="${runtime_dir}/libgomp.a" + +archives=("$libgfortran" "$libquadmath" "$libgcc" "$libgomp") +for archive in "${archives[@]}"; do + if [ ! -f "$archive" ]; then + echo "::error::Expected runtime archive not found: ${archive}" + exit 1 + fi +done + +"${GITHUB_WORKSPACE:-$(pwd)}/.github/scripts/verify-macos-static-archives.sh" \ + --target "$target" \ + --arch "$arch" \ + --mode error \ + "${archives[@]}" + +echo "Compiler: ${compiler}" +file "$compiler" +otool -L "$compiler" + +runtime_link_flags="${libgfortran} ${libquadmath} ${libgcc}" +fortran_runtime_flags="-static-libgcc -static-libgfortran -static-libquadmath -isysroot ${sdkroot}" +runtime_archives="${archives[*]}" +cache_key="r-macos-gfortran-14.2-universal-${pkg_sha256}" + +if [ "$github_output" -eq 1 ]; then + github_output_file="${GITHUB_OUTPUT:-/dev/stdout}" + { + echo "path=${compiler}" + echo "prefix=${prefix}" + echo "original_prefix=/opt/gfortran" + echo "runtime_lib_dir=${runtime_dir}" + echo "fortran_runtime_flags=${fortran_runtime_flags}" + echo "runtime_link_flags=${runtime_link_flags}" + echo "runtime_archives=${runtime_archives}" + echo "libgomp=${libgomp}" + echo "version=${version}" + echo "cache_key=${cache_key}" + } >> "$github_output_file" +fi diff --git a/.github/scripts/install-xpack-gfortran-macos.sh b/.github/scripts/install-xpack-gfortran-macos.sh new file mode 100755 index 00000000..c500d076 --- /dev/null +++ b/.github/scripts/install-xpack-gfortran-macos.sh @@ -0,0 +1,194 @@ +#!/usr/bin/env bash +set -euo pipefail + +usage() { + cat <<'USAGE' +Usage: install-xpack-gfortran-macos.sh --target VERSION --arch ARCH --work-dir PATH --prefix PATH [--github-output] + +Downloads the xPack GCC archive selected for the requested macOS build tuple, +verifies it, and prepares a relocated compiler prefix for CI. +USAGE +} + +target="" +arch="" +work_dir="" +prefix="" +github_output=0 + +while [ "$#" -gt 0 ]; do + case "$1" in + --target) + target="$2" + shift 2 + ;; + --arch) + arch="$2" + shift 2 + ;; + --work-dir) + work_dir="$2" + shift 2 + ;; + --prefix) + prefix="$2" + shift 2 + ;; + --github-output) + github_output=1 + shift + ;; + --help|-h) + usage + exit 0 + ;; + *) + echo "Unknown option: $1" >&2 + usage >&2 + exit 2 + ;; + esac +done + +if [ -z "$target" ] || [ -z "$arch" ] || [ -z "$work_dir" ] || [ -z "$prefix" ]; then + usage >&2 + exit 2 +fi + +case "${arch}:${target}" in + x86_64:10.13) + archive_name="xpack-gcc-12.4.0-1-darwin-x64" + package_name="xpack-gcc-12.4.0-1" + package_url="https://github.com/xpack-dev-tools/gcc-xpack/releases/download/v12.4.0-1/${archive_name}.tar.gz" + package_sha256="f194b0fc72c7d6563694707794e350e73f807635c8bdb05168924a56126d871c" + runtime_dir="lib/gcc/x86_64-apple-darwin18.7.0/12.4.0" + version="12.4.0" + ;; + *) + echo "::error::Unsupported xPack gfortran tuple: arch=${arch}, target=${target}" + exit 2 + ;; +esac + +archive="${work_dir}/${archive_name}.tar.gz" +expanded="${work_dir}/expanded" +payload_prefix="${expanded}/${package_name}" + +mkdir -p "$work_dir" + +echo "xPack GCC install" +echo "Package URL: ${package_url}" +echo "Expected SHA-256: ${package_sha256}" +echo "Requested tuple: arch=${arch}, target=${target}" +echo "Install prefix: ${prefix}" + +curl -fsSL --retry 3 --retry-delay 5 -o "$archive" "$package_url" +actual_sha256="$(shasum -a 256 "$archive" | awk '{print $1}')" +echo "Actual SHA-256: ${actual_sha256}" +if [ "$actual_sha256" != "$package_sha256" ]; then + echo "::error::Unexpected xPack GCC archive checksum" + exit 1 +fi + +mkdir -p "$expanded" +tar -xzf "$archive" -C "$expanded" +if [ ! -d "$payload_prefix" ]; then + echo "::error::Expanded archive does not contain expected ${package_name} payload" + exit 1 +fi + +mkdir -p "$(dirname "$prefix")" +ditto "$payload_prefix" "$prefix" + +compiler="${prefix}/bin/gfortran" +if [ ! -x "$compiler" ]; then + echo "::error::Expected gfortran compiler not found: ${compiler}" + exit 1 +fi + +sdkroot="$(xcrun --sdk macosx --show-sdk-path)" +libgfortran="${prefix}/lib/libgfortran.a" +libquadmath="${prefix}/lib/libquadmath.a" +libgcc="${prefix}/${runtime_dir}/libgcc.a" +libgomp="${prefix}/lib/libgomp.a" +libgfortran_spec="${prefix}/lib/libgfortran.spec" + +archives=("$libgfortran" "$libquadmath" "$libgcc" "$libgomp") +for archive_member in "${archives[@]}"; do + if [ ! -f "$archive_member" ]; then + echo "::error::Expected runtime archive not found: ${archive_member}" + exit 1 + fi +done + +if [ ! -f "$libgfortran_spec" ]; then + echo "::error::Expected libgfortran spec not found: ${libgfortran_spec}" + exit 1 +fi + +spec_tmp="${libgfortran_spec}.tmp" +# This xPack Darwin build lacks -static-libquadmath, but its libgfortran spec +# injects -lquadmath. Rewrite that injected library to the verified static +# archive so the compiler driver can still own the Fortran runtime link policy. +sed "s|-lquadmath|${libquadmath}|g" "$libgfortran_spec" > "$spec_tmp" +if cmp -s "$libgfortran_spec" "$spec_tmp"; then + echo "::error::xPack libgfortran spec did not contain the expected libquadmath injection" + exit 1 +fi +mv "$spec_tmp" "$libgfortran_spec" + +"${GITHUB_WORKSPACE:-$(pwd)}/.github/scripts/verify-macos-static-archives.sh" \ + --target "$target" \ + --arch "$arch" \ + --mode error \ + "${archives[@]}" + +echo "Compiler: ${compiler}" +file "$compiler" +otool -L "$compiler" +"$compiler" --version + +runtime_link_flags="" +fortran_runtime_flags="-static-libgcc -static-libgfortran -mmacosx-version-min=${target} -isysroot ${sdkroot}" +runtime_archives="${archives[*]}" +cache_key="${archive_name}-${package_sha256}" + +quadmath_probe="${work_dir}/quadmath-static-probe.f90" +quadmath_probe_exe="${work_dir}/quadmath-static-probe" +{ + echo "program main" + echo " real(16) :: x" + echo " x = sqrt(2.0_16)" + echo " print *, x" + echo "end program main" +} > "$quadmath_probe" + +"$compiler" \ + -static-libgcc \ + -static-libgfortran \ + "-mmacosx-version-min=${target}" \ + -isysroot "$sdkroot" \ + "$quadmath_probe" \ + -o "$quadmath_probe_exe" + +otool -L "$quadmath_probe_exe" +if otool -L "$quadmath_probe_exe" | awk '/libquadmath.*\.dylib/ { found=1; print } END { exit found ? 0 : 1 }'; then + echo "::error::xPack gfortran linked the quadmath probe against dynamic libquadmath" + exit 1 +fi + +if [ "$github_output" -eq 1 ]; then + github_output_file="${GITHUB_OUTPUT:-/dev/stdout}" + { + echo "path=${compiler}" + echo "prefix=${prefix}" + echo "original_prefix=xpack-gcc" + echo "runtime_lib_dir=${prefix}/${runtime_dir}" + echo "fortran_runtime_flags=${fortran_runtime_flags}" + echo "runtime_link_flags=${runtime_link_flags}" + echo "runtime_archives=${runtime_archives}" + echo "libgomp=${libgomp}" + echo "version=${version}" + echo "cache_key=${cache_key}" + } >> "$github_output_file" +fi diff --git a/.github/scripts/macos-qt-cache-key.sh b/.github/scripts/macos-qt-cache-key.sh new file mode 100755 index 00000000..06359737 --- /dev/null +++ b/.github/scripts/macos-qt-cache-key.sh @@ -0,0 +1,147 @@ +#!/usr/bin/env bash +set -euo pipefail + +QT_VERSION=5.15.18 +QT_SOURCE_SHA256=cea1fbabf02455f3f0e8eaa839f5d6f45cdb56b62c8a83af5c1d00ac05f912ea +QT_CACHE_EPOCH=1 +QT_SOURCE_URL="https://download.qt.io/archive/qt/5.15/${QT_VERSION}/single/qt-everywhere-opensource-src-${QT_VERSION}.tar.xz" + +macos_qt_script_dir() { + cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 + pwd +} + +macos_qt_sha256_file() { + if command -v shasum >/dev/null 2>&1; then + shasum -a 256 "$1" | awk '{print $1}' + elif command -v sha256sum >/dev/null 2>&1; then + sha256sum "$1" | awk '{print $1}' + else + echo "No SHA-256 tool found; expected shasum or sha256sum" >&2 + return 1 + fi +} + +macos_qt_sha256_stream() { + if command -v shasum >/dev/null 2>&1; then + shasum -a 256 | awk '{print $1}' + elif command -v sha256sum >/dev/null 2>&1; then + sha256sum | awk '{print $1}' + else + echo "No SHA-256 tool found; expected shasum or sha256sum" >&2 + return 1 + fi +} + +macos_qt_script_hash() { + local script_dir + script_dir="$(macos_qt_script_dir)" + + { + for script in build-qt-macos.sh macos-qt-cache-key.sh; do + local path="${script_dir}/${script}" + if [ ! -f "$path" ]; then + echo "Missing Qt cache input script: $path" >&2 + return 1 + fi + printf '%s %s\n' "$(macos_qt_sha256_file "$path")" "$script" + done + } | macos_qt_sha256_stream +} + +macos_qt_cache_key() { + local arch="$1" + local runner="$2" + local deployment_target="$3" + local script_hash + script_hash="$(macos_qt_script_hash)" + + printf 'qt-macos-%s-%s-%s-min%s-epoch%s-%s\n' \ + "$arch" \ + "$runner" \ + "$QT_VERSION" \ + "$deployment_target" \ + "$QT_CACHE_EPOCH" \ + "$script_hash" +} + +usage() { + cat <<'USAGE' +Usage: macos-qt-cache-key.sh --arch ARCH --runner RUNNER --deployment-target VERSION [--github-output] + +Prints the exact GitHub Actions cache key for the pinned macOS Qt build. +USAGE +} + +main() { + local arch="" + local runner="" + local deployment_target="" + local github_output=0 + + while [ "$#" -gt 0 ]; do + case "$1" in + --arch) + arch="$2" + shift 2 + ;; + --runner) + runner="$2" + shift 2 + ;; + --deployment-target) + deployment_target="$2" + shift 2 + ;; + --github-output) + github_output=1 + shift + ;; + --help|-h) + usage + exit 0 + ;; + *) + echo "Unknown argument: $1" >&2 + usage >&2 + exit 2 + ;; + esac + done + + if [ -z "$arch" ] || [ -z "$runner" ] || [ -z "$deployment_target" ]; then + usage >&2 + exit 2 + fi + + case "${arch}:${runner}:${deployment_target}" in + arm64:macos-15:11.0|x86_64:macos-15-intel:10.13) + ;; + *) + echo "Unsupported macOS Qt build tuple: arch=${arch}, runner=${runner}, deployment_target=${deployment_target}" >&2 + exit 2 + ;; + esac + + local key + key="$(macos_qt_cache_key "$arch" "$runner" "$deployment_target")" + printf '%s\n' "$key" + + if [ "$github_output" -eq 1 ]; then + if [ -z "${GITHUB_OUTPUT:-}" ]; then + echo "--github-output requires GITHUB_OUTPUT to be set" >&2 + exit 2 + fi + { + printf 'key=%s\n' "$key" + printf 'version=%s\n' "$QT_VERSION" + printf 'source_url=%s\n' "$QT_SOURCE_URL" + printf 'source_sha256=%s\n' "$QT_SOURCE_SHA256" + printf 'cache_epoch=%s\n' "$QT_CACHE_EPOCH" + } >> "$GITHUB_OUTPUT" + fi +} + +if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then + main "$@" +fi diff --git a/.github/scripts/verify-macos-artifacts.sh b/.github/scripts/verify-macos-artifacts.sh new file mode 100755 index 00000000..954c54e9 --- /dev/null +++ b/.github/scripts/verify-macos-artifacts.sh @@ -0,0 +1,188 @@ +#!/usr/bin/env bash +set -euo pipefail + +usage() { + cat <<'USAGE' +Usage: verify-macos-artifacts.sh --target VERSION --arch ARCH [--allow-prefix PATH ...] PATH... + +Verifies Mach-O files under PATH for: + * expected architecture + * deployment target not newer than --target + * no package-manager runtime library references + +Package-manager paths are always rejected: + /opt/homebrew, /usr/local/Cellar, /usr/local/opt, /opt/local +USAGE +} + +target="" +arch="" +allow_prefixes=() +paths=() + +while [ "$#" -gt 0 ]; do + case "$1" in + --target) + target="$2" + shift 2 + ;; + --arch) + arch="$2" + shift 2 + ;; + --allow-prefix) + allow_prefixes+=("$2") + shift 2 + ;; + --help|-h) + usage + exit 0 + ;; + --) + shift + while [ "$#" -gt 0 ]; do + paths+=("$1") + shift + done + ;; + -*) + echo "Unknown option: $1" >&2 + usage >&2 + exit 2 + ;; + *) + paths+=("$1") + shift + ;; + esac +done + +if [ -z "$target" ] || [ -z "$arch" ] || [ "${#paths[@]}" -eq 0 ]; then + usage >&2 + exit 2 +fi + +# Validate that all target paths exist before checking +for path in "${paths[@]}"; do + if [ ! -e "$path" ]; then + echo "::error::Path does not exist: $path" >&2 + exit 2 + fi +done + + +version_gt() { + awk -v a="$1" -v b="$2" ' + BEGIN { + split(a, av, ".") + split(b, bv, ".") + for (i = 1; i <= 3; i++) { + ai = av[i] + 0 + bi = bv[i] + 0 + if (ai > bi) exit 0 + if (ai < bi) exit 1 + } + exit 1 + }' +} + +is_macho() { + local file="$1" + file "$file" 2>/dev/null | grep -Eq 'Mach-O|universal binary' +} + +is_allowed_reference() { + local ref="$1" + case "$ref" in + @rpath/*|@loader_path/*|@executable_path/*|/usr/lib/*|/System/Library/*) + return 0 + ;; + esac + + local prefix + if [ "${#allow_prefixes[@]}" -gt 0 ]; then + for prefix in "${allow_prefixes[@]}"; do + case "$ref" in + "$prefix"/*) return 0 ;; + esac + done + fi + + return 1 +} + +check_file() { + local file="$1" + local fail=0 + local archs + local minos + local refs + local install_name + + archs=$(lipo -archs "$file" 2>/dev/null || true) + if [ -z "$archs" ]; then + echo "::error file=${file}::Could not determine Mach-O architecture" + return 1 + fi + if ! printf '%s\n' "$archs" | tr ' ' '\n' | grep -qx "$arch"; then + echo "::error file=${file}::Expected architecture ${arch}, found: ${archs}" + return 1 + fi + + minos=$(otool -arch "$arch" -l "$file" 2>/dev/null | awk ' + /LC_BUILD_VERSION/ { in_build = 1; next } + in_build && /minos/ { print $2; exit } + /LC_VERSION_MIN_MACOSX/ { in_old = 1; next } + in_old && /version/ { print $2; exit } + ') + if [ -n "$minos" ] && version_gt "$minos" "$target"; then + echo "::error file=${file}::Requires macOS ${minos}, newer than artifact target ${target}" + fail=1 + fi + + install_name=$(otool -arch "$arch" -D "$file" 2>/dev/null | awk 'NR == 2 { print $1 }' || true) + refs=$(otool -arch "$arch" -L "$file" 2>/dev/null | awk 'NR > 1 { print $1 }' || true) + while IFS= read -r ref; do + [ -n "$ref" ] || continue + if [ "$ref" = "$install_name" ]; then + case "$ref" in + */*) ;; + *) continue ;; + esac + fi + case "$ref" in + /opt/homebrew/*|/usr/local/Cellar/*|/usr/local/opt/*|/opt/local/*) + echo "::error file=${file}::Package-manager runtime reference is not allowed: ${ref}" + fail=1 + continue + ;; + esac + if ! is_allowed_reference "$ref"; then + echo "::error file=${file}::Unexpected runtime reference: ${ref}" + fail=1 + fi + done <<< "$refs" + + return "$fail" +} + +overall=0 +while IFS= read -r file; do + if is_macho "$file"; then + check_file "$file" || overall=1 + fi +done < <( + for path in "${paths[@]}"; do + if [ -d "$path" ]; then + find "$path" -type f \( -perm +111 -o -name "*.dylib" -o -name "*.so" \) + elif [ -f "$path" ]; then + printf '%s\n' "$path" + fi + done +) + +if [ "$overall" -ne 0 ]; then + exit "$overall" +fi + +echo "All checked Mach-O files match arch ${arch}, target macOS ${target}, and approved runtime paths." diff --git a/.github/scripts/verify-macos-static-archives.sh b/.github/scripts/verify-macos-static-archives.sh new file mode 100755 index 00000000..2c20875e --- /dev/null +++ b/.github/scripts/verify-macos-static-archives.sh @@ -0,0 +1,211 @@ +#!/usr/bin/env bash +set -euo pipefail + +usage() { + cat <<'USAGE' +Usage: verify-macos-static-archives.sh --target VERSION --arch ARCH [--mode error|warn] PATH... + +Verifies static archives before they are linked into deployable macOS binaries: + * expected architecture + * object-member deployment targets not newer than --target + +--mode error (default) fails the build on any finding. --mode warn keeps +structural problems (missing archive, wrong architecture) fatal but +downgrades object-member deployment-target findings to warning annotations +and exits 0. Member deployment targets in third-party toolchain archives +are outside this workflow's control, so only that uncertain signal is made +non-blocking; a missing input or wrong-arch archive is broken plumbing and +always fails. +USAGE +} + +target="" +arch="" +mode="error" +archives=() +max_member_errors=25 + +while [ "$#" -gt 0 ]; do + case "$1" in + --target) + target="$2" + shift 2 + ;; + --arch) + arch="$2" + shift 2 + ;; + --mode) + mode="$2" + shift 2 + ;; + --help|-h) + usage + exit 0 + ;; + --) + shift + while [ "$#" -gt 0 ]; do + archives+=("$1") + shift + done + ;; + -*) + echo "Unknown option: $1" >&2 + usage >&2 + exit 2 + ;; + *) + archives+=("$1") + shift + ;; + esac +done + +if [ -z "$target" ] || [ -z "$arch" ] || [ "${#archives[@]}" -eq 0 ]; then + usage >&2 + exit 2 +fi + +case "$mode" in + error|warn) ;; + *) + echo "Invalid --mode: $mode (expected error or warn)" >&2 + exit 2 + ;; +esac + +# Annotation level for findings: errors fail the build, warnings do not. +if [ "$mode" = "warn" ]; then + ann="warning" +else + ann="error" +fi + +version_gt() { + awk -v a="$1" -v b="$2" ' + BEGIN { + split(a, av, ".") + split(b, bv, ".") + for (i = 1; i <= 3; i++) { + ai = av[i] + 0 + bi = bv[i] + 0 + if (ai > bi) exit 0 + if (ai < bi) exit 1 + } + exit 1 + }' +} + +check_archive() { + local archive="$1" + local structural_fail=0 + local target_fail=0 + local archs + local line + local member="" + local in_build=0 + local in_old=0 + local minos + local reported=0 + local suppressed=0 + + if [ ! -f "$archive" ]; then + echo "::error::Static archive does not exist: ${archive}" + return 2 + fi + + archs=$(lipo -archs "$archive" 2>/dev/null || true) + if [ -n "$archs" ] && ! printf '%s\n' "$archs" | tr ' ' '\n' | grep -qx "$arch"; then + echo "::error file=${archive}::Expected architecture ${arch}, found: ${archs}" + structural_fail=1 + fi + + while IFS= read -r line; do + case "$line" in + *".a("*"):") + member="${line%:}" + in_build=0 + in_old=0 + ;; + *"LC_BUILD_VERSION"*) + in_build=1 + in_old=0 + ;; + *"LC_VERSION_MIN_MACOSX"*) + in_build=0 + in_old=1 + ;; + *" minos "*) + if [ "$in_build" -eq 1 ]; then + read -r _ minos _ <<< "$line" + if version_gt "$minos" "$target"; then + if [ "$reported" -lt "$max_member_errors" ]; then + echo "::${ann} file=${archive}::${member} requires macOS ${minos}, newer than archive target ${target}" + else + suppressed=$((suppressed + 1)) + fi + reported=$((reported + 1)) + target_fail=1 + fi + in_build=0 + fi + ;; + *" version "*) + if [ "$in_old" -eq 1 ]; then + read -r _ minos _ <<< "$line" + if version_gt "$minos" "$target"; then + if [ "$reported" -lt "$max_member_errors" ]; then + echo "::${ann} file=${archive}::${member} requires macOS ${minos}, newer than archive target ${target}" + else + suppressed=$((suppressed + 1)) + fi + reported=$((reported + 1)) + target_fail=1 + fi + in_old=0 + fi + ;; + esac + done < <(otool -arch "$arch" -l "$archive" 2>/dev/null || true) + + if [ "$suppressed" -gt 0 ]; then + echo "::${ann} file=${archive}::Suppressed ${suppressed} additional archive member deployment-target findings" + fi + + # 2 = structural problem (always fatal), 1 = deployment-target finding + # (respects --mode), 0 = clean. + if [ "$structural_fail" -ne 0 ]; then + return 2 + fi + if [ "$target_fail" -ne 0 ]; then + return 1 + fi + return 0 +} + +overall_structural=0 +overall_target=0 +for archive in "${archives[@]}"; do + rc=0 + check_archive "$archive" || rc=$? + case "$rc" in + 2) overall_structural=1 ;; + 1) overall_target=1 ;; + esac +done + +if [ "$overall_structural" -ne 0 ]; then + echo "::error::Static archive verification failed: missing archive or wrong architecture is always fatal." + exit 1 +fi + +if [ "$overall_target" -ne 0 ]; then + if [ "$mode" = "error" ]; then + exit 1 + fi + echo "::notice::Static archive verification reported deployment-target findings in warn mode; not failing the build." + exit 0 +fi + +echo "All checked static archives match arch ${arch} and target macOS ${target}." diff --git a/.github/workflows/build-linux.yml b/.github/workflows/build-linux.yml index 38b55845..10c44630 100644 --- a/.github/workflows/build-linux.yml +++ b/.github/workflows/build-linux.yml @@ -17,6 +17,16 @@ on: required: false type: string default: "x86_64" + release_channel: + description: "Build release channel: DEVEL, RC, or GA" + required: false + type: string + default: "DEVEL" + rc_number: + description: "Release candidate number when release_channel is RC" + required: false + type: string + default: "" jobs: build: @@ -33,7 +43,7 @@ jobs: qtbase5-dev qttools5-dev qtmultimedia5-dev libqt5serialport5-dev \ libqt5sql5-sqlite libqt5websockets5-dev \ libqt5multimedia5-plugins \ - libusb-1.0-0-dev libudev-dev libreadline-dev \ + libusb-1.0-0-dev libudev-dev libreadline-dev portaudio19-dev \ autoconf automake libtool pkg-config \ texinfo \ dpkg-dev fakeroot \ @@ -103,6 +113,8 @@ jobs: -DCMAKE_POLICY_VERSION_MINIMUM=3.5 \ -DWSJT_SKIP_MANPAGES=ON \ -DWSJT_BUILD_TESTS=ON \ + -DWSJT_RELEASE_CHANNEL="${{ inputs.release_channel }}" \ + -DWSJT_RC_NUMBER="${{ inputs.rc_number }}" \ -DPFUNIT_DIR="${{ steps.pfunit.outputs.dir }}" \ -Wno-dev @@ -158,6 +170,8 @@ jobs: ls -lh "$DEB" file "$DEB" dpkg-deb --info "$DEB" | head -20 + dpkg-deb -c "$DEB" | grep -qE '/usr/bin/map65$' + dpkg-deb -f "$DEB" Depends | grep -Eq 'libportaudio|portaudio' - name: Upload .deb uses: actions/upload-artifact@v7 @@ -189,6 +203,8 @@ jobs: # Confirm the core binaries are in the package. rpm -qpl "$RPM" | grep -qE '/bin/wsjtx$' rpm -qpl "$RPM" | grep -qE '/bin/jt9$' + rpm -qpl "$RPM" | grep -qE '/bin/map65$' + rpm -qpR "$RPM" | grep -Eq 'libportaudio|portaudio' - name: Upload RPM uses: actions/upload-artifact@v7 @@ -203,6 +219,7 @@ jobs: # linuxdeploy's desktop/icon integration needs these exact paths. test -x AppDir/usr/bin/wsjtx test -x AppDir/usr/bin/jt9 + test -x AppDir/usr/bin/map65 test -x AppDir/usr/bin/ft8code test -f AppDir/usr/share/applications/wsjtx.desktop test -f AppDir/usr/share/pixmaps/wsjtx_icon.png @@ -254,6 +271,7 @@ jobs: ./"$APPIMAGE" --appimage-extract >/dev/null test -x squashfs-root/usr/bin/wsjtx test -x squashfs-root/usr/bin/jt9 + test -x squashfs-root/usr/bin/map65 test -x squashfs-root/usr/bin/ft8code test -x squashfs-root/usr/bin/wsprd file squashfs-root/usr/bin/wsjtx | grep -q "ELF 64-bit" diff --git a/.github/workflows/build-macos.yml b/.github/workflows/build-macos.yml index 657af14e..295ab743 100644 --- a/.github/workflows/build-macos.yml +++ b/.github/workflows/build-macos.yml @@ -11,7 +11,7 @@ on: description: "Hamlib branch to build" required: false type: string - default: "4.7.0" + default: "4.7.1" arch: description: "Target architecture (arm64 or x86_64)" required: true @@ -24,6 +24,16 @@ on: description: "macOS deployment target version" required: true type: string + release_channel: + description: "Build release channel: DEVEL, RC, or GA" + required: false + type: string + default: "DEVEL" + rc_number: + description: "Release candidate number when release_channel is RC" + required: false + type: string + default: "" jobs: build: @@ -31,6 +41,28 @@ jobs: steps: - uses: actions/checkout@v6 + - name: Resolve source revision + id: source_revision + run: | + source_revision="${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || '' }}" + if [ -z "$source_revision" ]; then + source_revision="$(git rev-parse HEAD)" + fi + echo "sha=${source_revision}" >> "$GITHUB_OUTPUT" + + - name: Verify macOS build tuple + run: | + case "${{ inputs.arch }}:${{ inputs.runner }}:${{ inputs.deployment_target }}" in + arm64:macos-15:11.0|x86_64:macos-15-intel:10.13) + echo "Using supported macOS build tuple: ${{ inputs.arch }} on ${{ inputs.runner }} targeting ${{ inputs.deployment_target }}" + ;; + *) + echo "::error::Unsupported macOS build tuple: arch=${{ inputs.arch }}, runner=${{ inputs.runner }}, deployment_target=${{ inputs.deployment_target }}" + echo "::error::Use arm64:macos-15:11.0 or x86_64:macos-15-intel:10.13. Do not use macos-latest for release artifacts." + exit 1 + ;; + esac + - name: Check signing secrets id: check_secrets env: @@ -47,91 +79,285 @@ jobs: run: echo "HOMEBREW_PREFIX=$(brew --prefix)" >> "$GITHUB_ENV" - name: Install dependencies - run: brew install cmake gcc fftw boost qt@5 libusb dylibbundler autoconf automake libtool asciidoctor + run: brew install cmake autoconf automake libtool asciidoctor - - name: Locate gfortran - id: fc + - name: Compute Qt cache key + id: qt-key run: | - FC="$(brew --prefix gcc)/bin/gfortran" - [ -f "$FC" ] || FC="$(ls $HOMEBREW_PREFIX/bin/gfortran-* 2>/dev/null | sort -V | tail -1)" - echo "Found gfortran: $FC" - echo "path=$FC" >> "$GITHUB_OUTPUT" + .github/scripts/macos-qt-cache-key.sh \ + --arch "${{ inputs.arch }}" \ + --runner "${{ inputs.runner }}" \ + --deployment-target "${{ inputs.deployment_target }}" \ + --github-output + + - name: Restore Qt cache + id: qt-cache + uses: actions/cache/restore@v5 + with: + path: qt-prefix + key: ${{ steps.qt-key.outputs.key }} + fail-on-cache-miss: true - - name: Fix Qt5 keg-only paths + - name: Verify cached Qt deployment target run: | - QT5_PREFIX="$(brew --prefix qt@5)" - [ -e $HOMEBREW_PREFIX/mkspecs ] || sudo ln -s "${QT5_PREFIX}/mkspecs" $HOMEBREW_PREFIX/mkspecs - [ -e $HOMEBREW_PREFIX/plugins ] || sudo ln -s "${QT5_PREFIX}/plugins" $HOMEBREW_PREFIX/plugins - - - name: Cache pFUnit - id: pfunit-cache - uses: actions/cache@v5 - with: - path: pfunit-prefix - key: pfunit-macos-${{ inputs.arch }}-v4.9.0-${{ hashFiles('.github/workflows/build-macos.yml') }} + .github/scripts/verify-macos-artifacts.sh \ + --target "${{ inputs.deployment_target }}" \ + --arch "${{ inputs.arch }}" \ + --allow-prefix "${GITHUB_WORKSPACE}/qt-prefix" \ + "${GITHUB_WORKSPACE}/qt-prefix" + + - name: Install controlled ARM gfortran + id: controlled-arm-fc + if: inputs.arch == 'arm64' + run: | + .github/scripts/install-r-macos-gfortran.sh \ + --target "${{ inputs.deployment_target }}" \ + --arch "${{ inputs.arch }}" \ + --work-dir "${RUNNER_TEMP}/r-macos-gfortran" \ + --prefix "${GITHUB_WORKSPACE}/gfortran-prefix" \ + --github-output + + - name: Install controlled Intel gfortran + id: controlled-intel-fc + if: inputs.arch == 'x86_64' + run: | + .github/scripts/install-xpack-gfortran-macos.sh \ + --target "${{ inputs.deployment_target }}" \ + --arch "${{ inputs.arch }}" \ + --work-dir "${RUNNER_TEMP}/xpack-gfortran" \ + --prefix "${GITHUB_WORKSPACE}/gfortran-prefix" \ + --github-output + + - name: Select gfortran + id: fc + run: | + if [ "${{ inputs.arch }}" = "x86_64" ]; then + echo "Using controlled gfortran: ${{ steps.controlled-intel-fc.outputs.path }}" + { + echo "path=${{ steps.controlled-intel-fc.outputs.path }}" + echo "prefix=${{ steps.controlled-intel-fc.outputs.prefix }}" + echo "original_prefix=${{ steps.controlled-intel-fc.outputs.original_prefix }}" + echo "runtime_lib_dir=${{ steps.controlled-intel-fc.outputs.runtime_lib_dir }}" + echo "libgomp=${{ steps.controlled-intel-fc.outputs.libgomp }}" + echo "fortran_runtime_flags=${{ steps.controlled-intel-fc.outputs.fortran_runtime_flags }}" + echo "runtime_link_flags=${{ steps.controlled-intel-fc.outputs.runtime_link_flags }}" + echo "runtime_archives=${{ steps.controlled-intel-fc.outputs.runtime_archives }}" + echo "version=${{ steps.controlled-intel-fc.outputs.version }}" + echo "cache_key=${{ steps.controlled-intel-fc.outputs.cache_key }}" + } >> "$GITHUB_OUTPUT" + exit 0 + fi - - name: Build pFUnit - if: steps.pfunit-cache.outputs.cache-hit != 'true' + echo "Using controlled gfortran: ${{ steps.controlled-arm-fc.outputs.path }}" + { + echo "path=${{ steps.controlled-arm-fc.outputs.path }}" + echo "prefix=${{ steps.controlled-arm-fc.outputs.prefix }}" + echo "original_prefix=${{ steps.controlled-arm-fc.outputs.original_prefix }}" + echo "runtime_lib_dir=${{ steps.controlled-arm-fc.outputs.runtime_lib_dir }}" + echo "libgomp=${{ steps.controlled-arm-fc.outputs.libgomp }}" + echo "fortran_runtime_flags=${{ steps.controlled-arm-fc.outputs.fortran_runtime_flags }}" + echo "runtime_link_flags=${{ steps.controlled-arm-fc.outputs.runtime_link_flags }}" + echo "runtime_archives=${{ steps.controlled-arm-fc.outputs.runtime_archives }}" + echo "version=${{ steps.controlled-arm-fc.outputs.version }}" + echo "cache_key=${{ steps.controlled-arm-fc.outputs.cache_key }}" + } >> "$GITHUB_OUTPUT" + + - name: Verify static Fortran runtime deployment targets run: | - git clone --depth 1 --branch v4.9.0 --recursive \ - https://github.com/Goddard-Fortran-Ecosystem/pFUnit.git pfunit-src - cmake -S pfunit-src -B pfunit-build \ - -DSKIP_MPI=YES \ - -DSKIP_OPENMP=YES \ - -DCMAKE_POLICY_VERSION_MINIMUM=3.5 \ - -DCMAKE_Fortran_COMPILER="${{ steps.fc.outputs.path }}" \ - -DCMAKE_INSTALL_PREFIX="${GITHUB_WORKSPACE}/pfunit-prefix" - cmake --build pfunit-build -j$(sysctl -n hw.ncpu) - cmake --install pfunit-build + .github/scripts/verify-macos-static-archives.sh \ + --target "${{ inputs.deployment_target }}" \ + --arch "${{ inputs.arch }}" \ + --mode error \ + ${{ steps.fc.outputs.runtime_archives }} + + - name: Cache libusb + id: libusb-cache + uses: actions/cache/restore@v5 + with: + path: libusb-prefix + key: libusb-macos-${{ inputs.arch }}-${{ inputs.runner }}-1.0.27-min${{ inputs.deployment_target }}-${{ hashFiles('.github/scripts/build-libusb-macos.sh') }} - - name: Locate pFUnit config - id: pfunit + - name: Build libusb + if: steps.libusb-cache.outputs.cache-hit != 'true' run: | - CONFIG=$(find "${GITHUB_WORKSPACE}/pfunit-prefix" -name PFUNITConfig.cmake | head -1) - if [ -z "$CONFIG" ]; then - echo "ERROR: PFUNITConfig.cmake not found under pfunit-prefix" - find "${GITHUB_WORKSPACE}/pfunit-prefix" -maxdepth 3 -type d - exit 1 - fi - PFUNIT_DIR="$(dirname "$CONFIG")" - echo "Found PFUNITConfig.cmake at: $CONFIG" - echo "dir=${PFUNIT_DIR}" >> "$GITHUB_OUTPUT" + .github/scripts/build-libusb-macos.sh \ + 1.0.27 \ + "${{ inputs.deployment_target }}" \ + "${GITHUB_WORKSPACE}/libusb-prefix" + + - name: Save libusb cache + if: steps.libusb-cache.outputs.cache-hit != 'true' + continue-on-error: true + uses: actions/cache/save@v5 + with: + path: libusb-prefix + key: libusb-macos-${{ inputs.arch }}-${{ inputs.runner }}-1.0.27-min${{ inputs.deployment_target }}-${{ hashFiles('.github/scripts/build-libusb-macos.sh') }} - name: Cache Hamlib id: hamlib-cache - uses: actions/cache@v5 + uses: actions/cache/restore@v5 with: path: hamlib-prefix - key: hamlib-macos-${{ inputs.arch }}-${{ inputs.hamlib_branch }}-${{ hashFiles('.github/workflows/build-macos.yml') }} + key: hamlib-macos-${{ inputs.arch }}-${{ inputs.runner }}-${{ inputs.hamlib_branch }}-min${{ inputs.deployment_target }}-${{ hashFiles('.github/scripts/build-hamlib-macos.sh') }} - name: Build Hamlib if: steps.hamlib-cache.outputs.cache-hit != 'true' + env: + PKG_CONFIG_PATH: ${{ github.workspace }}/libusb-prefix/lib/pkgconfig + run: | + .github/scripts/build-hamlib-macos.sh \ + "${{ inputs.hamlib_branch }}" \ + "${{ inputs.deployment_target }}" \ + "${GITHUB_WORKSPACE}/hamlib-prefix" + + - name: Save Hamlib cache + if: steps.hamlib-cache.outputs.cache-hit != 'true' + continue-on-error: true + uses: actions/cache/save@v5 + with: + path: hamlib-prefix + key: hamlib-macos-${{ inputs.arch }}-${{ inputs.runner }}-${{ inputs.hamlib_branch }}-min${{ inputs.deployment_target }}-${{ hashFiles('.github/scripts/build-hamlib-macos.sh') }} + + - name: Cache PortAudio + id: portaudio-cache + uses: actions/cache/restore@v5 + with: + path: portaudio-prefix + key: portaudio-macos-${{ inputs.arch }}-${{ inputs.runner }}-19.7.0-min${{ inputs.deployment_target }}-${{ hashFiles('.github/scripts/build-portaudio-macos.sh') }} + + - name: Build PortAudio + if: steps.portaudio-cache.outputs.cache-hit != 'true' + run: | + .github/scripts/build-portaudio-macos.sh \ + 19.7.0 \ + "${{ inputs.deployment_target }}" \ + "${GITHUB_WORKSPACE}/portaudio-prefix" + + - name: Save PortAudio cache + if: steps.portaudio-cache.outputs.cache-hit != 'true' + continue-on-error: true + uses: actions/cache/save@v5 + with: + path: portaudio-prefix + key: portaudio-macos-${{ inputs.arch }}-${{ inputs.runner }}-19.7.0-min${{ inputs.deployment_target }}-${{ hashFiles('.github/scripts/build-portaudio-macos.sh') }} + + - name: Cache FFTW + id: fftw-cache + uses: actions/cache/restore@v5 + with: + path: fftw-prefix + key: fftw-macos-${{ inputs.arch }}-${{ inputs.runner }}-3.3.10-min${{ inputs.deployment_target }}-${{ hashFiles('.github/scripts/build-fftw-macos.sh') }} + + - name: Build FFTW + if: steps.fftw-cache.outputs.cache-hit != 'true' + run: | + .github/scripts/build-fftw-macos.sh \ + 3.3.10 \ + "${{ inputs.deployment_target }}" \ + "${GITHUB_WORKSPACE}/fftw-prefix" + + - name: Save FFTW cache + if: steps.fftw-cache.outputs.cache-hit != 'true' + continue-on-error: true + uses: actions/cache/save@v5 + with: + path: fftw-prefix + key: fftw-macos-${{ inputs.arch }}-${{ inputs.runner }}-3.3.10-min${{ inputs.deployment_target }}-${{ hashFiles('.github/scripts/build-fftw-macos.sh') }} + + - name: Cache Boost + id: boost-cache + uses: actions/cache/restore@v5 + with: + path: boost-prefix + key: boost-macos-${{ inputs.arch }}-${{ inputs.runner }}-1.85.0-min${{ inputs.deployment_target }}-${{ hashFiles('.github/scripts/build-boost-macos.sh') }} + + - name: Build Boost + if: steps.boost-cache.outputs.cache-hit != 'true' run: | - git clone --depth 1 --branch "${{ inputs.hamlib_branch }}" \ - https://github.com/Hamlib/Hamlib.git hamlib-src - cd hamlib-src - ./bootstrap - ./configure \ - --prefix="${GITHUB_WORKSPACE}/hamlib-prefix" \ - --disable-shared --enable-static \ - --without-cxx-binding - make -j$(sysctl -n hw.ncpu) - make install + .github/scripts/build-boost-macos.sh \ + 1.85.0 \ + "${{ inputs.arch }}" \ + "${{ inputs.deployment_target }}" \ + "${GITHUB_WORKSPACE}/boost-prefix" + + - name: Save Boost cache + if: steps.boost-cache.outputs.cache-hit != 'true' + continue-on-error: true + uses: actions/cache/save@v5 + with: + path: boost-prefix + key: boost-macos-${{ inputs.arch }}-${{ inputs.runner }}-1.85.0-min${{ inputs.deployment_target }}-${{ hashFiles('.github/scripts/build-boost-macos.sh') }} - name: Configure + env: + PKG_CONFIG_PATH: ${{ github.workspace }}/qt-prefix/lib/pkgconfig:${{ github.workspace }}/boost-prefix/lib/pkgconfig:${{ github.workspace }}/fftw-prefix/lib/pkgconfig:${{ github.workspace }}/libusb-prefix/lib/pkgconfig:${{ github.workspace }}/portaudio-prefix/lib/pkgconfig:${{ github.workspace }}/hamlib-prefix/lib/pkgconfig run: | cmake -S . -B wsjtx-build \ - -DCMAKE_PREFIX_PATH="${GITHUB_WORKSPACE}/hamlib-prefix;${GITHUB_WORKSPACE}/pfunit-prefix;$(brew --prefix qt@5);$(brew --prefix libusb);$(brew --prefix fftw);$(brew --prefix boost)" \ + -DCMAKE_PREFIX_PATH="${GITHUB_WORKSPACE}/qt-prefix;${GITHUB_WORKSPACE}/boost-prefix;${GITHUB_WORKSPACE}/fftw-prefix;${GITHUB_WORKSPACE}/libusb-prefix;${GITHUB_WORKSPACE}/portaudio-prefix;${GITHUB_WORKSPACE}/hamlib-prefix" \ -DCMAKE_Fortran_COMPILER="${{ steps.fc.outputs.path }}" \ + -DCMAKE_Fortran_FLAGS="${{ steps.fc.outputs.fortran_runtime_flags }}" \ -DCMAKE_OSX_DEPLOYMENT_TARGET=${{ inputs.deployment_target }} \ + -DCMAKE_EXE_LINKER_FLAGS="-Wl,-headerpad_max_install_names ${{ steps.fc.outputs.runtime_link_flags }}" \ + -DWSJT_MACOS_LIBGOMP_LIBRARY="${{ steps.fc.outputs.libgomp }}" \ + -DWSJT_SOURCE_REVISION="${{ steps.source_revision.outputs.sha }}" \ -DCMAKE_POLICY_VERSION_MINIMUM=3.5 \ -DWSJT_SKIP_MANPAGES=ON \ + -DWSJT_SKIP_BUNDLE_FIXUP=ON \ -DWSJT_BUILD_TESTS=ON \ - -DPFUNIT_DIR="${{ steps.pfunit.outputs.dir }}" \ + -DWSJT_RELEASE_CHANNEL="${{ inputs.release_channel }}" \ + -DWSJT_RC_NUMBER="${{ inputs.rc_number }}" \ -Wno-dev + - name: Verify resolved dependency prefixes + run: | + CACHE=wsjtx-build/CMakeCache.txt + BAD=$(awk -F= ' + /^(Boost_DIR|Boost_INCLUDE_DIR|Boost_LOG_LIBRARY_RELEASE|Boost_LOG_SETUP_LIBRARY_RELEASE|FFTW3F_LIBRARY|FFTW3F_THREADS_LIBRARY|FFTW3_INCLUDE_DIR|Hamlib_INCLUDE_DIR|Hamlib_LIBRARY|Portaudio_INCLUDE_DIR|Portaudio_LIBRARY|Usb_INCLUDE_DIR|Usb_LIBRARY|Qt5[^:]*_DIR|Qt5[^:]*_EXECUTABLE):/ && $2 ~ /^(\/opt\/homebrew|\/usr\/local\/Cellar|\/usr\/local\/opt|\/opt\/local)/ { + print + } + ' "$CACHE") + if [ -n "$BAD" ]; then + echo "::error::Deployable macOS build resolved bundled dependencies from a package-manager prefix:" + echo "$BAD" + exit 1 + fi + + QT_BAD=$(awk -F= -v prefix="${GITHUB_WORKSPACE}/qt-prefix" ' + /^Qt5[^:]*_(DIR|EXECUTABLE):/ && index($2, prefix) != 1 { + print + } + ' "$CACHE") + if [ -n "$QT_BAD" ]; then + echo "::error::Deployable macOS build did not resolve Qt from the cached qt-prefix:" + echo "$QT_BAD" + exit 1 + fi + + - name: Verify built dependency deployment targets + run: | + .github/scripts/verify-macos-artifacts.sh \ + --target "${{ inputs.deployment_target }}" \ + --arch "${{ inputs.arch }}" \ + --allow-prefix "${GITHUB_WORKSPACE}/boost-prefix" \ + --allow-prefix "${GITHUB_WORKSPACE}/fftw-prefix" \ + --allow-prefix "${GITHUB_WORKSPACE}/libusb-prefix" \ + --allow-prefix "${GITHUB_WORKSPACE}/portaudio-prefix" \ + "${GITHUB_WORKSPACE}/boost-prefix" \ + "${GITHUB_WORKSPACE}/fftw-prefix" \ + "${GITHUB_WORKSPACE}/libusb-prefix" \ + "${GITHUB_WORKSPACE}/portaudio-prefix" + + - name: Verify Hamlib static archive deployment targets + run: | + hamlib_archives=( "${GITHUB_WORKSPACE}/hamlib-prefix/lib/"*.a ) + .github/scripts/verify-macos-static-archives.sh \ + --target "${{ inputs.deployment_target }}" \ + --arch "${{ inputs.arch }}" \ + --mode error \ + "${hamlib_archives[@]}" + - name: Build - run: cmake --build wsjtx-build -j$(sysctl -n hw.ncpu) + run: cmake --build wsjtx-build -j"$(sysctl -n hw.ncpu)" - name: Run tests id: ctest @@ -145,6 +371,7 @@ jobs: - name: Upload test results if: always() && steps.ctest.conclusion != 'skipped' + continue-on-error: true uses: actions/upload-artifact@v7 with: name: ctest-results-macos-${{ inputs.arch }} @@ -156,81 +383,239 @@ jobs: file wsjtx-build/jt9 lipo -archs wsjtx-build/jt9 | grep -q ${{ inputs.arch }} - - name: Collect binaries + - name: Install app bundle and collect CLI assets id: collect run: | BUILD=wsjtx-build STAGE=stage/wsjtx-${{ inputs.version }}-${{ inputs.arch }} ASSETS=assets - mkdir -p "${STAGE}" "${ASSETS}" - - cp -R "${BUILD}/wsjtx.app" "${STAGE}/" + mkdir -p "${ASSETS}" + cmake --install "${BUILD}" --prefix "${STAGE}" - for bin in jt9 wsprd; do - [ -f "${BUILD}/${bin}" ] && cp "${BUILD}/${bin}" "${STAGE}/wsjtx.app/Contents/MacOS/" - done + APP="${STAGE}/wsjtx.app" + if [ ! -d "${APP}" ]; then + echo "::error::CMake install did not create ${APP}" + exit 1 + fi + if [ ! -x "${APP}/Contents/MacOS/map65" ]; then + echo "::error::CMake install did not create executable MAP65 companion app binary at ${APP}/Contents/MacOS/map65" + exit 1 + fi for bin in jt9 wsprd wsprcode jt65code jt4code ft8code q65code encode77 fcal hash22calc; do - [ -f "${BUILD}/${bin}" ] && cp "${BUILD}/${bin}" "${STAGE}/" && cp "${BUILD}/${bin}" "${ASSETS}/" + [ -f "${BUILD}/${bin}" ] && cp "${BUILD}/${bin}" "${ASSETS}/" done for bin in ft4sim jt4sim jt65sim cwsim sfoxsim echosim EchoCallSim; do - [ -f "${BUILD}/${bin}" ] && cp "${BUILD}/${bin}" "${STAGE}/" && cp "${BUILD}/${bin}" "${ASSETS}/" + [ -f "${BUILD}/${bin}" ] && cp "${BUILD}/${bin}" "${ASSETS}/" done echo "stage_dir=${STAGE}" >> "$GITHUB_OUTPUT" echo "assets_dir=${ASSETS}" >> "$GITHUB_OUTPUT" + - name: Verify CMake-installed app resources + run: | + APP="${{ steps.collect.outputs.stage_dir }}/wsjtx.app" + DATADIR="${APP}/Contents/Resources/wsjtx" + DOCDIR="${APP}/Contents/Resources/doc/wsjtx" + SOUNDDIR="${APP}/Contents/Resources/sounds" + + for file in cty.dat cty.dat_copyright.txt grid.dat sat.dat eclipse.txt ALLCALL7.TXT JPLEPH; do + if [ ! -f "${DATADIR}/${file}" ]; then + echo "::error::Expected CMake-installed data file is missing: ${DATADIR}/${file}" + exit 1 + fi + done + + set -- "${DOCDIR}/wsjtx-main"*.html + if [ "$#" -lt 1 ] || [ ! -f "$1" ]; then + echo "::error::Expected at least one CMake-installed local user guide in ${DOCDIR}" + printf 'Matched paths:\n' + printf ' %s\n' "$@" + exit 1 + fi + + if [ ! -f "${SOUNDDIR}/Wanted.wav" ]; then + echo "::error::Expected CMake-installed alert sound is missing: ${SOUNDDIR}/Wanted.wav" + exit 1 + fi + if [ ! -x "${APP}/Contents/MacOS/map65" ]; then + echo "::error::Expected CMake-installed MAP65 binary is missing: ${APP}/Contents/MacOS/map65" + exit 1 + fi + + if [ -e "${APP}/Contents/MacOS/sounds" ]; then + echo "::error::Alert sounds must not be installed under Contents/MacOS; codesign treats them as unsigned code." + exit 1 + fi + + echo "Verified CMake-installed data files in ${DATADIR}" + echo "Verified CMake-installed local user guides:" + printf ' %s\n' "$@" + echo "Verified CMake-installed alert sounds in ${SOUNDDIR}" + - name: Bundle dylibs into app run: | + set -Eeuo pipefail STAGE="${{ steps.collect.outputs.stage_dir }}" APP="${STAGE}/wsjtx.app" FRAMEWORKS="${APP}/Contents/Frameworks" - GCC_LIB="$(brew --prefix gcc)/lib/gcc/current" + FORTRAN_PREFIX="${{ steps.fc.outputs.prefix }}" + FORTRAN_ORIGINAL_PREFIX="${{ steps.fc.outputs.original_prefix }}" + GCC_LIB="${{ steps.fc.outputs.runtime_lib_dir }}" mkdir -p "${FRAMEWORKS}" - "$(brew --prefix qt@5)/bin/macdeployqt" "${APP}" -verbose=1 + dump_bundle_context() { + local status="$1" + local line="$2" + local command="$3" + echo "::error::Bundle dylibs into app failed at line ${line} with status ${status}: ${command}" + echo "APP=${APP}" + echo "FRAMEWORKS=${FRAMEWORKS}" + echo "FORTRAN_PREFIX=${FORTRAN_PREFIX}" + echo "FORTRAN_ORIGINAL_PREFIX=${FORTRAN_ORIGINAL_PREFIX}" + echo "GCC_LIB=${GCC_LIB}" + echo "HOMEBREW_PREFIX=${HOMEBREW_PREFIX}" + echo "App executable contents:" + ls -la "${APP}/Contents/MacOS" || true + echo "Framework contents:" + ls -la "${FRAMEWORKS}" || true + echo "External references in app executables:" + find "${APP}/Contents/MacOS" -type f -perm +111 -print -exec otool -L {} \; 2>/dev/null || true + if [ -f macdeployqt.log ]; then + echo "macdeployqt.log:" + cat macdeployqt.log + fi + } + trap 'status=$?; dump_bundle_context "$status" "$LINENO" "$BASH_COMMAND"; exit "$status"' ERR + + run_logged() { + echo "+ $*" + "$@" + } + + echo "Running macdeployqt..." + set +e + "${GITHUB_WORKSPACE}/qt-prefix/bin/macdeployqt" "${APP}" -verbose=2 > macdeployqt.log 2>&1 + status=$? + set -e + if [ "$status" -ne 0 ]; then + echo "::error::macdeployqt failed with status ${status}" + dump_bundle_context "$status" "$LINENO" "macdeployqt" + exit "$status" + fi + cat macdeployqt.log resolve_lib() { local lib="$1" + if [ -n "$FORTRAN_ORIGINAL_PREFIX" ] && [[ "$lib" == "$FORTRAN_ORIGINAL_PREFIX"/* ]]; then + local original_prefix="${FORTRAN_ORIGINAL_PREFIX}/" + local relocated="${FORTRAN_PREFIX}/${lib:${#original_prefix}}" + [ -f "$relocated" ] && echo "$relocated" && return 0 + fi if [[ "$lib" == $HOMEBREW_PREFIX/* ]]; then echo "$lib" + return 0 + elif [[ "$lib" == $GITHUB_WORKSPACE/* ]]; then + echo "$lib" + return 0 elif [[ "$lib" == @rpath/* ]]; then local name="${lib#@rpath/}" - for dir in "$GCC_LIB" "$HOMEBREW_PREFIX/lib"; do + for dir in \ + "$FRAMEWORKS" \ + "$GITHUB_WORKSPACE/boost-prefix/lib" \ + "$GITHUB_WORKSPACE/fftw-prefix/lib" \ + "$GITHUB_WORKSPACE/libusb-prefix/lib" \ + "$GITHUB_WORKSPACE/portaudio-prefix/lib" \ + "$FORTRAN_PREFIX/lib" \ + "$GCC_LIB" \ + "$HOMEBREW_PREFIX/lib" + do [ -f "$dir/$name" ] && echo "$dir/$name" && return done fi + return 0 + } + + should_bundle_ref() { + local ref="$1" + case "$ref" in + *Qt*.framework/*) + return 1 + ;; + "$FORTRAN_ORIGINAL_PREFIX"/*|"$HOMEBREW_PREFIX"/*|"$GITHUB_WORKSPACE"/*|@rpath/*) + return 0 + ;; + *) + return 1 + ;; + esac } bundle_dylib() { local binary="$1" - for lib in $(otool -L "$binary" | awk '{print $1}' | grep -E "($HOMEBREW_PREFIX|@rpath)" | grep -v Qt); do + local lib + while IFS= read -r lib; do + should_bundle_ref "$lib" || continue local resolved resolved=$(resolve_lib "$lib") - [ -z "$resolved" ] && continue - local libname=$(basename "$resolved") + if [ -z "$resolved" ]; then + echo "::error::Could not resolve ${lib} required by ${binary}" + exit 1 + fi + local libname + libname=$(basename "$resolved") + case "$libname" in + libgomp*.dylib) + echo "::error::Refusing to bundle ${resolved}; libgomp must be linked statically for deployable macOS artifacts." + exit 1 + ;; + esac if [ ! -f "${FRAMEWORKS}/${libname}" ]; then echo " Bundling: $resolved -> ${FRAMEWORKS}/${libname}" - cp "$resolved" "${FRAMEWORKS}/${libname}" - chmod 644 "${FRAMEWORKS}/${libname}" - install_name_tool -id "@executable_path/../Frameworks/${libname}" "${FRAMEWORKS}/${libname}" + run_logged cp "$resolved" "${FRAMEWORKS}/${libname}" + run_logged chmod 644 "${FRAMEWORKS}/${libname}" + run_logged install_name_tool -id "@rpath/${libname}" "${FRAMEWORKS}/${libname}" bundle_dylib "${FRAMEWORKS}/${libname}" fi - install_name_tool -change "$lib" "@executable_path/../Frameworks/${libname}" "$binary" 2>/dev/null || true - done + if [ "$lib" != "@rpath/${libname}" ]; then + run_logged install_name_tool -change "$lib" "@rpath/${libname}" "$binary" + fi + done < <(otool -L "$binary" | awk 'NR > 1 {print $1}' || true) + } + + ensure_app_rpath() { + local binary="$1" + local rpath + + while IFS= read -r rpath; do + [ -n "$rpath" ] || continue + case "$rpath" in + "$GITHUB_WORKSPACE"/*|"$HOMEBREW_PREFIX"/*) + run_logged install_name_tool -delete_rpath "$rpath" "$binary" + ;; + esac + done < <(otool -l "$binary" | awk '/LC_RPATH/{getline; getline; print $2}' || true) + + if ! otool -l "$binary" | awk '/LC_RPATH/{getline; getline; print $2}' | grep -Fxq "@executable_path/../Frameworks"; then + run_logged install_name_tool -add_rpath "@executable_path/../Frameworks" "$binary" + fi } for exe in "${APP}/Contents/MacOS/"*; do [ -f "$exe" ] && [ -x "$exe" ] && { + ensure_app_rpath "$exe" bundle_dylib "$exe" - for fw in $(otool -L "$exe" | awk '{print $1}' | grep '\.framework/'); do + for fw in $(otool -L "$exe" | awk '{print $1}' | grep '\.framework/' || true); do fwname=$(basename "$fw") bundled=$(find "${FRAMEWORKS}" -name "${fwname}" -path "*.framework/*" 2>/dev/null | head -1) if [ -n "$bundled" ]; then - fwrel="${bundled#${APP}/Contents/}" - install_name_tool -change "$fw" "@executable_path/../${fwrel}" "$exe" 2>/dev/null || true + app_contents="${APP}/Contents/" + fwrel="${bundled:${#app_contents}}" + if [ "$fw" != "@executable_path/../${fwrel}" ]; then + run_logged install_name_tool -change "$fw" "@executable_path/../${fwrel}" "$exe" + fi fi done } @@ -240,59 +625,225 @@ jobs: [ -f "$fw" ] && bundle_dylib "$fw" done + for exe in "${APP}/Contents/MacOS/"*; do + [ -f "$exe" ] && [ -x "$exe" ] && bundle_dylib "$exe" + done + echo "Checking for remaining external references..." - REMAINING=$(find "${APP}/Contents/MacOS" -type f -perm +111 -exec otool -L {} \; 2>/dev/null | grep "$HOMEBREW_PREFIX" || true) - if [ -n "$REMAINING" ]; then - echo "WARNING: External paths still present:" - echo "$REMAINING" + remaining_refs="${RUNNER_TEMP:-/tmp}/wsjtx-app-remaining-refs.txt" + : > "$remaining_refs" + while IFS= read -r binary; do + while IFS= read -r ref; do + case "$ref" in + "$FORTRAN_ORIGINAL_PREFIX"/*|"$HOMEBREW_PREFIX"/*|"$GITHUB_WORKSPACE"/*) + echo "${binary}: ${ref}" >> "$remaining_refs" + ;; + esac + done < <(otool -L "$binary" | awk 'NR > 1 {print $1}' || true) + done < <(find "${APP}/Contents/MacOS" -type f -perm +111 -print 2>/dev/null) + if [ -s "$remaining_refs" ]; then + echo "::error::External build-time paths still present:" + cat "$remaining_refs" + exit 1 else echo "All dylibs bundled successfully" fi - name: Bundle dylibs into CLI tools run: | + set -Eeuo pipefail ASSETS="${{ steps.collect.outputs.assets_dir }}" STAGE="${{ steps.collect.outputs.stage_dir }}" LIBDIR="${ASSETS}/lib" + FORTRAN_PREFIX="${{ steps.fc.outputs.prefix }}" + FORTRAN_ORIGINAL_PREFIX="${{ steps.fc.outputs.original_prefix }}" + GCC_LIB="${{ steps.fc.outputs.runtime_lib_dir }}" mkdir -p "${LIBDIR}" - BUNDLE_ARGS="" - for bin in "${ASSETS}"/*; do - [ -f "$bin" ] && [ -x "$bin" ] && [ "$(basename "$bin")" != "lib" ] && { - BUNDLE_ARGS="$BUNDLE_ARGS -x $bin" - } - done - dylibbundler -od -b $BUNDLE_ARGS -d "${LIBDIR}/" -p @loader_path/lib/ + dump_cli_context() { + local status="$1" + local line="$2" + local command="$3" + echo "::error::Bundle dylibs into CLI tools failed at line ${line} with status ${status}: ${command}" + echo "ASSETS=${ASSETS}" + echo "LIBDIR=${LIBDIR}" + echo "FORTRAN_PREFIX=${FORTRAN_PREFIX}" + echo "FORTRAN_ORIGINAL_PREFIX=${FORTRAN_ORIGINAL_PREFIX}" + echo "GCC_LIB=${GCC_LIB}" + echo "HOMEBREW_PREFIX=${HOMEBREW_PREFIX}" + echo "Asset contents:" + ls -la "${ASSETS}" || true + echo "Library contents:" + ls -la "${LIBDIR}" || true + echo "External references in CLI assets:" + for bin in "${ASSETS}"/*; do + [ -f "$bin" ] && [ -x "$bin" ] && [ "$(basename "$bin")" != "lib" ] || continue + echo "== $bin ==" + otool -L "$bin" || true + done + } + trap 'status=$?; dump_cli_context "$status" "$LINENO" "$BASH_COMMAND"; exit "$status"' ERR + + run_logged() { + echo "+ $*" + "$@" + } + + resolve_cli_ref() { + local ref="$1" + local name="" suffix="" + + if [ -n "$FORTRAN_ORIGINAL_PREFIX" ] && [[ "$ref" == "$FORTRAN_ORIGINAL_PREFIX"/* ]]; then + local original_prefix="${FORTRAN_ORIGINAL_PREFIX}/" + local relocated="${FORTRAN_PREFIX}/${ref:${#original_prefix}}" + [ -f "$relocated" ] && echo "$relocated" + return 0 + fi + + case "$ref" in + /usr/lib/*|/System/Library/*) + return 0 + ;; + @loader_path/lib/*) + name="${ref#@loader_path/lib/}" + [ -f "${LIBDIR}/${name}" ] && echo "${LIBDIR}/${name}" + return 0 + ;; + @loader_path/*) + name="${ref#@loader_path/}" + [ -f "${LIBDIR}/${name}" ] && echo "${LIBDIR}/${name}" + return 0 + ;; + "$GITHUB_WORKSPACE"/*|"$HOMEBREW_PREFIX"/*) + echo "$ref" + return 0 + ;; + esac + + if [[ "$ref" == @rpath/* ]]; then + suffix="${ref#@rpath/}" + if [[ "$suffix" == *.framework/* ]]; then + for dir in \ + "${STAGE}/wsjtx.app/Contents/Frameworks" \ + "${GITHUB_WORKSPACE}/qt-prefix/lib" + do + [ -f "${dir}/${suffix}" ] && echo "${dir}/${suffix}" && return 0 + done + else + name="${suffix}" + for dir in \ + "${LIBDIR}" \ + "${STAGE}/wsjtx.app/Contents/Frameworks" \ + "${GITHUB_WORKSPACE}/boost-prefix/lib" \ + "${GITHUB_WORKSPACE}/fftw-prefix/lib" \ + "${GITHUB_WORKSPACE}/libusb-prefix/lib" \ + "${GITHUB_WORKSPACE}/portaudio-prefix/lib" \ + "${FORTRAN_PREFIX}/lib" \ + "${GCC_LIB}" \ + "${HOMEBREW_PREFIX}/lib" + do + [ -f "${dir}/${name}" ] && echo "${dir}/${name}" && return 0 + done + fi + fi + + return 0 + } + + bundle_cli_deps() { + local binary="$1" + local change_prefix="$2" + local ref resolved out name target + + while IFS= read -r ref; do + resolved=$(resolve_cli_ref "$ref") + if [ -z "$resolved" ]; then + case "$ref" in + @rpath/*|@loader_path/*|"$GITHUB_WORKSPACE"/*|"$HOMEBREW_PREFIX"/*) + echo "::error::Could not resolve ${ref} required by ${binary}" + exit 1 + ;; + *) + continue + ;; + esac + fi + + name="$(basename "$resolved")" + case "$name" in + libgomp*.dylib) + echo "::error::Refusing to bundle ${resolved}; libgomp must be linked statically for deployable macOS artifacts." + exit 1 + ;; + esac + + out="${LIBDIR}/${name}" + if [ ! -f "$out" ]; then + echo " Bundling: ${resolved} -> ${out}" + run_logged cp "$resolved" "$out" + run_logged chmod 644 "$out" + run_logged install_name_tool -id "@rpath/${name}" "$out" + bundle_cli_deps "$out" "@rpath" + fi + + target="${change_prefix}/${name}" + if [ "$ref" != "$target" ]; then + run_logged install_name_tool -change "$ref" "$target" "$binary" + fi + done < <(otool -L "$binary" | awk 'NR > 1 {print $1}' | grep -E "($HOMEBREW_PREFIX|$GITHUB_WORKSPACE|@rpath|@loader_path)" || true) + } + + ensure_cli_rpath() { + local binary="$1" + local rpath + local bad_rpaths=() + local unique_bad_rpaths=() + + while IFS= read -r rpath; do + [ -n "$rpath" ] || continue + case "$rpath" in + "$GITHUB_WORKSPACE"/*|"$HOMEBREW_PREFIX"/*) + bad_rpaths+=("$rpath") + ;; + esac + done < <(otool -l "$binary" | awk '/LC_RPATH/{getline; getline; print $2}' || true) + + # Deduplicate bad rpaths (compatible with macOS Bash 3.2) + if [ "${#bad_rpaths[@]}" -gt 0 ]; then + for rpath in "${bad_rpaths[@]}"; do + local found=0 + local u + if [ "${#unique_bad_rpaths[@]}" -gt 0 ]; then + for u in "${unique_bad_rpaths[@]}"; do + [ "$u" = "$rpath" ] && found=1 && break + done + fi + [ "$found" -eq 0 ] && unique_bad_rpaths+=("$rpath") + done + fi + + if [ "${#unique_bad_rpaths[@]}" -gt 0 ]; then + for rpath in "${unique_bad_rpaths[@]}"; do + run_logged install_name_tool -delete_rpath "$rpath" "$binary" + done + fi + + if ! otool -l "$binary" | awk '/LC_RPATH/{getline; getline; print $2}' | grep -Fxq "@loader_path/lib"; then + run_logged install_name_tool -add_rpath "@loader_path/lib" "$binary" + fi + } - QT5="$(brew --prefix qt@5)/lib" for bin in "${ASSETS}"/*; do [ -f "$bin" ] && [ -x "$bin" ] && [ "$(basename "$bin")" != "lib" ] || continue - for fw in $(otool -L "$bin" | awk '{print $1}' | grep '\.framework/'); do - fwname=$(basename "$fw") - if [ ! -f "${LIBDIR}/${fwname}" ]; then - echo " Bundling framework: ${fwname}" - cp "$fw" "${LIBDIR}/${fwname}" - chmod 644 "${LIBDIR}/${fwname}" - install_name_tool -id "@loader_path/lib/${fwname}" "${LIBDIR}/${fwname}" - dylibbundler -b -x "${LIBDIR}/${fwname}" -d "${LIBDIR}/" -p @loader_path/ 2>/dev/null || true - fi - install_name_tool -change "$fw" "@loader_path/lib/${fwname}" "$bin" - codesign --force --sign - "$bin" - done + ensure_cli_rpath "$bin" + bundle_cli_deps "$bin" "@rpath" + run_logged codesign --force --sign - "$bin" done for lib in "${LIBDIR}"/*; do [ -f "$lib" ] || continue - for dep in $(otool -L "$lib" | awk '{print $1}' | grep '@loader_path/lib/'); do - depname=$(basename "$dep") - install_name_tool -change "$dep" "@loader_path/${depname}" "$lib" 2>/dev/null || true - done - RPATHS=$(otool -l "$lib" | grep -A2 LC_RPATH | grep "path " | awk '{print $2}' | sort | uniq -d) - for rp in $RPATHS; do - install_name_tool -delete_rpath "$rp" "$lib" 2>/dev/null || true - install_name_tool -add_rpath "$rp" "$lib" 2>/dev/null || true - done - codesign --force --sign - "$lib" + bundle_cli_deps "$lib" "@rpath" + run_logged codesign --force --sign - "$lib" done echo "Verifying CLI tools..." @@ -315,6 +866,14 @@ jobs: } done + - name: Verify bundled macOS deployment targets + run: | + STAGE="${{ steps.collect.outputs.stage_dir }}" + .github/scripts/verify-macos-artifacts.sh \ + --target "${{ inputs.deployment_target }}" \ + --arch "${{ inputs.arch }}" \ + "$STAGE" + - name: Import signing certificates if: steps.check_secrets.outputs.signing_enabled == 'true' env: @@ -385,11 +944,13 @@ jobs: # introduced as a workaround for the empty-plist parser bug.) find "${APP}/Contents/Frameworks" -type f \( -name "*.dylib" -o -perm +111 \) \ -exec codesign --force --options runtime $TS --sign "$IDENTITY" {} \; - find "${APP}/Contents/Frameworks" -name "*.framework" -type d | while read fw; do + find "${APP}/Contents/Frameworks" -name "*.framework" -type d | while read -r fw; do codesign --force --options runtime $TS --sign "$IDENTITY" "$fw" done - find "${APP}/Contents/PlugIns" -type f -name "*.dylib" \ - -exec codesign --force --options runtime $TS --sign "$IDENTITY" {} \; 2>/dev/null || true + if [ -d "${APP}/Contents/PlugIns" ]; then + find "${APP}/Contents/PlugIns" -type f -name "*.dylib" \ + -exec codesign --force --options runtime $TS --sign "$IDENTITY" {} \; + fi find "${APP}/Contents/MacOS" -type f -perm +111 \ -exec codesign --force --options runtime --entitlements "$ENTITLEMENTS" $TS --sign "$IDENTITY" {} \; @@ -430,7 +991,7 @@ jobs: # cert when secrets are present; produces an unsigned .pkg # otherwise. Either way the artifact is named identically and # satisfies the all-platforms-ready gate in release.yml. - - name: Build installer pkg + - name: Build and verify installer pkg run: | STAGE="${{ steps.collect.outputs.stage_dir }}" PKG_ID="org.k1jt.wsjtx.${{ inputs.arch }}" @@ -463,6 +1024,8 @@ jobs: pkgbuild --analyze --root "${PAYLOAD}" "$RUNNER_TEMP/components.plist" /usr/libexec/PlistBuddy -c "Set :0:BundleIsRelocatable false" "$RUNNER_TEMP/components.plist" 2>/dev/null || true + /usr/libexec/PlistBuddy -c "Set :0:BundleIsVersionChecked false" "$RUNNER_TEMP/components.plist" 2>/dev/null || true + /usr/libexec/PlistBuddy -c "Set :0:BundleOverwriteAction upgrade" "$RUNNER_TEMP/components.plist" 2>/dev/null || true pkgbuild \ --root "${PAYLOAD}" \ @@ -486,6 +1049,51 @@ jobs: "$PKG_OUT" fi + CHECK_PAYLOAD="$RUNNER_TEMP/pkg-check" + rm -rf "$CHECK_PAYLOAD" + pkgutil --expand-full "$PKG_OUT" "$CHECK_PAYLOAD" + [ "$(/usr/libexec/PlistBuddy -c "Print :0:BundleIsRelocatable" "$RUNNER_TEMP/components.plist")" = "false" ] + [ "$(/usr/libexec/PlistBuddy -c "Print :0:BundleIsVersionChecked" "$RUNNER_TEMP/components.plist")" = "false" ] + [ "$(/usr/libexec/PlistBuddy -c "Print :0:BundleOverwriteAction" "$RUNNER_TEMP/components.plist")" = "upgrade" ] + + APP_PAYLOAD="$CHECK_PAYLOAD/wsjtx-component.pkg/Payload/Applications/wsjtx.app" + DATADIR="${APP_PAYLOAD}/Contents/Resources/wsjtx" + DOCDIR="${APP_PAYLOAD}/Contents/Resources/doc/wsjtx" + SOUNDDIR="${APP_PAYLOAD}/Contents/Resources/sounds" + + for file in cty.dat cty.dat_copyright.txt grid.dat sat.dat eclipse.txt ALLCALL7.TXT JPLEPH; do + if [ ! -f "${DATADIR}/${file}" ]; then + echo "::error::Expected packaged data file is missing: ${DATADIR}/${file}" + exit 1 + fi + done + + set -- "${DOCDIR}/wsjtx-main"*.html + if [ "$#" -lt 1 ] || [ ! -f "$1" ]; then + echo "::error::Expected at least one local user guide in the packaged app bundle." + printf 'Matched paths:\n' + printf ' %s\n' "$@" + exit 1 + fi + + if [ ! -f "${SOUNDDIR}/Wanted.wav" ]; then + echo "::error::Expected packaged alert sound is missing: ${SOUNDDIR}/Wanted.wav" + exit 1 + fi + if [ ! -x "${APP_PAYLOAD}/Contents/MacOS/map65" ]; then + echo "::error::Expected packaged MAP65 binary is missing: ${APP_PAYLOAD}/Contents/MacOS/map65" + exit 1 + fi + + if [ -e "${APP_PAYLOAD}/Contents/MacOS/sounds" ]; then + echo "::error::Packaged alert sounds must not be under Contents/MacOS." + exit 1 + fi + + echo "Verified packaged local user guides:" + printf ' %s\n' "$@" + echo "Verified packaged alert sounds in ${SOUNDDIR}" + - name: Notarize pkg if: steps.check_secrets.outputs.signing_enabled == 'true' env: diff --git a/.github/workflows/build-windows.yml b/.github/workflows/build-windows.yml index fd0f14a5..1d6f8ec9 100644 --- a/.github/workflows/build-windows.yml +++ b/.github/workflows/build-windows.yml @@ -12,6 +12,16 @@ on: required: false type: string default: "4.7.0" + release_channel: + description: "Build release channel: DEVEL, RC, or GA" + required: false + type: string + default: "DEVEL" + rc_number: + description: "Release candidate number when release_channel is RC" + required: false + type: string + default: "" jobs: build: @@ -160,11 +170,12 @@ jobs: cmake -G "MSYS Makefiles" -S . -B wsjtx-build \ -DCMAKE_PREFIX_PATH="${WORKSPACE}/hamlib-prefix" \ -DOMNIRIG_TYPE_LIB="${OMNIRIG}" \ - -DWSJT_SKIP_MAP65=ON \ -DCMAKE_Fortran_FLAGS="-fallow-argument-mismatch -std=legacy" \ -DCMAKE_POLICY_VERSION_MINIMUM=3.5 \ -DWSJT_SKIP_MANPAGES=ON \ -DWSJT_BUILD_TESTS=ON \ + -DWSJT_RELEASE_CHANNEL="${{ inputs.release_channel }}" \ + -DWSJT_RC_NUMBER="${{ inputs.rc_number }}" \ -DPFUNIT_DIR="${{ steps.pfunit.outputs.pfunit_dir }}" \ -DGFTL_DIR="${{ steps.pfunit.outputs.gftl_dir }}" \ -DGFTL_SHARED_DIR="${{ steps.pfunit.outputs.gftl_shared_dir }}" \ @@ -195,6 +206,27 @@ jobs: - name: Verify binary run: | file wsjtx-build/jt9.exe + test -x wsjtx-build/map65/map65.exe + + - name: Stage install + run: | + WORKSPACE=$(cygpath "${GITHUB_WORKSPACE}") + cmake --install wsjtx-build --prefix "${WORKSPACE}/stage-main" + ls -la "${WORKSPACE}/stage-main/bin" + + - name: Audit staged runtime DLL imports + run: | + WORKSPACE=$(cygpath "${GITHUB_WORKSPACE}") + test -f "${WORKSPACE}/stage-main/bin/map65.exe" + test -f "${WORKSPACE}/stage-main/bin/qmap.exe" + test -f "${WORKSPACE}/stage-main/bin/wsjtx.exe" + test -f "${WORKSPACE}/stage-main/bin/jt9.exe" + bash .github/scripts/audit-staged-dll-imports-windows.sh \ + "${WORKSPACE}/stage-main/bin" \ + "${WORKSPACE}/stage-main/bin/map65.exe" \ + "${WORKSPACE}/stage-main/bin/qmap.exe" \ + "${WORKSPACE}/stage-main/bin/wsjtx.exe" \ + "${WORKSPACE}/stage-main/bin/jt9.exe" # Emit an NSIS installer containing the full CLI tool set # (wsjtx.exe, jt9, wsprd, fmtave, fcal, fmeasure + WSJT_BUILD_UTILS @@ -218,6 +250,7 @@ jobs: -D CPACK_PACKAGE_VERSION="${{ inputs.version }}" \ -D CPACK_PACKAGE_FILE_NAME="wsjtx-${{ inputs.version }}-win64" ls -la *.exe + test -x map65/map65.exe # Self-signed ephemeral signing — the signing step is wired into the # pipeline, but the signature does NOT chain to a trusted root. This @@ -268,5 +301,6 @@ jobs: name: wsjtx-${{ inputs.version }}-windows-x86_64 path: | wsjtx-build/jt9.exe + wsjtx-build/map65/map65.exe wsjtx-build/wsprd.exe wsjtx-build/wsjtx.exe diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 52592fb4..a1bf639a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,8 +28,24 @@ jobs: echo "Derived version from CMakeLists.txt: $VERSION" echo "version=$VERSION" >> "$GITHUB_OUTPUT" - macos: + macos-arm64-qt: + needs: prepare + uses: ./.github/workflows/prepare-macos-qt.yml + with: + arch: "arm64" + runner: "macos-15" + deployment_target: "11.0" + + macos-intel-qt: needs: prepare + uses: ./.github/workflows/prepare-macos-qt.yml + with: + arch: "x86_64" + runner: "macos-15-intel" + deployment_target: "10.13" + + macos: + needs: [prepare, macos-arm64-qt] uses: ./.github/workflows/build-macos.yml with: version: ${{ needs.prepare.outputs.version }} @@ -40,7 +56,7 @@ jobs: secrets: inherit macos-intel: - needs: prepare + needs: [prepare, macos-intel-qt] uses: ./.github/workflows/build-macos.yml with: version: ${{ needs.prepare.outputs.version }} diff --git a/.github/workflows/prepare-macos-qt.yml b/.github/workflows/prepare-macos-qt.yml new file mode 100644 index 00000000..de9f5fe5 --- /dev/null +++ b/.github/workflows/prepare-macos-qt.yml @@ -0,0 +1,73 @@ +name: Prepare macOS Qt + +on: + workflow_call: + inputs: + arch: + description: "Target architecture (arm64 or x86_64)" + required: true + type: string + runner: + description: "GitHub Actions runner label" + required: true + type: string + deployment_target: + description: "macOS deployment target version" + required: true + type: string + +jobs: + qt-cache-key: + runs-on: ubuntu-latest + outputs: + key: ${{ steps.qt-key.outputs.key }} + steps: + - uses: actions/checkout@v6 + + - name: Compute Qt cache key + id: qt-key + run: | + .github/scripts/macos-qt-cache-key.sh \ + --arch "${{ inputs.arch }}" \ + --runner "${{ inputs.runner }}" \ + --deployment-target "${{ inputs.deployment_target }}" \ + --github-output + + prepare: + needs: qt-cache-key + runs-on: ${{ inputs.runner }} + concurrency: + group: ${{ needs.qt-cache-key.outputs.key }} + cancel-in-progress: false + steps: + - uses: actions/checkout@v6 + + - name: Restore Qt cache + id: qt-cache + uses: actions/cache/restore@v5 + with: + path: qt-prefix + key: ${{ needs.qt-cache-key.outputs.key }} + + - name: Build Qt + if: steps.qt-cache.outputs.cache-hit != 'true' + run: | + .github/scripts/build-qt-macos.sh \ + --arch "${{ inputs.arch }}" \ + --deployment-target "${{ inputs.deployment_target }}" \ + --prefix "${GITHUB_WORKSPACE}/qt-prefix" + + - name: Verify Qt prefix + run: | + .github/scripts/verify-macos-artifacts.sh \ + --target "${{ inputs.deployment_target }}" \ + --arch "${{ inputs.arch }}" \ + --allow-prefix "${GITHUB_WORKSPACE}/qt-prefix" \ + "${GITHUB_WORKSPACE}/qt-prefix" + + - name: Save Qt cache + if: steps.qt-cache.outputs.cache-hit != 'true' + uses: actions/cache/save@v5 + with: + path: qt-prefix + key: ${{ needs.qt-cache-key.outputs.key }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index be547624..a8b9bd42 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -15,10 +15,30 @@ jobs: runs-on: ubuntu-latest outputs: version: ${{ steps.v.outputs.version }} + release_channel: ${{ steps.v.outputs.release_channel }} + rc_number: ${{ steps.v.outputs.rc_number }} steps: - uses: actions/checkout@v6 - id: v - run: echo "version=${GITHUB_REF_NAME#build/v}" >> "$GITHUB_OUTPUT" + run: | + VERSION="${GITHUB_REF_NAME#build/v}" + if [[ "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + RELEASE_CHANNEL=GA + RC_NUMBER="" + elif [[ "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+-rc([1-9][0-9]*)$ ]]; then + RELEASE_CHANNEL=RC + RC_NUMBER="${BASH_REMATCH[1]}" + else + echo "::error::Unsupported release tag version: $VERSION" + echo "::error::Supported release tags are build/vX.Y.Z and build/vX.Y.Z-rcN." + exit 1 + fi + + { + echo "version=$VERSION" + echo "release_channel=$RELEASE_CHANNEL" + echo "rc_number=$RC_NUMBER" + } >> "$GITHUB_OUTPUT" # Enforce that the pushed tag's numeric version base # matches CMakeLists.txt:55 VERSION (first 3 components). CMake's @@ -45,8 +65,24 @@ jobs: echo "Parity check PASSED." # ── Build all five platforms ─────────────────────────────────────── - macos: + macos-arm64-qt: + needs: prepare + uses: ./.github/workflows/prepare-macos-qt.yml + with: + arch: "arm64" + runner: "macos-15" + deployment_target: "11.0" + + macos-intel-qt: needs: prepare + uses: ./.github/workflows/prepare-macos-qt.yml + with: + arch: "x86_64" + runner: "macos-15-intel" + deployment_target: "10.13" + + macos: + needs: [prepare, macos-arm64-qt] uses: ./.github/workflows/build-macos.yml with: version: ${{ needs.prepare.outputs.version }} @@ -54,15 +90,19 @@ jobs: arch: "arm64" runner: "macos-15" deployment_target: "11.0" + release_channel: ${{ needs.prepare.outputs.release_channel }} + rc_number: ${{ needs.prepare.outputs.rc_number }} secrets: inherit macos-intel: - needs: prepare + needs: [prepare, macos-intel-qt] uses: ./.github/workflows/build-macos.yml with: version: ${{ needs.prepare.outputs.version }} hamlib_branch: "4.7.1" arch: "x86_64" + release_channel: ${{ needs.prepare.outputs.release_channel }} + rc_number: ${{ needs.prepare.outputs.rc_number }} runner: "macos-15-intel" deployment_target: "10.13" secrets: inherit @@ -74,6 +114,8 @@ jobs: version: ${{ needs.prepare.outputs.version }} hamlib_branch: "4.7.1" arch: "x86_64" + release_channel: ${{ needs.prepare.outputs.release_channel }} + rc_number: ${{ needs.prepare.outputs.rc_number }} secrets: inherit linux-arm: @@ -83,6 +125,8 @@ jobs: version: ${{ needs.prepare.outputs.version }} hamlib_branch: "4.7.1" arch: "aarch64" + release_channel: ${{ needs.prepare.outputs.release_channel }} + rc_number: ${{ needs.prepare.outputs.rc_number }} secrets: inherit windows: @@ -91,6 +135,8 @@ jobs: with: version: ${{ needs.prepare.outputs.version }} hamlib_branch: "4.7.1" + release_channel: ${{ needs.prepare.outputs.release_channel }} + rc_number: ${{ needs.prepare.outputs.rc_number }} secrets: inherit # ── Publish release + sync to public repo ────────────────────────── @@ -205,7 +251,7 @@ jobs: # that collide on basename across architectures — `gh release # create` uses basenames as asset names and duplicates cause # upload failures. - FILES=$(find artifacts -maxdepth 2 -type f \ + mapfile -t files < <(find artifacts -maxdepth 2 -type f \ \( -name "*.pkg" -o -name "*.AppImage" -o -name "*.deb" \ -o -name "*.exe" -o -name "*.tar.gz" -o -name "*.rpm" \)) # SemVer pre-release tags contain a hyphen after the version @@ -219,7 +265,7 @@ jobs: --title "WSJT-X ${{ needs.prepare.outputs.version }}" \ --generate-notes \ $PRERELEASE_FLAG \ - $FILES + "${files[@]}" # ── Public mirror: GA only ───────────────────────────────────────── # RC/beta tags (any tag carrying a '-' in the version, e.g. @@ -303,11 +349,11 @@ jobs: # Same asset filter as the internal release. Re-find rather than # carrying a list — keeps the all-platforms-ready gate, internal # release, and public release mechanically aligned on one filter. - FILES=$(find artifacts -maxdepth 2 -type f \ + mapfile -t files < <(find artifacts -maxdepth 2 -type f \ \( -name "*.pkg" -o -name "*.AppImage" -o -name "*.deb" \ -o -name "*.exe" -o -name "*.tar.gz" -o -name "*.rpm" \)) gh release create "$PUBLIC_TAG" \ -R WSJTX/wsjtx \ --title "WSJT-X ${VERSION}" \ --generate-notes \ - $FILES + "${files[@]}" diff --git a/Audio/BWFFile.cpp b/Audio/BWFFile.cpp index 78d6a79f..5ddf9d8b 100644 --- a/Audio/BWFFile.cpp +++ b/Audio/BWFFile.cpp @@ -18,6 +18,95 @@ namespace { + qint64 constexpr riff_type_size = 4; + int constexpr max_chunk_read_size = (std::numeric_limits<int>::max) (); + + bool checked_add (qint64 lhs, qint64 rhs, qint64 * result) + { + if (!result) + { + return false; + } + + if ((rhs > 0 && lhs > (std::numeric_limits<qint64>::max) () - rhs) || + (rhs < 0 && lhs < (std::numeric_limits<qint64>::min) () - rhs)) + { + return false; + } + + *result = lhs + rhs; + return true; + } + + bool checked_padded_chunk_size (quint32 raw_size, qint64 * padded_size) + { + return checked_add (raw_size, raw_size & 1u, padded_size); + } + + bool checked_chunk_end (qint64 payload_offset, quint32 raw_size, qint64 limit, qint64 * end) + { + qint64 padded_size; + return checked_padded_chunk_size (raw_size, &padded_size) && + checked_add (payload_offset, padded_size, end) && + payload_offset >= 0 && *end <= limit; + } + + bool checked_chunk_payload_end (qint64 payload_offset, quint32 raw_size, qint64 limit, qint64 * end) + { + return checked_add (payload_offset, raw_size, end) && + payload_offset >= 0 && *end <= limit; + } + + bool read_bounded_chunk (QFile& file, quint32 raw_size, QByteArray * out) + { + if (!out || raw_size > static_cast<quint32> (max_chunk_read_size)) + { + return false; + } + + auto data = file.read (static_cast<int> (raw_size)); + if (data.size () != static_cast<int> (raw_size)) + { + return false; + } + + *out = data; + return true; + } + + bool valid_pcm_format (quint16 channels, quint32 sample_rate, quint16 bits_per_sample) + { + return channels && sample_rate && bits_per_sample && !(bits_per_sample % 8); + } + + template <size_t N> + QByteArray fixed_field_value (char const (&field)[N]) + { + auto const * end = static_cast<char const *> (::memchr (field, '\0', N)); + auto const length = end ? end - field : static_cast<ptrdiff_t> (N); + return QByteArray {field, static_cast<int> (length)}; + } + + template <size_t N> + QString fixed_field_prefix_string (char const (&field)[N], int max_length) + { + auto const bounded_length = std::min (max_length, static_cast<int> (N)); + auto const * end = static_cast<char const *> (::memchr (field, '\0', bounded_length)); + auto const length = end ? static_cast<int> (end - field) : bounded_length; + return QString::fromLatin1 (field, length); + } + + template <size_t N> + void assign_fixed_field (char (&field)[N], QByteArray const& value) + { + ::memset (field, '\0', N); + auto const length = std::min (value.size (), static_cast<int> (N)); + if (length > 0) + { + ::memcpy (field, value.constData (), static_cast<size_t> (length)); + } + } + // chunk descriptor struct Desc { @@ -63,6 +152,8 @@ namespace quint32 size_; }; + qint64 constexpr chunk_header_size = sizeof (Desc); + // "fmt " chunk contents struct FormatChunk { @@ -208,44 +299,64 @@ bool BWFFile::impl::read_header () if (!(file_.openMode () & ReadOnly)) return false; if (!file_.seek (0)) return false; Desc outer_desc; - quint32 outer_offset = file_.pos (); + auto const file_size = file_.size (); + qint64 outer_offset = file_.pos (); quint32 outer_size {0}; bool be {false}; - while (outer_offset < sizeof outer_desc + outer_desc.size_ - 1) // allow for uncounted pad + while (outer_offset + chunk_header_size <= file_size) { if (file_.read (&outer_desc, sizeof outer_desc) != sizeof outer_desc) return false; be = !memcmp (&outer_desc.id_, "RIFX", 4); outer_size = be ? qFromBigEndian<quint32> (outer_desc.size_) : qFromLittleEndian<quint32> (outer_desc.size_); + qint64 outer_chunk_end; + if (!checked_chunk_end (file_.pos (), outer_size, file_size, &outer_chunk_end)) return false; if (!memcmp (&outer_desc.id_, "RIFF", 4) || be) { // RIFF or RIFX + if (outer_size < static_cast<quint32> (riff_type_size)) return false; char riff_item[4]; if (file_.read (riff_item, sizeof riff_item) != sizeof riff_item) return false; if (!memcmp (riff_item, "WAVE", 4)) { // WAVE Desc wave_desc; - quint32 wave_offset = file_.pos (); + qint64 wave_offset = file_.pos (); quint32 wave_size {0}; - while (wave_offset < outer_offset + sizeof outer_desc + outer_size - 1) + while (wave_offset + chunk_header_size <= outer_chunk_end) { if (file_.read (&wave_desc, sizeof wave_desc) != sizeof wave_desc) return false; wave_size = be ? qFromBigEndian<quint32> (wave_desc.size_) : qFromLittleEndian<quint32> (wave_desc.size_); + auto const wave_payload_offset = file_.pos (); + qint64 wave_payload_end; + qint64 wave_chunk_end; + if (!checked_chunk_payload_end (wave_payload_offset, wave_size, outer_chunk_end, &wave_payload_end) || + !checked_chunk_end (wave_payload_offset, wave_size, outer_chunk_end, &wave_chunk_end)) + { + return false; + } if (!memcmp (&wave_desc.id_, "bext", 4)) { - bext_ = file_.read (wave_size); + if (wave_size < sizeof (BroadcastAudioExtension) || + !read_bounded_chunk (file_, wave_size, &bext_)) + { + return false; + } } if (!memcmp (&wave_desc.id_, "fmt ", 4)) { + if (wave_size < sizeof (FormatChunk)) return false; FormatChunk fmt; if (file_.read (reinterpret_cast<char *> (&fmt), sizeof fmt) != sizeof fmt) return false; - auto audio_format = be ? qFromBigEndian<quint16> (fmt.audio_format) : qFromLittleEndian<quint16> (fmt.audio_format); + auto const audio_format = be ? qFromBigEndian<quint16> (fmt.audio_format) : qFromLittleEndian<quint16> (fmt.audio_format); if (audio_format != 0 && audio_format != 1) return false; // not PCM nor undefined + auto const channels = be ? qFromBigEndian<quint16> (fmt.num_channels) : qFromLittleEndian<quint16> (fmt.num_channels); + auto const sample_rate = be ? qFromBigEndian<quint32> (fmt.sample_rate) : qFromLittleEndian<quint32> (fmt.sample_rate); + auto const bits_per_sample = be ? qFromBigEndian<quint16> (fmt.bits_per_sample) : qFromLittleEndian<quint16> (fmt.bits_per_sample); + if (!valid_pcm_format (channels, sample_rate, bits_per_sample)) return false; format_.setByteOrder (be ? QAudioFormat::BigEndian : QAudioFormat::LittleEndian); - format_.setChannelCount (be ? qFromBigEndian<quint16> (fmt.num_channels) : qFromLittleEndian<quint16> (fmt.num_channels)); + format_.setChannelCount (channels); format_.setCodec ("audio/pcm"); - format_.setSampleRate (be ? qFromBigEndian<quint32> (fmt.sample_rate) : qFromLittleEndian<quint32> (fmt.sample_rate)); - int bits_per_sample {be ? qFromBigEndian<quint16> (fmt.bits_per_sample) : qFromLittleEndian<quint16> (fmt.bits_per_sample)}; + format_.setSampleRate (sample_rate); format_.setSampleSize (bits_per_sample); format_.setSampleType (8 == bits_per_sample ? QAudioFormat::UnSignedInt : QAudioFormat::SignedInt); } @@ -256,29 +367,38 @@ bool BWFFile::impl::read_header () } else if (!memcmp (&wave_desc.id_, "LIST", 4)) { + if (wave_size < static_cast<quint32> (riff_type_size)) return false; char list_type[4]; if (file_.read (list_type, sizeof list_type) != sizeof list_type) return false; if (!memcmp (list_type, "INFO", 4)) { Desc info_desc; - quint32 info_offset = file_.pos (); + qint64 info_offset = file_.pos (); quint32 info_size {0}; - while (info_offset < wave_offset + sizeof wave_desc + wave_size - 1) + while (info_offset + chunk_header_size <= wave_payload_end) { if (file_.read (&info_desc, sizeof info_desc) != sizeof info_desc) return false; info_size = be ? qFromBigEndian<quint32> (info_desc.size_) : qFromLittleEndian<quint32> (info_desc.size_); - info_dictionary_[info_desc.id_] = file_.read (info_size); - if (!file_.seek (info_offset + sizeof info_desc + (info_size + 1) / 2 * 2)) return false;; + auto const info_payload_offset = file_.pos (); + qint64 info_payload_end; + qint64 info_chunk_end; + if (!checked_chunk_payload_end (info_payload_offset, info_size, wave_payload_end, &info_payload_end) || + !checked_chunk_end (info_payload_offset, info_size, wave_chunk_end, &info_chunk_end) || + !read_bounded_chunk (file_, info_size, &info_dictionary_[info_desc.id_])) + { + return false; + } + if (!file_.seek (info_chunk_end)) return false; info_offset = file_.pos (); } } } - if (!file_.seek (wave_offset + sizeof wave_desc + (wave_size + 1) / 2 * 2)) return false; + if (!file_.seek (wave_chunk_end)) return false; wave_offset = file_.pos (); } } } - if (!file_.seek (outer_offset + sizeof outer_desc + (outer_size + 1) / 2 * 2)) return false; + if (!file_.seek (outer_chunk_end)) return false; outer_offset = file_.pos (); } return data_size_ >= 0 && file_.seek (header_length_); @@ -670,7 +790,7 @@ auto BWFFile::list_info () -> InfoDictionary& // Broadcast Audio Extension fields auto BWFFile::bext_version () const -> BextVersion { - return static_cast<BextVersion> (m_->bext () ? 0 : m_->bext ()->version_); + return static_cast<BextVersion> (m_->bext () ? m_->bext ()->version_ : 0); } void BWFFile::bext_version (BextVersion version) @@ -682,55 +802,53 @@ void BWFFile::bext_version (BextVersion version) QByteArray BWFFile::bext_description () const { if (!m_->bext ()) return {}; - return QByteArray::fromRawData (m_->bext ()->description_, strlen (m_->bext ()->description_)); + return fixed_field_value (m_->bext ()->description_); } void BWFFile::bext_description (QByteArray const& description) { m_->header_dirty_ = true; - ::memcpy (m_->bext ()->description_, description.constData (), sizeof BroadcastAudioExtension::description_); + assign_fixed_field (m_->bext ()->description_, description); } QByteArray BWFFile::bext_originator () const { if (!m_->bext ()) return {}; - return QByteArray::fromRawData (m_->bext ()->originator_, strlen (m_->bext ()->originator_)); + return fixed_field_value (m_->bext ()->originator_); } void BWFFile::bext_originator (QByteArray const& originator) { m_->header_dirty_ = true; - ::memcpy (m_->bext ()->originator_, originator.constData (), sizeof BroadcastAudioExtension::originator_); + assign_fixed_field (m_->bext ()->originator_, originator); } QByteArray BWFFile::bext_originator_reference () const { if (!m_->bext ()) return {}; - return QByteArray::fromRawData (m_->bext ()->originator_reference_, strlen (m_->bext ()->originator_reference_)); + return fixed_field_value (m_->bext ()->originator_reference_); } void BWFFile::bext_originator_reference (QByteArray const& reference) { m_->header_dirty_ = true; - ::memcpy (m_->bext ()->originator_reference_, reference.constData (), sizeof BroadcastAudioExtension::originator_reference_); + assign_fixed_field (m_->bext ()->originator_reference_, reference); } QDateTime BWFFile::bext_origination_date_time () const { if (!m_->bext ()) return {}; - return {QDate::fromString (m_->bext ()->origination_date_, "yyyy-MM-dd"), - QTime::fromString (m_->bext ()->origination_time_, "hh-mm-ss"), Qt::UTC}; + return {QDate::fromString (fixed_field_prefix_string (m_->bext ()->origination_date_, 10), "yyyy-MM-dd"), + QTime::fromString (fixed_field_prefix_string (m_->bext ()->origination_time_, 8), "hh-mm-ss"), Qt::UTC}; } void BWFFile::bext_origination_date_time (QDateTime const& dt) { m_->header_dirty_ = true; - ::memcpy (m_->bext ()->origination_date_, - dt.date ().toString ("yyyy-MM-dd").toLocal8Bit ().constData (), - sizeof BroadcastAudioExtension::origination_date_); - ::memcpy (m_->bext ()->origination_time_, - dt.time ().toString ("hh-mm-ss").toLocal8Bit ().constData (), - sizeof BroadcastAudioExtension::origination_time_); + assign_fixed_field (m_->bext ()->origination_date_, + dt.date ().toString ("yyyy-MM-dd").toLocal8Bit ()); + assign_fixed_field (m_->bext ()->origination_time_, + dt.time ().toString ("hh-mm-ss").toLocal8Bit ()); } quint64 BWFFile::bext_time_reference () const @@ -825,8 +943,8 @@ void BWFFile::bext_max_short_term_loudness (quint16 loudness) QByteArray BWFFile::bext_coding_history () const { if (size_t (m_->bext_.size ()) <= sizeof (BroadcastAudioExtension)) return {}; - return QByteArray::fromRawData (m_->bext ()->coding_history_, - m_->bext_.size () - sizeof (BroadcastAudioExtension)); + return QByteArray {m_->bext ()->coding_history_, + static_cast<int> (m_->bext_.size () - sizeof (BroadcastAudioExtension))}; } void BWFFile::bext_coding_history (QByteArray const& text) diff --git a/CMake/Modules/NSIS.template.in b/CMake/Modules/NSIS.template.in index 9e171e28..b14a8623 100644 --- a/CMake/Modules/NSIS.template.in +++ b/CMake/Modules/NSIS.template.in @@ -970,6 +970,22 @@ SectionEnd ; "Program Files" for AllUsers, "My Documents" for JustMe... Function .onInit + ; --- WSJT-X running-process check (custom) --- + ; Abort cleanly if WSJT-X is already running, to avoid a half-installed + ; mess when the user upgrades over a live instance. Uses tasklist+findstr + ; (built into every supported Windows version) so no NSIS plugin is + ; required. + wsjtx_running_check: + nsExec::Exec '"$SYSDIR\cmd.exe" /c tasklist /FI "IMAGENAME eq wsjtx.exe" 2>NUL | $SYSDIR\findstr.exe /I "wsjtx.exe" >NUL' + Pop $0 + ${If} $0 == "0" + MessageBox MB_RETRYCANCEL|MB_ICONEXCLAMATION \ + "WSJT-X is currently running. $\n$\nPlease close it before installing or upgrading." \ + /SD IDCANCEL IDRETRY wsjtx_running_check + Abort + ${EndIf} + ; --- end WSJT-X running-process check --- + Push $0 Push $1 Push $2 diff --git a/CMake/Modules/generate_version_info.cmake b/CMake/Modules/generate_version_info.cmake index b746aaba..4fc6c4a4 100644 --- a/CMake/Modules/generate_version_info.cmake +++ b/CMake/Modules/generate_version_info.cmake @@ -115,7 +115,7 @@ function(generate_version_info outfiles) endif() endif() - if (NOT PROJECT_VERSION_REVISION AND BUILD_TYPE_REVISION) + if (NOT PRODUCT_VERSION_REVISION AND BUILD_TYPE_REVISION) set (PRODUCT_VERSION_REVISION ${BUILD_TYPE_REVISION}) endif () diff --git a/CMake/Modules/set_build_type.cmake b/CMake/Modules/set_build_type.cmake index 1f1f1273..9305c0e7 100644 --- a/CMake/Modules/set_build_type.cmake +++ b/CMake/Modules/set_build_type.cmake @@ -20,6 +20,10 @@ include (CMakeParseArguments) # variable BUIlD_TYPE_REVISION is unset. # macro (set_build_type) + set (WSJT_RELEASE_CHANNEL "DEVEL" CACHE STRING "Build release channel: DEVEL, RC, or GA.") + set_property (CACHE WSJT_RELEASE_CHANNEL PROPERTY STRINGS DEVEL RC GA) + set (WSJT_RC_NUMBER "" CACHE STRING "Release candidate number used when WSJT_RELEASE_CHANNEL is RC.") + set (options GA) set (oneValueArgs RC) set (multiValueArgs) @@ -31,12 +35,36 @@ macro (set_build_type) if (BUILD_TYPE_GA AND BUILD_TYPE_RC) message (FATAL_ERROR "Only specify one build type from RC or GA.") endif () - if (NOT BUILD_TYPE_GA) - if (BUILD_TYPE_RC) - set (BUILD_TYPE_REVISION "-rc${BUILD_TYPE_RC}") + + string (TOUPPER "${WSJT_RELEASE_CHANNEL}" _WSJT_RELEASE_CHANNEL) + if (ARGC GREATER 0) + if (BUILD_TYPE_GA) + set (_WSJT_RELEASE_CHANNEL "GA") + elseif (BUILD_TYPE_RC) + if ("${BUILD_TYPE_RC}" STREQUAL "0") + set (_WSJT_RELEASE_CHANNEL "DEVEL") + else () + set (_WSJT_RELEASE_CHANNEL "RC") + set (WSJT_RC_NUMBER "${BUILD_TYPE_RC}") + endif () else () - set (BUILD_TYPE_REVISION "-devel") + set (_WSJT_RELEASE_CHANNEL "DEVEL") + endif () + endif () + + if (NOT _WSJT_RELEASE_CHANNEL MATCHES "^(DEVEL|RC|GA)$") + message (FATAL_ERROR "WSJT_RELEASE_CHANNEL must be DEVEL, RC, or GA; got \"${WSJT_RELEASE_CHANNEL}\".") + endif () + + set (BUILD_TYPE_REVISION "") + if (_WSJT_RELEASE_CHANNEL STREQUAL "DEVEL") + set (BUILD_TYPE_REVISION "-devel") + elseif (_WSJT_RELEASE_CHANNEL STREQUAL "RC") + if (NOT WSJT_RC_NUMBER MATCHES "^[1-9][0-9]*$") + message (FATAL_ERROR "WSJT_RC_NUMBER must be a positive integer when WSJT_RELEASE_CHANNEL is RC.") endif () + set (BUILD_TYPE_REVISION "-rc${WSJT_RC_NUMBER}") endif () - message (STATUS "Building ${PROJECT_NAME} v${PROJECT_VERSION}${BUILD_TYPE_REVISION}") + set (WSJT_RELEASE_CHANNEL "${_WSJT_RELEASE_CHANNEL}" CACHE STRING "Build release channel: DEVEL, RC, or GA." FORCE) + message (STATUS "Building ${PROJECT_NAME} v${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH}${BUILD_TYPE_REVISION}") endmacro () diff --git a/CMakeLists.txt b/CMakeLists.txt index 087b2a49..4b725654 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10,11 +10,27 @@ if (APPLE) # # otool -l <binary> | grep -A3 LC_VERSION_MIN_MACOSX # - set (CMAKE_OSX_DEPLOYMENT_TARGET 10.12 - CACHE STRING "Earliest version of macOS supported + if (NOT CMAKE_OSX_DEPLOYMENT_TARGET) + if (DEFINED ENV{MACOSX_DEPLOYMENT_TARGET} AND NOT "$ENV{MACOSX_DEPLOYMENT_TARGET}" STREQUAL "") + set (_WSJTX_MACOS_DEPLOYMENT_TARGET "$ENV{MACOSX_DEPLOYMENT_TARGET}") + else () + set (_WSJTX_MACOS_ARCHITECTURES "${CMAKE_OSX_ARCHITECTURES}") + if (NOT _WSJTX_MACOS_ARCHITECTURES) + execute_process (COMMAND uname -m + OUTPUT_VARIABLE _WSJTX_MACOS_ARCHITECTURES + OUTPUT_STRIP_TRAILING_WHITESPACE) + endif () + + if (_WSJTX_MACOS_ARCHITECTURES MATCHES "(^|;)arm64($|;)") + set (_WSJTX_MACOS_DEPLOYMENT_TARGET 11.0) + else () + set (_WSJTX_MACOS_DEPLOYMENT_TARGET 10.13) + endif () + endif () -Earliest version we can support with Qt 5.12, C++11 & libc++ is 10.12. -Do not override this if you intend to build an official deployable installer.") + set (CMAKE_OSX_DEPLOYMENT_TARGET "${_WSJTX_MACOS_DEPLOYMENT_TARGET}" + CACHE STRING "Earliest macOS version supported by the target architecture") + endif () endif (APPLE) # @@ -45,7 +61,7 @@ if (POLICY CMP0075) endif () project (wsjtx - VERSION 3.0.1.0 + VERSION 3.0.2.0 LANGUAGES C CXX Fortran ) set (PROJECT_DESCRIPTION "WSJT-X: Digital Modes for Weak Signal Communications in Amateur Radio") @@ -91,8 +107,8 @@ message (STATUS "Building for for: ${CMAKE_SYSTEM_NAME}-${PROJECT_ARCHITECTURE}" message (STATUS "******************************************************") include (set_build_type) -# RC 0 or omitted is a development build, GA is a General Availability release build -set_build_type (GA) +# Default is a development build; release jobs pass RC or GA explicitly. +set_build_type () set (wsjtx_VERSION "${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH}${BUILD_TYPE_REVISION}") # @@ -134,6 +150,7 @@ include (CMakeDependentOption) OPTION (BUILD_SHARED_LIBS "Build Shared Libraries" OFF) # Set the LIB_TYPE variable to STATIC SET (LIB_TYPE STATIC) +set (WSJT_SOURCE_REVISION "" CACHE STRING "Source revision associated with this build") if (BUILD_SHARED_LIBS) # User wants to build Dynamic Libraries, so change the LIB_TYPE variable to CMake keyword 'SHARED' set (LIB_TYPE SHARED) @@ -151,7 +168,9 @@ option (WSJT_GENERATE_DOCS "Generate documentation files." ON) option (WSJT_RIG_NONE_CAN_SPLIT "Allow split operation with \"None\" as rig.") option (WSJT_TRACE_UDP "Debugging option that turns on UDP message protocol diagnostics.") option (WSJT_BUILD_UTILS "Build simulators and code demonstrators." ON) +option (WSJT_BUILD_TESTS "Build test programs." ON) option (WSJT_FOX_OTP "Enable Fox OTP Verification Messages." ON) +option (WSJT_SKIP_BUNDLE_FIXUP "Skip install-time bundle dependency fixup." OFF) option (WSJT_SKIP_MAP65 "Skip building MAP65 EME decoder (legacy Fortran; fails on GCC 15)." OFF) CMAKE_DEPENDENT_OPTION (WSJT_QDEBUG_IN_RELEASE "Leave Qt debugging statements in Release configuration." OFF "NOT is_debug_build" OFF) @@ -233,6 +252,7 @@ set (wsjt_qt_CXXSRCS Transceiver/PollingTransceiver.cpp Transceiver/HamlibTransceiver.cpp Transceiver/TCITransceiver.cpp + Transceiver/HRDMessage.cpp Transceiver/HRDTransceiver.cpp Transceiver/DXLabSuiteCommanderTransceiver.cpp Network/NetworkMessage.cpp @@ -295,6 +315,8 @@ set (wsjtx_CXXSRCS WSJTXLogging.cpp logbook/logbook.cpp Network/PSKReporter.cpp + Network/PSKReporterConfiguration.cpp + Network/PSKReporterIPFIX.cpp Modulator/Modulator.cpp Detector/Detector.cpp widgets/logqso.cpp @@ -1032,6 +1054,21 @@ find_package (Boost 1.62 REQUIRED COMPONENTS log_setup log) # find_package (OpenMP) +if (APPLE) + set (WSJT_MACOS_LIBGOMP_LIBRARY "" CACHE FILEPATH "Path to the static GNU OpenMP runtime archive") + if (NOT WSJT_MACOS_LIBGOMP_LIBRARY) + execute_process ( + COMMAND ${CMAKE_Fortran_COMPILER} -print-file-name=libgomp.a + OUTPUT_VARIABLE WSJT_MACOS_LIBGOMP_LIBRARY + OUTPUT_STRIP_TRAILING_WHITESPACE + ERROR_QUIET + ) + endif () + if (NOT WSJT_MACOS_LIBGOMP_LIBRARY OR NOT EXISTS "${WSJT_MACOS_LIBGOMP_LIBRARY}") + message (FATAL_ERROR "Static GNU OpenMP runtime archive not found. Install a GNU Fortran/OpenMP runtime that provides libgomp.a, or set WSJT_MACOS_LIBGOMP_LIBRARY to the archive path. Deployable macOS builds intentionally link libgomp statically instead of bundling a package-manager libgomp dylib.") + endif () +endif () + # # fftw3 single precision library # @@ -1264,7 +1301,8 @@ endif () if (WSJT_GENERATE_DOCS) add_subdirectory (doc) endif (WSJT_GENERATE_DOCS) -if (EXISTS ${CMAKE_SOURCE_DIR}/tests AND IS_DIRECTORY ${CMAKE_SOURCE_DIR}/tests) +if (WSJT_BUILD_TESTS AND EXISTS ${CMAKE_SOURCE_DIR}/tests AND IS_DIRECTORY ${CMAKE_SOURCE_DIR}/tests) + enable_testing () add_subdirectory (tests) endif () @@ -1300,6 +1338,13 @@ if (${OPENMP_FOUND} OR APPLE) endif (APPLE) endif (${OPENMP_FOUND} OR APPLE) +add_library (wsjt_fort_common INTERFACE) +target_link_libraries (wsjt_fort_common INTERFACE wsjt_fort wsjt_cxx) + +function (wsjt_link_common_fortran tgt) + target_link_libraries (${tgt} PUBLIC wsjt_fort_common) +endfunction () + if(WSJT_BUILD_UTILS) add_executable (jt4sim lib/jt4sim.f90) @@ -1597,13 +1642,12 @@ target_link_libraries (record_time_signal wsjt_cxx wsjt_qtmm wsjt_qt) add_executable (jt9 ${jt9_FSRCS} ${jt9_VERSION_RESOURCES}) if (${OPENMP_FOUND} OR APPLE) if (APPLE) - # On Mac we don't have working OpenMP support in the C/C++ - # compilers so we have to manually set the correct linking flags - # and libraries to get OpenMP support in jt9. + # On Mac we don't have working OpenMP support in the C/C++ + # compilers so we have to manually set the correct flags to get + # OpenMP support in jt9. set_target_properties (jt9 PROPERTIES Fortran_MODULE_DIRECTORY ${CMAKE_BINARY_DIR}/fortran_modules_omp - LINK_LIBRARIES "gomp;gcc_s.1" # assume GNU libgcc OpenMP ) target_compile_options (jt9 PRIVATE @@ -1627,18 +1671,20 @@ if (${OPENMP_FOUND} OR APPLE) LINK_FLAGS -Wl,--stack,16777216 ) endif () - target_link_libraries (jt9 wsjt_fort_omp wsjt_cxx fort_qt) + if (APPLE) + target_link_libraries (jt9 wsjt_fort_omp wsjt_cxx fort_qt "${WSJT_MACOS_LIBGOMP_LIBRARY}" gcc_s.1) + else () + target_link_libraries (jt9 wsjt_fort_omp wsjt_cxx fort_qt) + endif () else (${OPENMP_FOUND} OR APPLE) target_link_libraries (jt9 wsjt_fort wsjt_cxx fort_qt) endif (${OPENMP_FOUND} OR APPLE) -if (WIN32) +if (NOT WSJT_SKIP_MAP65) find_package (Portaudio REQUIRED) - if (NOT WSJT_SKIP_MAP65) - add_subdirectory (map65) - endif () + add_subdirectory (map65) endif () - add_subdirectory (qmap) +add_subdirectory (qmap) # build the main application generate_version_info (wsjtx_VERSION_RESOURCES @@ -1682,8 +1728,8 @@ set_target_properties (wsjtx PROPERTIES MACOSX_BUNDLE_INFO_STRING "${PROJECT_DESCRIPTION}" MACOSX_BUNDLE_ICON_FILE "${WSJTX_ICON_FILE}" MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH} - MACOSX_BUNDLE_SHORT_VERSION_STRING "v${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH}" - MACOSX_BUNDLE_LONG_VERSION_STRING "Version ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH}${SCS_VERSION_STR}" + MACOSX_BUNDLE_SHORT_VERSION_STRING "v${wsjtx_VERSION}" + MACOSX_BUNDLE_LONG_VERSION_STRING "Version ${wsjtx_VERSION}" MACOSX_BUNDLE_BUNDLE_NAME "${PROJECT_BUNDLE_NAME}" MACOSX_BUNDLE_BUNDLE_EXECUTABLE_NAME "${PROJECT_NAME}" MACOSX_BUNDLE_COPYRIGHT "${PROJECT_COPYRIGHT}" @@ -1825,6 +1871,13 @@ install (TARGETS qmap BUNDLE DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT runtime ) +if (NOT WSJT_SKIP_MAP65) + install (TARGETS map65 + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT runtime + BUNDLE DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT runtime + ) +endif () + if(WSJT_BUILD_UTILS) install (TARGETS ft8code jt65code jt9code jt4code msk144code q65code fst4sim ft8sim q65sim EchoCallSim testEchoCall echosim hash22calc cablog @@ -1872,13 +1925,8 @@ install (FILES sat.dat contrib/Ephemeris/JPLEPH eclipse.txt - DESTINATION ${CMAKE_INSTALL_DATADIR}/${CMAKE_PROJECT_NAME} - #COMPONENT runtime - ) - -install (FILES ALLCALL7.TXT - DESTINATION ${CMAKE_INSTALL_BINDIR} + DESTINATION ${CMAKE_INSTALL_DATADIR}/${CMAKE_PROJECT_NAME} #COMPONENT runtime ) @@ -1889,21 +1937,44 @@ install (DIRECTORY #COMPONENT runtime ) +if (APPLE) + set (WSJT_SOUND_DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}) +else () + set (WSJT_SOUND_DESTINATION ${CMAKE_INSTALL_BINDIR}) +endif () install (DIRECTORY ${PROJECT_SOURCE_DIR}/sounds - DESTINATION ${CMAKE_INSTALL_BINDIR} + DESTINATION ${WSJT_SOUND_DESTINATION} #COMPONENT runtime ) if (WIN32) - install (FILES - contrib/tls/libssl-1_1.dll - contrib/tls/libcrypto-1_1.dll - contrib/tls/libssl-1_1-x64.dll - contrib/tls/libcrypto-1_1-x64.dll - DESTINATION ${CMAKE_INSTALL_BINDIR} - #COMPONENT runtime + # Bundle OpenSSL runtime DLLs from the build environment. + # Qt's QSslSocket loads OpenSSL by filename at runtime; the names depend + # on what Qt was built against (libssl-1_1*.dll for older Qt-on-OpenSSL-1.1, + # libssl-3-x64.dll for current MSYS2 Qt-on-OpenSSL-3). Glob whatever the + # runner provides so SuperFox verification, Update Hamlib, LotW download, + # and eQSL keep working as the build environment advances. + set (_openssl_msys_prefix "$ENV{MSYSTEM_PREFIX}") + if (NOT _openssl_msys_prefix) + set (_openssl_msys_prefix "/mingw64") + endif () + file (GLOB _openssl_runtime_dlls + "${_openssl_msys_prefix}/bin/libssl-*.dll" + "${_openssl_msys_prefix}/bin/libcrypto-*.dll" ) + if (_openssl_runtime_dlls) + install (FILES ${_openssl_runtime_dlls} + DESTINATION ${CMAKE_INSTALL_BINDIR} + #COMPONENT runtime + ) + else () + message (WARNING + "OpenSSL runtime DLLs not found at ${_openssl_msys_prefix}/bin — " + "TLS features (SuperFox, Update Hamlib, LotW, eQSL) will fail on " + "installs without OpenSSL in PATH." + ) + endif () endif (WIN32) # @@ -1987,7 +2058,7 @@ endif () # # bundle fixup only done in non-Debug configurations # -if (NOT is_debug_build) +if (NOT is_debug_build AND NOT WSJT_SKIP_BUNDLE_FIXUP) # add this sub-sirectory after all install steps and other # sub-directories to ensure that all executables are in-place before # any fixup is done @@ -2039,6 +2110,13 @@ endif () set (CPACK_DEBIAN_PACKAGE_HOMEPAGE "${PROJECT_HOMEPAGE}") set (CPACK_DEBIAN_PACKAGE_DEPENDS "libgfortran5 (>=8.3) | libgfortran4 (>=7.3) | libgfortran3 (>=6.3), libfftw3-single3 (>=3.3), libgomp1 (>=6), libqt5serialport5 (>=5.7), libqt5multimedia5-plugins (>=5.7), libqt5widgets5 (>=5.7), libqt5network5 (>=5.7), libqt5printsupport5 (>=5.7), libqt5websockets5 (>=5.7), libqt5sql5-sqlite (>=5.7), libusb-1.0-0 (>=1.0.21), libboost-log1.62.0 (>=1.62.0) | libboost-log1.65.1 (>=1.65.1) | libboost-log1.67.0 (>=1.67.0) | libboost-log1.71.0 (>=1.71.0) | libboost-log1.74.0 (>=1.74.0) | libboost-log1.81.0 (>=1.81.0) | libboost-log1.83.0 (>=1.83.0) | libboost-log1.85.0 (>=1.85.0)") set (CPACK_DEBIAN_PACKAGE_SHLIBDEPS ON) +# Take over data files (icon, samples, docs) from the distro `wsjtx-data`, +# `wsjtx-doc`, `wsjtx-improved-data`, and `wsjtx-improved-doc` binary packages +# so installing this .deb on a system carrying any of them doesn't fail with a +# file conflict and doesn't cascade-remove `js8call` or other consumers. +set (CPACK_DEBIAN_PACKAGE_PROVIDES "wsjtx-data (= ${wsjtx_VERSION}), wsjtx-doc (= ${wsjtx_VERSION}), wsjtx-improved-data (= ${wsjtx_VERSION}), wsjtx-improved-doc (= ${wsjtx_VERSION})") +set (CPACK_DEBIAN_PACKAGE_REPLACES "wsjtx-data, wsjtx-doc, wsjtx-improved-data, wsjtx-improved-doc") +set (CPACK_DEBIAN_PACKAGE_CONFLICTS "wsjtx-data (<< ${wsjtx_VERSION}), wsjtx-doc (<< ${wsjtx_VERSION}), wsjtx-improved-data (<< ${wsjtx_VERSION}), wsjtx-improved-doc (<< ${wsjtx_VERSION})") set (CPACK_RPM_PACKAGE_ARCHITECTURE ${CMAKE_SYSTEM_PROCESSOR}) set (CPACK_RPM_PACKAGE_REQUIRES "qt5-qtbase >= 5.9, qt5-qtserialport >= 5.9, qt5-qtmultimedia >= 5.9, qt5-qtwebsockets >= 5.9, qt5-qtsvg >= 5.9, libusbx >= 1.0.22, libgfortran >= 7, libgomp >= 7, fftw-libs-single >= 3.3, boost-log >= 1.62") diff --git a/CMakeLists_wsjtx.txt b/CMakeLists_wsjtx.txt index e39232f9..8276ad59 100644 --- a/CMakeLists_wsjtx.txt +++ b/CMakeLists_wsjtx.txt @@ -1850,14 +1850,32 @@ install (DIRECTORY ) if (WIN32) - install (FILES - contrib/tls/libssl-1_1.dll - contrib/tls/libcrypto-1_1.dll - contrib/tls/libssl-1_1-x64.dll - contrib/tls/libcrypto-1_1-x64.dll - DESTINATION ${CMAKE_INSTALL_BINDIR} - #COMPONENT runtime + # Bundle OpenSSL runtime DLLs from the build environment. + # Qt's QSslSocket loads OpenSSL by filename at runtime; the names depend + # on what Qt was built against (libssl-1_1*.dll for older Qt-on-OpenSSL-1.1, + # libssl-3-x64.dll for current MSYS2 Qt-on-OpenSSL-3). Glob whatever the + # runner provides so SuperFox verification, Update Hamlib, LotW download, + # and eQSL keep working as the build environment advances. + set (_openssl_msys_prefix "$ENV{MSYSTEM_PREFIX}") + if (NOT _openssl_msys_prefix) + set (_openssl_msys_prefix "/mingw64") + endif () + file (GLOB _openssl_runtime_dlls + "${_openssl_msys_prefix}/bin/libssl-*.dll" + "${_openssl_msys_prefix}/bin/libcrypto-*.dll" ) + if (_openssl_runtime_dlls) + install (FILES ${_openssl_runtime_dlls} + DESTINATION ${CMAKE_INSTALL_BINDIR} + #COMPONENT runtime + ) + else () + message (WARNING + "OpenSSL runtime DLLs not found at ${_openssl_msys_prefix}/bin — " + "TLS features (SuperFox, Update Hamlib, LotW, eQSL) will fail on " + "installs without OpenSSL in PATH." + ) + endif () endif (WIN32) # @@ -1993,6 +2011,13 @@ endif () set (CPACK_DEBIAN_PACKAGE_HOMEPAGE "${PROJECT_HOMEPAGE}") set (CPACK_DEBIAN_PACKAGE_DEPENDS "libgfortran5 (>=8.3) | libgfortran4 (>=7.3) | libgfortran3 (>=6.3), libfftw3-single3 (>=3.3), libgomp1 (>=6), libqt5serialport5 (>=5.7), libqt5multimedia5-plugins (>=5.7), libqt5widgets5 (>=5.7), libqt5network5 (>=5.7), libqt5printsupport5 (>=5.7), libqt5websockets5 (>=5.7), libqt5sql5-sqlite (>=5.7), libusb-1.0-0 (>=1.0.21), libboost-log1.62.0 (>=1.62.0) | libboost-log1.65.1 (>=1.65.1) | libboost-log1.67.0 (>=1.67.0) | libboost-log1.71.0 (>=1.71.0) | libboost-log1.74.0 (>=1.74.0) | libboost-log1.81.0 (>=1.81.0) | libboost-log1.83.0 (>=1.83.0) | libboost-log1.85.0 (>=1.85.0)") set (CPACK_DEBIAN_PACKAGE_SHLIBDEPS ON) +# Take over data files (icon, samples, docs) from the distro `wsjtx-data`, +# `wsjtx-doc`, `wsjtx-improved-data`, and `wsjtx-improved-doc` binary packages +# so installing this .deb on a system carrying any of them doesn't fail with a +# file conflict and doesn't cascade-remove `js8call` or other consumers. +set (CPACK_DEBIAN_PACKAGE_PROVIDES "wsjtx-data (= ${wsjtx_VERSION}), wsjtx-doc (= ${wsjtx_VERSION}), wsjtx-improved-data (= ${wsjtx_VERSION}), wsjtx-improved-doc (= ${wsjtx_VERSION})") +set (CPACK_DEBIAN_PACKAGE_REPLACES "wsjtx-data, wsjtx-doc, wsjtx-improved-data, wsjtx-improved-doc") +set (CPACK_DEBIAN_PACKAGE_CONFLICTS "wsjtx-data (<< ${wsjtx_VERSION}), wsjtx-doc (<< ${wsjtx_VERSION}), wsjtx-improved-data (<< ${wsjtx_VERSION}), wsjtx-improved-doc (<< ${wsjtx_VERSION})") set (CPACK_RPM_PACKAGE_ARCHITECTURE ${CMAKE_SYSTEM_PROCESSOR}) set (CPACK_RPM_PACKAGE_REQUIRES "qt5-qtbase >= 5.9, qt5-qtserialport >= 5.9, qt5-qtmultimedia >= 5.9, qt5-qtwebsockets >= 5.9, qt5-qtsvg >= 5.9, libusbx >= 1.0.22, libgfortran >= 7, libgomp >= 7, fftw-libs-single >= 3.3, boost-log >= 1.62") diff --git a/Configuration.cpp b/Configuration.cpp index 185b3e4b..bf598688 100644 --- a/Configuration.cpp +++ b/Configuration.cpp @@ -500,7 +500,7 @@ public: void transceiver_ptt (bool); void transceiver_audio (bool); void transceiver_tune (bool); - void transceiver_period (double); + void transceiver_period (double, bool = false); void transceiver_blocksize (qint32); void transceiver_modulator_start (QString, unsigned, double, double, double, bool, bool, double, double); void transceiver_modulator_stop (bool); @@ -1262,13 +1262,13 @@ void Configuration::transceiver_tune (bool on) m_->transceiver_tune (on); } -void Configuration::transceiver_period (double period) +void Configuration::transceiver_period (double period, bool force) { #if WSJT_TRACE_CAT qDebug () << "Configuration::transceiver_period:" << period << m_->cached_rig_state_; #endif - m_->transceiver_period (period); + m_->transceiver_period (period, force); } void Configuration::transceiver_blocksize (qint32 blocksize) @@ -4979,7 +4979,7 @@ void Configuration::impl::on_voices_combo_box_currentIndexChanged (int /* index void Configuration::impl::read_voices () { - QString audioPath = QCoreApplication::applicationDirPath() + "/sounds/"; + QString audioPath = app_sounds_directory (); QString voiceList = audioPath + "voices.dat"; // load the content of voices.dat file to the voices combo box QFile file2 {voiceList}; QStringList wordList; @@ -5009,7 +5009,7 @@ void Configuration::impl::on_pb_test_alerts_clicked (bool) read_voicesPath(); #ifdef WIN32 QAudioOutput info(QAudioDeviceInfo::defaultOutputDevice()); - QString audioPath = QCoreApplication::applicationDirPath() + "/sounds" + voicesPath_ + "/"; + QString audioPath = app_sounds_directory (voicesPath_); QAudioFormat format; format.setCodec("audio/pcm"); format.setSampleRate (48000); @@ -5023,7 +5023,7 @@ void Configuration::impl::on_pb_test_alerts_clicked (bool) effect->open(QIODevice::ReadOnly); audio->start(effect); #else - QString audioPath = QCoreApplication::applicationDirPath() + "/sounds" + voicesPath_ + "/"; + QString audioPath = app_sounds_directory (voicesPath_); QSound::play(audioPath + "Testing123.wav"); // for Linux and macOS #endif } @@ -5217,11 +5217,14 @@ void Configuration::impl::transceiver_tune (bool on) } -void Configuration::impl::transceiver_period (double period) +void Configuration::impl::transceiver_period (double period, bool force) { cached_rig_state_.online (true); // we want the rig online set_cached_mode (); - if (cached_rig_state_.period() != period) + // force bypasses the de-dup so a caller can re-assert the period even when + // the cache already holds it but the rig never actually applied it (e.g. a + // period set that was emitted while the TCI rig was still offline). + if (force || cached_rig_state_.period() != period) { // printf("%s(%0.1f) Configuration #:%d period: %0.1f cached: %0.1f\n",QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),transceiver_command_number_+1,period,cached_rig_state_.period()); cached_rig_state_.period (period); diff --git a/Configuration.hpp b/Configuration.hpp index 3fb9d501..e8ccbc30 100644 --- a/Configuration.hpp +++ b/Configuration.hpp @@ -399,7 +399,7 @@ public: // Set period for TCI audio // - Q_SLOT void transceiver_period (double = 15.0); + Q_SLOT void transceiver_period (double = 15.0, bool force = false); // Set blocksize for TCI audio. // diff --git a/Network/Cloudlog.cpp b/Network/Cloudlog.cpp index ea9ac395..50e2fdee 100644 --- a/Network/Cloudlog.cpp +++ b/Network/Cloudlog.cpp @@ -26,6 +26,7 @@ #include "moc_Cloudlog.cpp" #include "Configuration.hpp" +#include "revision_utils.hpp" namespace { @@ -63,6 +64,7 @@ public: QNetworkRequest request(u); request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json")); + request.setRawHeader ("User-Agent", http_user_agent ().toUtf8 ()); reply_ = network_manager_->post(request, data); connect (reply_.data (), &QNetworkReply::finished, this, &Cloudlog::impl::reply_logqso); @@ -89,7 +91,7 @@ public: } QNetworkRequest request {apiUrl+"/index.php/api/auth/"+apiKey}; - request.setRawHeader ("User-Agent", "WSJT-X Cloudlog API"); + request.setRawHeader ("User-Agent", http_user_agent ().toUtf8 ()); request.setOriginatingObject (this); reply_ = network_manager_->get (request); connect (reply_.data (), &QNetworkReply::finished, this, &Cloudlog::impl::reply_apitest); diff --git a/Network/PSKReporter.cpp b/Network/PSKReporter.cpp index 5e64d5c5..5a0eac26 100644 --- a/Network/PSKReporter.cpp +++ b/Network/PSKReporter.cpp @@ -7,26 +7,22 @@ // Reports will be sent in batch mode every 5 minutes. #include <fstream> -#include <iostream> -#include <cmath> +#include <string> +#include <ctime> #include <QObject> #include <QString> #include <QDateTime> #include <QSharedPointer> #include <QUdpSocket> #include <QTcpSocket> -#include <QHostInfo> #include <QQueue> -#include <QByteArray> -#include <QDataStream> #include <QTimer> -#include <QDir> #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) #include <QRandomGenerator> #endif #include "Logger.hpp" -#include "Configuration.hpp" +#include "PSKReporterIPFIX.hpp" #include "pimpl_impl.hpp" @@ -42,15 +38,15 @@ namespace // quint16 SERVICE_PORT {14739}; 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 MAX_PENDING_SPOTS {2048}; int CACHE_TIMEOUT {300}; // default to 5 minutes for repeating spots QMap<QString, time_t> spot_cache; -} -static int added; -static int removed; +#ifdef DEBUGPSK + int added; + int removed; +#endif +} class PSKReporter::impl final : public QObject @@ -60,15 +56,13 @@ class PSKReporter::impl final using logger_type = boost::log::sources::severity_channel_logger_mt<boost::log::trivial::severity_level>; public: - impl (PSKReporter * self, Configuration const * config, QString const& program_info) + impl (PSKReporter * self, PSKReporter::Options const& options) : logger_ {boost::log::keywords::channel = "PSKRPRT"} , self_ {self} - , config_ {config} + , options_ {options} , sequence_number_ {0u} , send_descriptors_ {0} - , send_receiver_data_ {0} , flush_counter_ {0u} - , prog_id_ {program_info} { #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) observation_id_ = qrand(); @@ -79,9 +73,8 @@ public: // This timer sets the interval to check for spots to send. connect (&report_timer_, &QTimer::timeout, [this] () {send_report ();}); - // This timer repeats the sending of IPFIX templates and receiver - // information if we are using UDP, in case server has been - // restarted ans lost cached information. + // UDP has no session state, so templates are repeated periodically in case + // the collector restarted and lost its template cache. connect (&descriptor_timer_, &QTimer::timeout, [this] () { if (socket_ && QAbstractSocket::UdpSocket == socket_->socketType ()) @@ -89,18 +82,16 @@ public: LOG_LOG_LOCATION (logger_, trace, "enable descriptor resend"); // send templates again send_descriptors_ = 3; // three times - // send receiver data set again - send_receiver_data_ = 3; // three times } }); - eclipse_load(config->data_dir ().absoluteFilePath ("eclipse.txt")); + eclipse_load(options_.eclipse_file_path); } void check_connection () { if (!socket_ || QAbstractSocket::UnconnectedState == socket_->state () - || (socket_->socketType () != (config_->psk_reporter_tcpip () ? QAbstractSocket::TcpSocket : QAbstractSocket::UdpSocket))) + || (socket_->socketType () != (options_.use_tcpip ? QAbstractSocket::TcpSocket : QAbstractSocket::UdpSocket))) { // we need to create the appropriate socket if (socket_ @@ -127,7 +118,7 @@ public: void handle_socket_error (QAbstractSocket::SocketError e) { - LOG_LOG_LOCATION (logger_, warning, "socket error: " << socket_->errorString ()); + LOG_LOG_LOCATION (logger_, warning, "socket error: " << qPrintable (socket_->errorString ())); switch (e) { case QAbstractSocket::RemoteHostClosedError: @@ -148,19 +139,17 @@ public: { // Using deleteLater for the deleter as we may eventually // be called from the disconnected handler above. - if (config_->psk_reporter_tcpip ()) + if (options_.use_tcpip) { LOG_LOG_LOCATION (logger_, trace, "create TCP/IP socket"); socket_.reset (new QTcpSocket, &QObject::deleteLater); send_descriptors_ = 1; - send_receiver_data_ = 1; } else { LOG_LOG_LOCATION (logger_, trace, "create UDP/IP socket"); socket_.reset (new QUdpSocket, &QObject::deleteLater); send_descriptors_ = 3; - send_receiver_data_ = 3; } #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) @@ -174,11 +163,11 @@ public: // use this for pseudo connection with UDP, allows us to use // QIODevice::write() instead of QUDPSocket::writeDatagram() socket_->connectToHost (HOST, SERVICE_PORT, QAbstractSocket::WriteOnly); - LOG_LOG_LOCATION (logger_, debug, "remote host: " << HOST << " port: " << SERVICE_PORT); + LOG_LOG_LOCATION (logger_, debug, "remote host: " << HOST.latin1 () << " port: " << SERVICE_PORT); if (!report_timer_.isActive ()) { - report_timer_.start (MIN_SEND_INTERVAL+1 * 1000); // we add 1 to give some more randomization + report_timer_.start ((MIN_SEND_INTERVAL + 1) * 1000); } if (!descriptor_timer_.isActive ()) { @@ -198,7 +187,6 @@ public: } void send_report (bool send_residue = false); - void build_preamble (QDataStream&); void eclipse_load(QString filename); bool eclipse_active(QDateTime now = QDateTime::currentDateTime()); @@ -209,389 +197,139 @@ public: return flush; } - QString getStringFromQDateTime(const QString& dateTimeString, const QString& format) - { - QDateTime dateTime = QDateTime::fromString(dateTimeString, format); - return dateTime.toString(); - } - QList<QDateTime> eclipseDates; logger_type mutable logger_; PSKReporter * self_; - Configuration const * config_; + PSKReporter::Options options_; QSharedPointer<QAbstractSocket> socket_; - int dns_lookup_id_; - QByteArray payload_; quint32 sequence_number_; int send_descriptors_; - // Currently PSK Reporter requires that a receiver data set is sent - // in every data flow. This memeber variable can be used to only - // send that information at session start (3 times for UDP), when it - // changes (3 times for UDP), or once per hour (3 times) if using - // UDP. Uncomment the relevant code to enable that fuctionality. - int send_receiver_data_; - unsigned flush_counter_; quint32 observation_id_; QString rx_call_; QString rx_grid_; QString rx_ant_; QString rigInformation_; - QString prog_id_; - QByteArray tx_data_; - QByteArray tx_residue_; - 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_; - }; - QQueue<Spot> spots_; + QQueue<PSKReporterIPFIX::Spot> spots_; QTimer report_timer_; QTimer descriptor_timer_; }; #include "PSKReporter.moc" -namespace -{ - void writeUtfString (QDataStream& out, QString const& s) - { - auto const& utf = s.toUtf8 ().left (254); - out << quint8 (utf.size ()); - out.writeRawData (utf, utf.size ()); - } - - int num_pad_bytes (int len) - { - return ALIGNMENT_PADDING ? (4 - len % 4) % 4 : 0; - } - - void 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); - } -} - bool PSKReporter::impl::eclipse_active(QDateTime timeutc) { - qDebug() << timeutc; + Q_UNUSED (timeutc); #ifdef DEBUGECLIPSE - std::ofstream mylog("/temp/eclipse.log", std::ios_base::app); + std::ofstream mylog("/temp/eclipse.log", std::ios_base::app); #endif - QDateTime dateNow = QDateTime::currentDateTimeUtc(); - for (int i=0; i< eclipseDates.size(); ++i) + QDateTime const dateNow = QDateTime::currentDateTimeUtc (); + for (auto const& check : eclipseDates) { - QDateTime check = eclipseDates.at(i); // already in UTC time - // +- 6 hour window - qint64 secondsDiff = qAbs(check.secsTo(dateNow)); - if (secondsDiff <= 3600*6) // 6 hour check + auto const secondsDiff = qAbs (check.secsTo (dateNow)); + if (secondsDiff <= 3600 * 6) { #ifdef DEBUGECLIPSE - mylog << dateNow.toString(Qt::ISODate) << " Eclipse! " << "secondsDiff=" << secondsDiff << std::endl; + mylog << dateNow.toString(Qt::ISODate) << " Eclipse! " << "secondsDiff=" << secondsDiff << std::endl; #endif - return true; + return true; } } #ifdef DEBUGECLIPSE - mylog << timeutc.toString("yyyy-MM-dd HH:mm:ss") << " no eclipse" << "\n"; + mylog << timeutc.toString("yyyy-MM-dd HH:mm:ss") << " no eclipse" << "\n"; #endif - return false; + return false; } void PSKReporter::impl::eclipse_load(QString eclipse_file) { - std::ifstream fs(qPrintable(eclipse_file)); - std::string mydate,mytime,myline; + std::ifstream fs(qPrintable(eclipse_file)); #ifdef DEBUGECLIPSE - std::ofstream mylog("c:/temp/eclipse.log"); - mylog << "eclipse_file=" << eclipse_file << std::endl; + std::ofstream mylog("/temp/eclipse.log"); + mylog << "eclipse_file=" << qPrintable(eclipse_file) << std::endl; #endif - if (fs.is_open()) + std::string line; + while (std::getline (fs, line)) { - while(!fs.eof()) - { - std::getline(fs, myline); - if (myline[0] != '#' && myline.length() > 2) // make sure to skip blank lines - { - //QString format = "yyyy-MM-dd hh:mm:ss"; - QDateTime qdate = QDateTime::fromString(QString::fromStdString(myline), Qt::ISODate); - QDateTime now = QDateTime::currentDateTimeUtc(); - // only add the date if we can cover the whole 12 hours - //if (now < qdate.toUTC().addSecs(-3600*6)) - eclipseDates.append(qdate); -#ifdef DEBUGECLIPSE - //else - // mylog << "not adding " << myline << std::endl; -#endif - - } + if (line.size () <= 2 || line[0] == '#') + { + continue; + } + auto const eclipse = QDateTime::fromString(QString::fromStdString(line), Qt::ISODate); + if (eclipse.isValid ()) + { + eclipseDates.append(eclipse); + } #ifdef DEBUGECLIPSE - mylog << myline << std::endl; + mylog << line << std::endl; #endif - } } #ifdef DEBUGECLIPSE - if (eclipse_active(QDateTime::currentDateTime().toUTC())) mylog << "Eclipse is active" << std::endl; - else mylog << "Eclipse is not active" << std::endl; + if (eclipse_active(QDateTime::currentDateTime().toUTC())) mylog << "Eclipse is active" << std::endl; + else mylog << "Eclipse is not active" << std::endl; #endif } -void PSKReporter::impl::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, "#: " << 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, "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, "sent local information"); - } -} - void PSKReporter::impl::send_report (bool send_residue) { LOG_LOG_LOCATION (logger_, trace, "sending residue: " << send_residue); - if (QAbstractSocket::ConnectedState != socket_->state ()) return; - - QDataStream message {&payload_, QIODevice::WriteOnly | QIODevice::Append}; - QDataStream tx_out {&tx_data_, QIODevice::WriteOnly | QIODevice::Append}; - - if (!payload_.size ()) + check_connection (); + if (!socket_ || QAbstractSocket::ConnectedState != socket_->state ()) { - // Build header, optional descriptors, and receiver information - build_preamble (message); + return; } auto flush = flushing () || send_residue; - while (spots_.size () || flush) + if (!spots_.size () && !flush && !send_descriptors_) { - if (!payload_.size ()) - { - // Build header, optional descriptors, and receiver information - build_preamble (message); - } + return; + } - if (!tx_data_.size () && (spots_.size () || tx_residue_.size ())) - { - // Set Header - tx_out - << quint16 (0x50e3) // Template ID - << quint16 (0u); // Length (place-holder) - } + QList<PSKReporterIPFIX::Spot> spots; + while (!spots_.isEmpty ()) + { + spots.append (spots_.dequeue ()); + } - // insert any residue - if (tx_residue_.size ()) - { - tx_out.writeRawData (tx_residue_.constData (), tx_residue_.size ()); - LOG_LOG_LOCATION (logger_, debug, "sent residue"); - tx_residue_.clear (); - } + bool const include_descriptors = send_descriptors_ > 0; + if (include_descriptors) + { + --send_descriptors_; + } - LOG_LOG_LOCATION (logger_, debug, "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> ( + auto const max_payload_bytes = options_.use_tcpip + ? PSKReporterIPFIX::maxTcpIpfixPayloadBytes () + : PSKReporterIPFIX::maxUdpIpfixPayloadBytes (); + auto const packets = PSKReporterIPFIX::buildPackets ( + {rx_call_, rx_grid_, options_.program_info, rx_ant_, rigInformation_} + , spots + , include_descriptors + , sequence_number_ + , observation_id_ + , static_cast<quint32> ( #if QT_VERSION >= QT_VERSION_CHECK(5, 8, 0) - spot.time_.toSecsSinceEpoch () + QDateTime::currentDateTime ().toSecsSinceEpoch () #else - spot.time_.toMSecsSinceEpoch () / 1000 + QDateTime::currentDateTime ().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 - LOG_LOG_LOCATION (logger_, debug, "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, "remaining spots: " << spots_.size ()); + ) + , max_payload_bytes); + + for (auto const& packet : packets) + { + Q_ASSERT (packet.payload.size () <= max_payload_bytes); + socket_->write (packet.payload); + sequence_number_ += packet.spot_count; + LOG_LOG_LOCATION (logger_, debug, "sent packet bytes: " << packet.payload.size () << " spots: " << packet.spot_count); } } -PSKReporter::PSKReporter (Configuration const * config, QString const& program_info) - : m_ {this, config, program_info} +PSKReporter::PSKReporter (Options const& options) + : m_ {this, options} { - LOG_LOG_LOCATION (m_->logger_, trace, "Started for: " << program_info); + LOG_LOG_LOCATION (m_->logger_, trace, "Started for: " << qPrintable (options.program_info)); } PSKReporter::~PSKReporter () @@ -613,13 +351,11 @@ bool PSKReporter::eclipse_active(QDateTime now) void PSKReporter::setLocalStation (QString const& call, QString const& gridSquare, QString const& antenna, QString const& rigInformation) { - LOG_LOG_LOCATION (m_->logger_, trace, "call: " << call << " grid: " << gridSquare << " ant: " << antenna); + LOG_LOG_LOCATION (m_->logger_, trace, "call: " << qPrintable (call) << " grid: " << qPrintable (gridSquare) << " ant: " << qPrintable (antenna)); m_->check_connection (); - if (call != m_->rx_call_ || gridSquare != m_->rx_grid_ || antenna != m_->rx_ant_) + if (call != m_->rx_call_ || gridSquare != m_->rx_grid_ || antenna != m_->rx_ant_ || rigInformation != m_->rigInformation_) { LOG_LOG_LOCATION (m_->logger_, trace, "updating information"); - m_->send_receiver_data_ = m_->socket_ - && QAbstractSocket::UdpSocket == m_->socket_->socketType () ? 3 : 1; m_->rx_call_ = call; m_->rx_grid_ = gridSquare; m_->rx_ant_ = antenna; @@ -630,56 +366,58 @@ void PSKReporter::setLocalStation (QString const& call, QString const& gridSquar bool PSKReporter::addRemoteStation (QString const& call, QString const& grid, Radio::Frequency freq , QString const& mode, int snr, QDateTime qSpotTime) { - LOG_LOG_LOCATION (m_->logger_, trace, "call: " << call << " grid: " << grid << " freq: " << freq << " mode: " << mode << " snr: " << snr); + LOG_LOG_LOCATION (m_->logger_, trace, "call: " << qPrintable (call) << " grid: " << qPrintable (grid) << " freq: " << freq << " mode: " << qPrintable (mode) << " snr: " << snr); m_->check_connection (); - if (m_->socket_ && m_->socket_->isValid ()) - { - if (QAbstractSocket::UnconnectedState == m_->socket_->state ()) - { - reconnect (); - } - // remove any earlier spots of this call to reduce pskreporter load + // 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 #ifdef DEBUGPSK - static std::fstream fs; - if (!fs.is_open()) fs.open("/temp/psk.log", std::fstream::in | std::fstream::out | std::fstream::app); + added++; #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 || eclipse_active(qdateNow)) // then it's a new spot - { - m_->spots_.enqueue ({call, grid, snr, freq, mode, qSpotTime}); - spot_cache.insert(call, time(NULL)); + 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 || eclipse_active(qdateNow)) + { + m_->spots_.enqueue ({call, grid, snr, freq, mode, qSpotTime}); + spot_cache.insert(call, time(NULL)); #ifdef DEBUGPSK - if (fs.is_open()) fs << "Adding " << call << " freq=" << freq << " " << spot_cache[call] << " count=" << m_->spots_.count() << std::endl; + if (fs.is_open()) fs << "Adding " << call << " freq=" << freq << " " << spot_cache[call] << " count=" << m_->spots_.count() << std::endl; #endif - } - else if (time(NULL) - spot_cache[call] > CACHE_TIMEOUT) // then the cache has expired - { - m_->spots_.enqueue ({call, grid, snr, freq, mode, qSpotTime}); + } + else if (time(NULL) - spot_cache[call] > CACHE_TIMEOUT) + { + m_->spots_.enqueue ({call, grid, snr, freq, mode, qSpotTime}); #ifdef DEBUGPSK - if (fs.is_open()) fs << "Adding # " << call << spot_cache[call] << " count=" << m_->spots_.count() << std::endl; + if (fs.is_open()) fs << "Adding # " << call << spot_cache[call] << " count=" << m_->spots_.count() << std::endl; #endif - spot_cache[call] = time(NULL); - } - else - { - removed++; + spot_cache[call] = time(NULL); + } + else + { #ifdef DEBUGPSK - if (fs.is_open()) fs << "Removing " << call << " " << time(NULL) << " reduction=" << removed/(double)added*100 << "%" << std::endl; + removed++; + 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()); - } - return true; } - return false; + + bool accepted = true; + while (m_->spots_.size () > MAX_PENDING_SPOTS) + { + m_->spots_.dequeue (); + accepted = false; + LOG_LOG_LOCATION (m_->logger_, warning, "PSKReporter pending spot queue exceeded " << MAX_PENDING_SPOTS << "; dropped oldest spot"); + } + + 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()); + } + return accepted; } void PSKReporter::sendReport (bool last) diff --git a/Network/PSKReporter.hpp b/Network/PSKReporter.hpp index 4b2175c8..46fe0a82 100644 --- a/Network/PSKReporter.hpp +++ b/Network/PSKReporter.hpp @@ -2,6 +2,8 @@ #define PSK_REPORTER_HPP_ #include <QObject> +#include <QDateTime> +#include <QString> #include "Radio.hpp" #include "pimpl_h.hpp" @@ -14,16 +16,22 @@ class PSKReporter final Q_OBJECT public: + struct Options + { + bool use_tcpip; + QString eclipse_file_path; + QString program_info; + }; + explicit PSKReporter (Configuration const *, QString const& program_info); + explicit PSKReporter (Options const& options); ~PSKReporter (); void reconnect (); void setLocalStation (QString const& call, QString const& grid, QString const& antenna, QString const& rigInformation); - // - // Returns false if PSK Reporter connection is not available - // + // Returns false if accepting the spot required dropping an older pending spot. bool addRemoteStation (QString const& call, QString const& grid, Radio::Frequency freq, QString const& mode, int snr, QDateTime spotTime); // diff --git a/Network/PSKReporterConfiguration.cpp b/Network/PSKReporterConfiguration.cpp new file mode 100644 index 00000000..9369e911 --- /dev/null +++ b/Network/PSKReporterConfiguration.cpp @@ -0,0 +1,18 @@ +#include "PSKReporter.hpp" + +#include <QDir> + +#include "Configuration.hpp" + +namespace +{ + PSKReporter::Options options_from_config (Configuration const * config, QString const& program_info) + { + return {config->psk_reporter_tcpip (), config->data_dir ().absoluteFilePath ("eclipse.txt"), program_info}; + } +} + +PSKReporter::PSKReporter (Configuration const * config, QString const& program_info) + : PSKReporter {options_from_config (config, program_info)} +{ +} diff --git a/Network/PSKReporterIPFIX.cpp b/Network/PSKReporterIPFIX.cpp new file mode 100644 index 00000000..27b3aea2 --- /dev/null +++ b/Network/PSKReporterIPFIX.cpp @@ -0,0 +1,294 @@ +#include "PSKReporterIPFIX.hpp" + +#include <QBuffer> +#include <QDataStream> +#include <QtGlobal> + +namespace +{ + constexpr int MAX_UDP_IP_PACKET_BYTES = 1000; + constexpr int IPV6_HEADER_BYTES = 40; + constexpr int UDP_HEADER_BYTES = 8; + constexpr int MAX_UDP_IPFIX_PAYLOAD_BYTES = MAX_UDP_IP_PACKET_BYTES - IPV6_HEADER_BYTES - UDP_HEADER_BYTES; + constexpr int MAX_TCP_IPFIX_PAYLOAD_BYTES = 0xffff; + constexpr bool ALIGNMENT_PADDING = true; + + constexpr int CALLSIGN_LIMIT = 32; + constexpr int LOCATOR_LIMIT = 16; + constexpr int MODE_LIMIT = 16; + constexpr int PROGRAM_INFO_LIMIT = 80; + constexpr int ANTENNA_LIMIT = 128; + constexpr int RIG_INFORMATION_LIMIT = 128; + + // PSK Reporter uses enterprise-specific IPFIX elements under PEN 30351. + // Template 0x50e3 describes sender/spot records; template 0x50e2 describes + // receiver metadata, with receiverCallsign as the options-template scope. + constexpr quint32 PSK_REPORTER_PEN = 30351; + constexpr quint16 SENDER_TEMPLATE_ID = 0x50e3; + constexpr quint16 RECEIVER_TEMPLATE_ID = 0x50e2; + + int num_pad_bytes (int len) + { + return ALIGNMENT_PADDING ? (4 - len % 4) % 4 : 0; + } + + QByteArray boundedUtf8 (QString const& value, int max_bytes) + { + auto utf8 = value.toUtf8 (); + if (utf8.size () <= max_bytes) + { + return utf8; + } + + auto bounded_size = qMax (0, max_bytes); + while (bounded_size > 0 + && (static_cast<quint8> (utf8[bounded_size]) & 0xc0) == 0x80) + { + --bounded_size; + } + return utf8.left (bounded_size); + } + + void writeUtfString (QDataStream& out, QString const& value, int max_bytes) + { + auto const utf8 = boundedUtf8 (value, max_bytes); + out << quint8 (utf8.size ()); + out.writeRawData (utf8.constData (), utf8.size ()); + } + + void setLength (QDataStream& out, QByteArray& bytes, int offset = sizeof (quint16)) + { + auto const pad_len = num_pad_bytes (bytes.size ()); + if (pad_len) + { + out.writeRawData (QByteArray {pad_len, '\0'}.constData (), pad_len); + } + + auto const pos = out.device ()->pos (); + out.device ()->seek (offset); + out << static_cast<quint16> (bytes.size ()); + out.device ()->seek (pos); + } + + QByteArray descriptorSets () + { + QByteArray sets; + { + // Sender Information template: callsign, frequency, SNR, mode, locator, + // information source, and spot timestamp. + QByteArray descriptor; + QDataStream out {&descriptor, QIODevice::WriteOnly}; + out + << quint16 (2u) + << quint16 (0u) + << quint16 (SENDER_TEMPLATE_ID) + << quint16 (7u) + << quint16 (0x8000 + 1u) // senderCallsign + << quint16 (0xffff) + << PSK_REPORTER_PEN + << quint16 (0x8000 + 5u) // frequency, 5-byte unsigned integer + << quint16 (5u) + << PSK_REPORTER_PEN + << quint16 (0x8000 + 6u) // sNR + << quint16 (1u) + << PSK_REPORTER_PEN + << quint16 (0x8000 + 10u) // mode + << quint16 (0xffff) + << PSK_REPORTER_PEN + << quint16 (0x8000 + 3u) // senderLocator + << quint16 (0xffff) + << PSK_REPORTER_PEN + << quint16 (0x8000 + 11u) // informationSource + << quint16 (1u) + << PSK_REPORTER_PEN + << quint16 (150u) // dateTimeSeconds + << quint16 (4u); + setLength (out, descriptor); + sets.append (descriptor); + } + { + // Receiver Information options template. Scope Field Count must remain 1: + // receiverCallsign scopes receiver locator, software, antenna, and rig. + QByteArray descriptor; + QDataStream out {&descriptor, QIODevice::WriteOnly}; + out + << quint16 (3u) + << quint16 (0u) + << quint16 (RECEIVER_TEMPLATE_ID) + << quint16 (5u) + << quint16 (1u) + << quint16 (0x8000 + 2u) // receiverCallsign, scope field + << quint16 (0xffff) + << PSK_REPORTER_PEN + << quint16 (0x8000 + 4u) // receiverLocator + << quint16 (0xffff) + << PSK_REPORTER_PEN + << quint16 (0x8000 + 8u) // decodingSoftware + << quint16 (0xffff) + << PSK_REPORTER_PEN + << quint16 (0x8000 + 9u) // antennaInformation + << quint16 (0xffff) + << PSK_REPORTER_PEN + << quint16 (0x8000 + 13u) // rigInformation + << quint16 (0xffff) + << PSK_REPORTER_PEN; + setLength (out, descriptor); + sets.append (descriptor); + } + return sets; + } + + QByteArray receiverSet (PSKReporterIPFIX::Receiver const& receiver) + { + QByteArray data; + QDataStream out {&data, QIODevice::WriteOnly}; + out << quint16 (RECEIVER_TEMPLATE_ID) << quint16 (0u); + writeUtfString (out, receiver.callsign, CALLSIGN_LIMIT); + writeUtfString (out, receiver.locator, LOCATOR_LIMIT); + writeUtfString (out, receiver.program_info, PROGRAM_INFO_LIMIT); + writeUtfString (out, receiver.antenna, ANTENNA_LIMIT); + writeUtfString (out, receiver.rig_information, RIG_INFORMATION_LIMIT); + setLength (out, data); + return data; + } + + int senderSetLength (int record_bytes) + { + auto const len = 2 * sizeof (quint16) + record_bytes; + return len + num_pad_bytes (len); + } + + int messageLength (int set_bytes) + { + auto const len = 2 * sizeof (quint16) + 3 * sizeof (quint32) + set_bytes; + return len + num_pad_bytes (len); + } + + QByteArray spotRecord (PSKReporterIPFIX::Spot const& spot) + { + QByteArray data; + QDataStream out {&data, QIODevice::WriteOnly}; + // Field order must match the sender template above. + writeUtfString (out, spot.callsign, CALLSIGN_LIMIT); + + out + << static_cast<quint8> ((spot.frequency >> 32) & 0xff) + << static_cast<quint32> (spot.frequency & 0xffffffffu) + << static_cast<qint8> (spot.snr); + + writeUtfString (out, spot.mode, MODE_LIMIT); + writeUtfString (out, spot.locator, LOCATOR_LIMIT); + out + << quint8 (1u) + << static_cast<quint32> ( +#if QT_VERSION >= QT_VERSION_CHECK(5, 8, 0) + spot.time.toSecsSinceEpoch () +#else + spot.time.toMSecsSinceEpoch () / 1000 +#endif + ); + return data; + } + + QByteArray senderSet (QList<QByteArray> const& records) + { + QByteArray data; + QDataStream out {&data, QIODevice::WriteOnly}; + out << quint16 (SENDER_TEMPLATE_ID) << quint16 (0u); + for (auto const& record : records) + { + out.writeRawData (record.constData (), record.size ()); + } + setLength (out, data); + return data; + } + + QByteArray message (QByteArray const& sets, quint32 sequence_number, quint32 observation_id, quint32 export_time) + { + QByteArray data; + QDataStream out {&data, QIODevice::WriteOnly}; + out + << quint16 (10u) + << quint16 (0u) + << export_time + << sequence_number + << observation_id; + out.writeRawData (sets.constData (), sets.size ()); + setLength (out, data); + return data; + } +} + +namespace PSKReporterIPFIX +{ + int maxUdpIpfixPayloadBytes () + { + return MAX_UDP_IPFIX_PAYLOAD_BYTES; + } + + int maxTcpIpfixPayloadBytes () + { + return MAX_TCP_IPFIX_PAYLOAD_BYTES; + } + + QList<Packet> buildPackets (Receiver const& receiver, QList<Spot> const& spots + , bool include_descriptors, quint32 sequence_number + , quint32 observation_id, quint32 export_time + , int max_payload_bytes) + { + QList<Packet> packets; + QByteArray first_base_sets; + if (include_descriptors) + { + first_base_sets.append (descriptorSets ()); + } + auto const receiver_set = receiverSet (receiver); + first_base_sets.append (receiver_set); + + auto const base_payload = message (first_base_sets, sequence_number, observation_id, export_time); + Q_ASSERT (base_payload.size () <= max_payload_bytes); + if (spots.isEmpty ()) + { + packets.append ({base_payload, 0}); + return packets; + } + + QList<QByteArray> records; + int record_count = 0; + int record_bytes = 0; + auto base_sets = first_base_sets; + for (auto const& spot : spots) + { + auto const record = spotRecord (spot); + auto const candidate_record_bytes = record_bytes + record.size (); + auto const candidate_payload_size = messageLength (base_sets.size () + senderSetLength (candidate_record_bytes)); + if (!records.isEmpty () && candidate_payload_size > max_payload_bytes) + { + auto const payload = message (base_sets + senderSet (records), sequence_number, observation_id, export_time); + Q_ASSERT (payload.size () <= max_payload_bytes); + packets.append ({payload, record_count}); + sequence_number += record_count; + records.clear (); + record_count = 0; + record_bytes = 0; + // Follow-on split packets keep receiver data but do not repeat + // descriptors until the caller schedules the next descriptor send. + base_sets = receiver_set; + } + + records.append (record); + ++record_count; + record_bytes += record.size (); + Q_ASSERT (messageLength (base_sets.size () + senderSetLength (record_bytes)) <= max_payload_bytes); + } + + if (!records.isEmpty ()) + { + auto const payload = message (base_sets + senderSet (records), sequence_number, observation_id, export_time); + Q_ASSERT (payload.size () <= max_payload_bytes); + packets.append ({payload, record_count}); + } + + return packets; + } +} diff --git a/Network/PSKReporterIPFIX.hpp b/Network/PSKReporterIPFIX.hpp new file mode 100644 index 00000000..1704f6fa --- /dev/null +++ b/Network/PSKReporterIPFIX.hpp @@ -0,0 +1,47 @@ +#ifndef PSK_REPORTER_IPFIX_HPP_ +#define PSK_REPORTER_IPFIX_HPP_ + +#include <QByteArray> +#include <QDateTime> +#include <QList> +#include <QString> + +#include "Radio.hpp" + +namespace PSKReporterIPFIX +{ + int maxUdpIpfixPayloadBytes (); + int maxTcpIpfixPayloadBytes (); + + struct Receiver + { + QString callsign; + QString locator; + QString program_info; + QString antenna; + QString rig_information; + }; + + struct Spot + { + QString callsign; + QString locator; + int snr; + Radio::Frequency frequency; + QString mode; + QDateTime time; + }; + + struct Packet + { + QByteArray payload; + int spot_count; + }; + + QList<Packet> buildPackets (Receiver const& receiver, QList<Spot> const& spots + , bool include_descriptors, quint32 sequence_number + , quint32 observation_id, quint32 export_time + , int max_payload_bytes); +} + +#endif diff --git a/Release_Notes.txt b/Release_Notes.txt index dadfae3e..afcdacdb 100644 --- a/Release_Notes.txt +++ b/Release_Notes.txt @@ -11,6 +11,85 @@ Copyright 2001 - 2026 by Joe Taylor, K1JT, and the WSJT Development Team + Release: WSJT-X 3.0.2 + June 19, 2026 + ------------------------- + +WSJT-X 3.0.2 is a bug-fix release. New installation packages for +Windows, Linux, and macOS systems include user applications WSJT-X, +MAP65, and QMAP. + +Changes since release 3.0.1: + + - Ham Radio Deluxe (HRD): fixes CAT-control failures reported with + the 3.0.1 Windows builds, where WSJT-X could fail to communicate + correctly with HRD. HRD reply handling has been made more robust + while preserving compatibility with existing HRD responses. + + - OmniRig: fixes setups where WSJT-X could fail to set the rig + frequency at startup on slower rigs, including reports involving + the FTDX-101 family. + + - Transceiver Control Interface (TCI): fixes silent transmit audio + for modes with transmit/receive periods other than 15 s, improves + mode-change handling, and corrects split/fake-split frequency state + updates. + + - MAP65 and QMAP: MAP65 is again included in the release packages. + MAP65 includes cross-platform modernization work, improved decoder + output and audio/device handling, and fixes for JT65 live decoding + and transmit audio. MAP65 and QMAP also now use writable user + locations for settings and generated runtime files in packaged + installs. + + - Wide Graph: "Erase reference spectrum" now properly clears stale + reference-spectrum correction so it no longer affects new waterfall + data. + + - Callsign highlighting: highlighted callsigns can now be cleared + reliably, and background highlighting is correctly applied to the + second callsign on a decode line. + + - Audible Alerts: Wanted alert sounds on Linux and macOS now follow + the Wanted alert setting rather than the DX Call alert setting. + + - WAV files: improves WAV/BWF file handling so malformed or truncated + recordings are handled robustly and no longer risk crashing WSJT-X. + + - CloudLog: sends a versioned User-Agent with API-key tests and QSO + uploads, fixing failures on hosting providers that reject requests + without a User-Agent header. + + - Windows: the installer now detects when WSJT-X is already running + and asks you to close it before upgrading, avoiding incomplete + installs caused by locked files. + + - Windows: fixes clean installs where features depending on Transport + Layer Security (TLS) could fail. This bug could affect features + such as SuperFox verification, Update Hamlib, LoTW user-data + download, eQSL, and other HTTPS downloads/uploads, such as spotting + to LiveCQ. + + - macOS: fixes packages that could miss required data files on fresh + installs, restoring FT8 callsign filtering, DXCC country names, + grid-to-state lookup, and astronomical-data lookup. + + - macOS: Intel packages are now built with a macOS 10.13 deployment + target and checked to avoid bundled package-manager runtime + libraries built for newer macOS versions, improving compatibility + with older Intel Macs. + + - Linux: fixes .deb installs on systems that already have + distribution packages for wsjtx-data, wsjtx-doc, or + wsjtx-improved-*, avoiding file conflicts and improper removal of + dependent packages such as JS8Call. + + - Release builds: downloadable installers are now produced by an + automated build-and-package pipeline for Windows, macOS, and + Linux. This improves release consistency and catches + packaging/runtime problems before publication. + + Release: WSJT-X 3.0.1 May 4, 2026 ------------------------- diff --git a/Transceiver/EmulateSplitTransceiver.cpp b/Transceiver/EmulateSplitTransceiver.cpp index 3dfc4b5c..e7971fef 100644 --- a/Transceiver/EmulateSplitTransceiver.cpp +++ b/Transceiver/EmulateSplitTransceiver.cpp @@ -54,8 +54,14 @@ void EmulateSplitTransceiver::handle_update (TransceiverState const& state, else { TransceiverState new_state {state}; - // Follow the rig if in RX mode. - if (state.ptt ()) new_state.frequency (rx_frequency_); + // Fake split QSYs the rig to the TX dial before the PTT echo may + // arrive. Keep that transient from being adopted as the RX dial. + if (state.ptt () || (split_ && tx_frequency_ + && state.frequency () == tx_frequency_ + && state.frequency () != rx_frequency_)) + { + new_state.frequency (rx_frequency_); + } // These are always what was requested in prior set state operation new_state.tx_frequency (tx_frequency_); diff --git a/Transceiver/HRDMessage.cpp b/Transceiver/HRDMessage.cpp new file mode 100644 index 00000000..c1aabf50 --- /dev/null +++ b/Transceiver/HRDMessage.cpp @@ -0,0 +1,132 @@ +#include "Transceiver/HRDMessage.hpp" + +#include <QVector> + +namespace +{ + int constexpr header_size_value = 16; + int constexpr max_message_size_value = 1024 * 1024; + quint32 constexpr magic_1_value = 0x1234ABCD; + quint32 constexpr magic_2_value = 0xABCD1234; + + void append_u32_le (QByteArray * bytes, quint32 value) + { + bytes->append (static_cast<char> (value & 0xffu)); + bytes->append (static_cast<char> ((value >> 8) & 0xffu)); + bytes->append (static_cast<char> ((value >> 16) & 0xffu)); + bytes->append (static_cast<char> ((value >> 24) & 0xffu)); + } + + quint32 read_u32_le (QByteArray const& bytes, int offset) + { + return static_cast<quint32> (static_cast<quint8> (bytes[offset])) + | (static_cast<quint32> (static_cast<quint8> (bytes[offset + 1])) << 8) + | (static_cast<quint32> (static_cast<quint8> (bytes[offset + 2])) << 16) + | (static_cast<quint32> (static_cast<quint8> (bytes[offset + 3])) << 24); + } + + HRDMessage::ParseResult valid_partial (int required_size) + { + return {true, false, required_size, {}, {}}; + } + + HRDMessage::ParseResult invalid (QString const& error) + { + return {false, false, 0, {}, error}; + } +} + +namespace HRDMessage +{ + int header_size () + { + return header_size_value; + } + + int max_message_size () + { + return max_message_size_value; + } + + QByteArray make (QString const& payload) + { + QByteArray message; + auto const payload_units = payload.size () + 1; + auto const payload_bytes = payload_units * 2; + auto const message_size = header_size_value + payload_bytes; + + append_u32_le (&message, static_cast<quint32> (message_size)); + append_u32_le (&message, magic_1_value); + append_u32_le (&message, magic_2_value); + append_u32_le (&message, 0u); + + auto const utf16 = payload.utf16 (); + for (int i = 0; i != payload_units; ++i) + { + auto const unit = static_cast<quint16> (utf16[i]); + message.append (static_cast<char> (unit & 0xffu)); + message.append (static_cast<char> ((unit >> 8) & 0xffu)); + } + + return message; + } + + ParseResult parse (QByteArray const& message) + { + if (message.size () < header_size_value) + { + return valid_partial (header_size_value); + } + + auto const message_size = read_u32_le (message, 0); + auto const magic_1 = read_u32_le (message, 4); + auto const magic_2 = read_u32_le (message, 8); + + if (magic_1 != magic_1_value || magic_2 != magic_2_value) + { + return invalid ("invalid magic values"); + } + + if (message_size < static_cast<quint32> (header_size_value)) + { + return invalid ("message size is smaller than the header"); + } + + if (message_size > static_cast<quint32> (max_message_size_value)) + { + return invalid ("message size is too large"); + } + + if (message.size () < static_cast<int> (message_size)) + { + return valid_partial (static_cast<int> (message_size)); + } + + auto const payload_bytes = static_cast<int> (message_size) - header_size_value; + if (payload_bytes < 2) + { + return invalid ("payload is missing the terminator"); + } + + if (payload_bytes % 2) + { + return invalid ("payload is not valid UTF-16"); + } + + QVector<ushort> payload; + payload.reserve (payload_bytes / 2); + for (int offset = header_size_value; offset != static_cast<int> (message_size); offset += 2) + { + payload.append (static_cast<ushort> ( + static_cast<quint16> (static_cast<quint8> (message[offset])) + | (static_cast<quint16> (static_cast<quint8> (message[offset + 1])) << 8))); + } + + if (payload.isEmpty () || payload.back () != 0u) + { + return invalid ("payload is missing the terminator"); + } + + return {true, true, static_cast<int> (message_size), QString::fromUtf16 (payload.constData (), payload.size () - 1), {}}; + } +} diff --git a/Transceiver/HRDMessage.hpp b/Transceiver/HRDMessage.hpp new file mode 100644 index 00000000..61cc8d4a --- /dev/null +++ b/Transceiver/HRDMessage.hpp @@ -0,0 +1,25 @@ +#ifndef HRD_MESSAGE_HPP__ +#define HRD_MESSAGE_HPP__ + +#include <QByteArray> +#include <QString> + +namespace HRDMessage +{ + int header_size (); + int max_message_size (); + + struct ParseResult + { + bool valid; + bool complete; + int required_size; + QString payload; + QString error; + }; + + QByteArray make (QString const& payload); + ParseResult parse (QByteArray const& message); +} + +#endif diff --git a/Transceiver/HRDTransceiver.cpp b/Transceiver/HRDTransceiver.cpp index a0cef0ce..eb719842 100644 --- a/Transceiver/HRDTransceiver.cpp +++ b/Transceiver/HRDTransceiver.cpp @@ -10,6 +10,7 @@ #include <QDir> #include "Network/NetworkServerLookup.hpp" +#include "Transceiver/HRDMessage.hpp" #include "qt_helpers.hpp" namespace @@ -30,48 +31,6 @@ void HRDTransceiver::register_transceivers (logger_type *, (*registry)[HRD_transceiver_name] = TransceiverFactory::Capabilities (id, TransceiverFactory::Capabilities::network, true, true /* maybe */); } -struct HRDMessage -{ - // Placement style new overload for outgoing messages that does the - // construction too. - static void * operator new (size_t size, QString const& payload) - { - size += sizeof (QChar) * (payload.size () + 1); // space for terminator too - HRDMessage * storage (reinterpret_cast<HRDMessage *> (new char[size])); - storage->size_ = size ; - ushort const * pl (payload.utf16 ()); - std::copy (pl, pl + payload.size () + 1, storage->payload_); // copy terminator too - storage->magic_1_ = magic_1_value_; - storage->magic_2_ = magic_2_value_; - storage->checksum_ = 0; - return storage; - } - - // Placement style new overload for incoming messages that does the - // construction too. - // - // No memory allocation here. - static void * operator new (size_t /* size */, QByteArray const& message) - { - // Nasty const_cast here to avoid copying the message buffer. - return const_cast<HRDMessage *> (reinterpret_cast<HRDMessage const *> (message.data ())); - } - - void operator delete (void * p, size_t) - { - delete [] reinterpret_cast<char *> (p); // Mirror allocation in operator new above. - } - - quint32 size_; - qint32 magic_1_; - qint32 magic_2_; - qint32 checksum_; // Apparently not used. - QChar payload_[0]; // UTF-16 (which is wchar_t on Windows) - - static qint32 constexpr magic_1_value_ = 0x1234ABCD; - static qint32 constexpr magic_2_value_ = 0xABCD1234; -}; - HRDTransceiver::HRDTransceiver (logger_type * logger , std::unique_ptr<TransceiverBase> wrapped , QString const& server @@ -1063,8 +1022,8 @@ QString HRDTransceiver::send_command (QString const& cmd, bool prepend_context, else { auto string = prepend_context ? context + cmd : cmd; - QScopedPointer<HRDMessage> message {new (string) HRDMessage}; - if (!write_to_port (reinterpret_cast<char const *> (message.data ()), message->size_)) + auto message = HRDMessage::make (string); + if (!write_to_port (message.constData (), message.size ())) { CAT_ERROR ("failed to write command" << cmd << "to HRD"); throw error { @@ -1080,25 +1039,35 @@ QString HRDTransceiver::send_command (QString const& cmd, bool prepend_context, } else { - HRDMessage const * reply {new (buffer) HRDMessage}; - if (reply->magic_1_value_ != reply->magic_1_ && reply->magic_2_value_ != reply->magic_2_) + auto reply = HRDMessage::parse (buffer); + while (reply.valid && !reply.complete) { - CAT_ERROR (cmd << "invalid reply"); - throw error { - tr ("Ham Radio Deluxe sent an invalid reply to our command \"%1\"") - .arg (cmd) - }; + CAT_TRACE (cmd << "reading more reply data"); + buffer += read_reply (cmd); + if (buffer.size () >= reply.required_size) + { + reply = HRDMessage::parse (buffer); + } } - // keep reading until expected size arrives - while (buffer.size () - offsetof (HRDMessage, size_) < reply->size_) + if (!reply.valid) { - CAT_TRACE (cmd << "reading more reply data"); - buffer += read_reply (cmd); - reply = new (buffer) HRDMessage; + CAT_ERROR (cmd << "invalid reply:" << reply.error); + throw error { + tr ("Ham Radio Deluxe sent an invalid reply to our command \"%1\": %2") + .arg (cmd) + .arg (reply.error) + }; } - result = QString {reply->payload_}; // this is not a memory leak (honest!) + // HRD frames replies with an in-band NUL (U+0000) as a value separator + // and terminator. The byte-level parser returns the full body minus only + // the final terminator, preserving embedded/trailing NULs; the pre-#66 + // QString{const QChar*} path stopped at the first NUL. Downstream name, + // list and value parsing was written against that first-NUL contract, so + // restore it here (radio name, vfo-count, dropdown-list, slider-range). + auto const nul = reply.payload.indexOf (QChar {0}); + result = nul < 0 ? reply.payload : reply.payload.left (nul); } CAT_TRACE (cmd << " ->" << result); return result; diff --git a/Transceiver/HRDTransceiver.hpp b/Transceiver/HRDTransceiver.hpp index f3db8bce..94066a29 100644 --- a/Transceiver/HRDTransceiver.hpp +++ b/Transceiver/HRDTransceiver.hpp @@ -5,7 +5,6 @@ #include <tuple> #include <memory> -#include <QScopedPointer> #include <QString> #include <QStringList> diff --git a/Transceiver/OmniRigTransceiver.cpp b/Transceiver/OmniRigTransceiver.cpp index 67f4b178..467d71ab 100644 --- a/Transceiver/OmniRigTransceiver.cpp +++ b/Transceiver/OmniRigTransceiver.cpp @@ -291,15 +291,21 @@ int OmniRigTransceiver::do_start () if (OmniRig::PM_FREQ & writable_params_) { - rig_->SetFreq (f); + QTimer::singleShot (200, [=] { + rig_->SetFreq (f); + }); } else if (reversed_ && (OmniRig::PM_FREQB & writable_params_)) { - rig_->SetFreqB (f); + QTimer::singleShot (200, [=] { + rig_->SetFreqB (f); + }); } else if (!reversed_ && (OmniRig::PM_FREQA & writable_params_)) { - rig_->SetFreqA (f); + QTimer::singleShot (200, [=] { + rig_->SetFreqA (f); + }); } update_rx_frequency (f); CAT_TRACE ("started"); diff --git a/Transceiver/TCITransceiver.cpp b/Transceiver/TCITransceiver.cpp index f3a8001b..86d8e76e 100644 --- a/Transceiver/TCITransceiver.cpp +++ b/Transceiver/TCITransceiver.cpp @@ -711,7 +711,10 @@ void TCITransceiver::onMessageReceived(const QString &str) if (args.at(1) == "0" ) mode_ = args.at(2).toLower(); else mode_ = args.at(1).toLower(); } else mode_ = args.at(1); if (started_mode_.isEmpty()) started_mode_ = mode_; - if (busy_mode_) return; // was tci_done1(); + if (busy_mode_) { + if (requested_mode_.isEmpty() || requested_mode_ == mode_) tci_done8(); + return; + } else if (!requested_mode_.isEmpty() && requested_mode_ != mode_ && !band_change) { sendTextMessage(mode_to_command(requested_mode_)); } @@ -1000,8 +1003,7 @@ void TCITransceiver::rig_split () if (busy_split_) return; if (tci_timer5_->isActive()) mysleep5(0); busy_split_ = true; - const QString cmd = CmdSplitEnable + SmDP + rx_ + SmCM + "false" + SmTZ; // changed from below so split always false - //const QString cmd = CmdSplitEnable + SmDP + rx_ + SmCM + (requested_split_ ? "true" : "false") + SmTZ; + const QString cmd = CmdSplitEnable + SmDP + rx_ + SmCM + (requested_split_ ? "true" : "false") + SmTZ; sendTextMessage(cmd); mysleep5(500); busy_split_ = false; @@ -1153,7 +1155,7 @@ void TCITransceiver::do_frequency (Frequency f, MODE m, bool no_ignore) if (!requested_mode_.isEmpty() && requested_mode_ != mode_ && !busy_mode_) { busy_mode_ = true; sendTextMessage(mode_to_command(requested_mode_)); - mysleep7(1000); + mysleep8(1000); if (requested_mode_.isEmpty() || requested_mode_ == mode_) update_mode (m); else { printf("%s TCI failed set mode %s->%s",QDateTime::QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),mode_.toStdString().c_str(),requested_mode_.toStdString().c_str()); diff --git a/bundle_fixup/CMakeLists.txt b/bundle_fixup/CMakeLists.txt index 79e7c7eb..0210c652 100644 --- a/bundle_fixup/CMakeLists.txt +++ b/bundle_fixup/CMakeLists.txt @@ -17,6 +17,10 @@ if (APPLE OR WIN32) # if a system Qt is used (e.g. installed in /usr/lib/), it will not be included in the installation set (fixup_exe "\$ENV{DESTDIR}\${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_BINDIR}/${CMAKE_PROJECT_NAME}${CMAKE_EXECUTABLE_SUFFIX}") + set (fixup_exes "${fixup_exe}") + if (NOT WSJT_SKIP_MAP65) + list (APPEND fixup_exes "\$ENV{DESTDIR}\${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_BINDIR}/map65${CMAKE_EXECUTABLE_SUFFIX}") + endif () #get_filename_component (hamlib_lib_dir ${Hamlib_LIBRARIES} PATH) @@ -80,8 +84,10 @@ if (APPLE OR WIN32) get_filename_component (usb_lib_dir ${Usb_LIBRARY} PATH) list (APPEND fixup_library_dirs ${usb_lib_dir}) - get_filename_component (portaudio_lib_dir ${Portaudio_LIBRARY} PATH) - list (APPEND fixup_library_dirs ${portaudio_lib_dir}/../bin) + if (NOT WSJT_SKIP_MAP65) + get_filename_component (portaudio_lib_dir ${Portaudio_LIBRARY} PATH) + list (APPEND fixup_library_dirs ${portaudio_lib_dir}/../bin) + endif () get_filename_component (fftw_lib_dir ${FFTW3F_LIBRARY} PATH) list (APPEND fixup_library_dirs ${fftw_lib_dir}) @@ -136,18 +142,85 @@ if (APPLE OR WIN32) ) set (gp_tool "objdump") # we want MinGW tool - not MSVC (See GetPrerequisites.cmake) - endif (WIN32) INSTALL (CODE " get_filename_component (the_path \"\$ENV{DESTDIR}\${CMAKE_INSTALL_PREFIX}/${WSJT_PLUGIN_DESTINATION}\" REALPATH) file (GLOB_RECURSE QTPLUGINS \"\${the_path}/*${CMAKE_SHARED_LIBRARY_SUFFIX}\") include (BundleUtilities) + function (gp_resolve_item_override context item exepath dirs resolved_item_var resolved_var) + string (TOLOWER \"\${item}\" item_lower) + if (item_lower MATCHES \"^(api-ms-win-|ext-ms-).*\\\\.dll$\") + set (api_set_root \"\$ENV{SystemRoot}\") + if (NOT api_set_root) + set (api_set_root \"\$ENV{windir}\") + endif () + file (TO_CMAKE_PATH \"\${api_set_root}/System32/\${item}\" api_set_path) + set (\${resolved_item_var} \"\${api_set_path}\" PARENT_SCOPE) + set (\${resolved_var} TRUE PARENT_SCOPE) + endif () + endfunction () set (BU_CHMOD_BUNDLE_ITEMS ON) set (gp_tool ${gp_tool}) - # canonicalize path in install context - get_filename_component (the_exe ${fixup_exe} REALPATH) - fixup_bundle (\"\${the_exe}\" \"\${QTPLUGINS}\" \"${fixup_library_dirs}\")" + set (fixup_exes \"${fixup_exes}\") + foreach (the_exe_path IN LISTS fixup_exes) + get_filename_component (the_exe \"\${the_exe_path}\" REALPATH) + fixup_bundle (\"\${the_exe}\" \"\${QTPLUGINS}\" \"${fixup_library_dirs}\") + endforeach ()" #COMPONENT runtime ) -endif (APPLE OR WIN32) + endif (WIN32) + + if(APPLE) + # Mark GCC/Fortran runtimes as system libs so fixup_bundle ignores them + set(_m65_fortran_system_libs + libgcc_s.1.1.dylib + libgfortran.5.dylib + libquadmath.0.dylib + ) + set(BU_SYSTEM_LIBS ${BU_SYSTEM_LIBS} ${_m65_fortran_system_libs}) + endif() + + if(APPLE AND CMAKE_Fortran_COMPILER_ID STREQUAL "GNU") + # Ask gfortran where its libs live + execute_process( + COMMAND ${CMAKE_Fortran_COMPILER} -print-file-name=libgfortran.5.dylib + OUTPUT_VARIABLE _gfortran_path + OUTPUT_STRIP_TRAILING_WHITESPACE + ) + get_filename_component(_gfortran_dir "${_gfortran_path}" DIRECTORY) + + # Append to fixup_library_dirs (a normal CMake list) + list(APPEND fixup_library_dirs "${_gfortran_dir}") + endif() + if(APPLE) + INSTALL (CODE " + # Resolve plugin directory + get_filename_component(the_path \"\$ENV{DESTDIR}\${CMAKE_INSTALL_PREFIX}/${WSJT_PLUGIN_DESTINATION}\" REALPATH) + + file(GLOB_RECURSE QTPLUGINS \"\${the_path}/*${CMAKE_SHARED_LIBRARY_SUFFIX}\") + + list(FILTER QTPLUGINS EXCLUDE REGEX \".*\\\\.exe\") + list(FILTER QTPLUGINS EXCLUDE REGEX \".*\\\\.dll\") + list(FILTER QTPLUGINS EXCLUDE REGEX \".*qthid.*\") + list(FILTER QTPLUGINS EXCLUDE REGEX \".*rigctl.*\") + + include(BundleUtilities) + set(BU_CHMOD_BUNDLE_ITEMS ON) + set(BU_SYSTEM_LIBS \"${BU_SYSTEM_LIBS}\") + + set(fixup_library_dirs \"${fixup_library_dirs}\") + + set(fixup_exes \"${fixup_exes}\") + foreach (the_exe_path IN LISTS fixup_exes) + get_filename_component(the_exe \"\${the_exe_path}\" REALPATH) + fixup_bundle( + \"\${the_exe}\" + \"\${QTPLUGINS}\" + \"\${fixup_library_dirs}\" + ) + endforeach () + ") + endif (APPLE) + +endif (APPLE OR WIN32) diff --git a/doc/common/links.adoc b/doc/common/links.adoc index 6fa989c0..0fb162b6 100644 --- a/doc/common/links.adoc +++ b/doc/common/links.adoc @@ -55,8 +55,7 @@ d). Edit lines as needed. Keeping them in alphabetic order help see dupes. :raspbian64: https://sourceforge.net/projects/wsjt/files/wsjtx-{VERSION}/wsjtx_{VERSION}_arm64.deb[wsjtx_{VERSION}_arm64.deb] :debian: https://www.debian.org/[Debian] :dev_guide: https://wsjt.sourceforge.io/wsjtx-doc/wsjt-dev-guide.html[Dev-Guide] -:devsvn: https://sourceforge.net/p/wsjt/wsjt/HEAD/tree/[Devel-SVN] -:devrepo: https://sourceforge.net/p/wsjt/wsjtx/ci/master/tree/[SourceForge] +:devrepo: https://github.com/WSJTX/wsjtx/[GitHub] :dimension4: http://www.thinkman.com/dimension4/[Thinking Man Software] :downloads: https://wsjtx.github.io/wsjtx/downloads.html[WSJT Downloads Page] :dxatlas: http://www.dxatlas.com/[Afreet Software, Inc.] @@ -91,11 +90,7 @@ d). Edit lines as needed. Keeping them in alphabetic order help see dupes. :projsummary: https://sourceforge.net/projects/wsjt/[Project Summary] :pskreporter: https://pskreporter.info/pskmap.html[PSK Reporter] :sourceforge: https://sourceforge.net/user/registration[SourceForge] -:sourceforge-jtsdk: https://sourceforge.net/projects/jtsdk[SourceForge JTSDK] :ubuntu_sdk: https://launchpad.net/~ubuntu-sdk-team/+archive/ppa[Ubuntu SDK Notice] -:win_openssl_packages: https://slproweb.com/products/Win32OpenSSL.html[Windows OpenSSL Packages] -:win32_openssl: https://sourceforge.net/projects/wsjt-x-improved/files/Additional%20Files/OpenSSL/Win32OpenSSL_Light-1_1_1a.msi/download[Win32 OpenSSL Light Package] -:win64_openssl: https://sourceforge.net/projects/wsjt-x-improved/files/Additional%20Files/OpenSSL/Win64OpenSSL_Light-1_1_1a.msi[Win64 OpenSSL Light Package] :writelog: https://writelog.com/[Writelog] :wsjtx_group: https://wsjtx.groups.io/g/main[WSJTX Group] :wsjt_group: https://groups.io/g/wsjtgroup[WSJT Group] @@ -109,31 +104,19 @@ d). Edit lines as needed. Keeping them in alphabetic order help see dupes. // Download Links :cty_dat: https://www.country-files.com/bigcty/cty.dat/[Amateur Radio Country Files] :jtbridge: https://jt-bridge.eller.nu/[JT-Bridge] -:jtsdk_doc: https://sourceforge.net/projects/wsjt/files/wsjtx-{VERSION}/JTSDK-DOC.exe[Download] -:jtsdk_installer: https://sourceforge.net/projects/jtsdk/files/win32/2.0.0/JTSDK-2.0.0-B2-Win32.exe/download[Download] -:jtsdk_omnirig: https://sourceforge.net/projects/jtsdk/files/win32/2.0.0/base/contrib/OmniRig.zip/download[Download] -:jtsdk_py: https://sourceforge.net/projects/wsjt/files/wsjtx-{VERSION}/JTSDK-PY.exe[Download] -:jtsdk_qt: https://sourceforge.net/projects/wsjt/files/wsjtx-{VERSION}/JTSDK-QT.exe[Download] -:jtsdk_vcredist: https://sourceforge.net/projects/jtsdk/files/win32/2.0.0/base/contrib/vcredist_x86.exe/download[Download] :nh6z: http://www.nh6z.net/Amatuer_Radio_Station_NH6Z/Other_Peoples_Software.html[here] :omnirig: http://www.dxatlas.com/OmniRig/Files/OmniRig.zip[Omni-Rig] :osx: https://sourceforge.net/projects/wsjt/files/wsjtx-{VERSION}/wsjtx-{VERSION}-Darwin.dmg[wsjtx-{VERSION}-Darwin.dmg] :osxarm: https://sourceforge.net/projects/wsjt/files/wsjtx-{VERSION}/wsjtx-{VERSION}-Arm-Darwin.dmg[wsjtx-{VERSION}-ARM-Darwin.dmg] :QRA64_EME: https://sourceforge.net/projects/wsjt/files/wsjtx-{VERSION}/QRA64_EME.pdf[QRA64 for microwave EME] -:svn: https://subversion.apache.org/packages.html#windows[Subversion] :win32: https://sourceforge.net/projects/wsjt/files/wsjtx-{VERSION}/wsjtx-{VERSION}-win32.exe[wsjtx-{VERSION}-win32.exe] :win64: https://sourceforge.net/projects/wsjt/files/wsjtx-{VERSION}/wsjtx-{VERSION}-win64.exe[wsjtx-{VERSION}-win64.exe] :wsjt-devel: https://sourceforge.net/projects/wsjt/lists/wsjt-devel/[wsjt-devel] -:wsjt-x-improved-community: https://sourceforge.net/projects/wsjt-x-improved/lists/wsjt-x-improved-community/[wsjt-x-improved-community] -:wsjt_repo: https://sourceforge.net/p/wsjt/wsjt_orig/ci/master/tree/[WSJT Source Repository] -:wspr_code: https://sourceforge.net/projects/wsjt/files/wsjtx-{VERSION}/WSPRcode.exe[WSPRcode.exe] -:wspr_svn: https://sourceforge.net/p/wsjt/wspr/ci/master/tree/[WSPR Source Repository] // MAIL-TO links :alex_efros: mailto:powerman@powerman.name[Alex Efros] :bill_somerville: mailto:g4wjs -at- c l a s s d e s i g n -dot- com [G4WJS] :dev_mail_list: https://sourceforge.net/mailarchive/forum.php?forum_name=wsjt-devel[WSJT Developers Email List] -:dev_mail_svn: https://sourceforge.net/auth/subscriptions/[WSJT SVN Archives] :devmail: mailto:wsjt-devel@lists.sourceforge.net[wsjt-devel@lists.sourceforge.net] :devmail1: mailto:wsjt-devel@lists.sourceforge.net[Post Message] :wsjtgroup_mail: mailto:wsjtgroup@groups.io[Post Message] diff --git a/doc/user_guide/en/acknowledgements.adoc b/doc/user_guide/en/acknowledgements.adoc index 5986a42d..7998233b 100644 --- a/doc/user_guide/en/acknowledgements.adoc +++ b/doc/user_guide/en/acknowledgements.adoc @@ -2,9 +2,9 @@ The _WSJT_ project was started by *K1JT* in 2001. Starting in 2005 it has been an Open Source project, and it has included the programs -_WSJT_, _MAP65_, _WSPR_, _WSJT-X_, and _QMAP_. *G4WJS* (since 2013), -*K9AN* (2015), *IV3NWV* (2016), *DG2YCB* (2021-2026), *N9ADG* (2022), -*G4KLA* (2024), *DL3WDG* (2024), *W3SZ* (2025), and *KJ5HST* (2026) +_WSJT_, _MAP65_, _WSPR_, _WSJT-X_, and _QMAP_. *G4WJS* (2013-2021), +*K9AN* (since 2015), *IV3NWV* (2016), *DG2YCB* (2021-2026), *N9ADG* (2022), +*G4KLA* (2024), *DL3WDG* (2024), *W3SZ* (2025), and *KJ5HST* and *KD0BTO* (2026) have made major contributions to _WSJT-X_. *G4WJS* and *W9MDB* also made major contributions to the _Hamlib_ library, on which _WSJT-X_ depends for rig control. diff --git a/doc/user_guide/en/controls-functions-wide-graph.adoc b/doc/user_guide/en/controls-functions-wide-graph.adoc index 1e791a29..22303d72 100644 --- a/doc/user_guide/en/controls-functions-wide-graph.adoc +++ b/doc/user_guide/en/controls-functions-wide-graph.adoc @@ -42,7 +42,8 @@ work properly, you should restrict the range of displayed frequencies so that only the active part of the spectrum is shown. - Check *Ref Spec* if you are using a pre-computed -<<REFERENCE_SPECTRUM,Reference Spectrum>>. +<<REFERENCE_SPECTRUM,Reference Spectrum>>. This control is available +only when a saved reference spectrum exists. - Select *Current* or *Cumulative* for the spectrum displayed in the bottom one-third of the Wide Graph window. *Current* is the average diff --git a/doc/user_guide/en/faq.adoc b/doc/user_guide/en/faq.adoc index 2c6a43b2..2ef71ab8 100644 --- a/doc/user_guide/en/faq.adoc +++ b/doc/user_guide/en/faq.adoc @@ -51,7 +51,9 @@ each instance of _WSJT-X_. I am getting a "Network Error - SSL/TLS support not installed" message. What should I do?:: -You need to install suitable _OpenSSL_ libraries - see <<OPENSSL,Instructions to install _OpenSSL_>>. +Update to the latest Windows installer package or reinstall _WSJT-X_. +Current Windows installers include the required _OpenSSL_ runtime DLLs; +see <<OPENSSL,Windows _OpenSSL_ troubleshooting>>. I occasionally get Rig Control Errors if I adjust my Icom rig's VFO. What's wrong?:: diff --git a/doc/user_guide/en/install-from-source.adoc b/doc/user_guide/en/install-from-source.adoc index b70e89c5..971901e4 100644 --- a/doc/user_guide/en/install-from-source.adoc +++ b/doc/user_guide/en/install-from-source.adoc @@ -10,6 +10,12 @@ following packages: - gfortran 4.8 or later - fftw3 - MinGW (for Windows only) +- OpenSSL runtime DLLs in the MinGW environment used for Windows + installer builds + +For Windows installer builds, the _OpenSSL_ runtime DLLs bundled with +the installer are taken from the build environment. The DLLs must match +the Qt libraries used by that environment. Source code for _WSJT-X_ v{VERSION} can be downloaded with the command: diff --git a/doc/user_guide/en/install-mac.adoc b/doc/user_guide/en/install-mac.adoc index f661276c..0c589343 100644 --- a/doc/user_guide/en/install-mac.adoc +++ b/doc/user_guide/en/install-mac.adoc @@ -1,9 +1,8 @@ -For *macOS 10.15* and later installers are provided for x86_64 (Intel) +For *macOS* installers are provided for x86_64 (Intel) systems and for ARM64 (Apple silicon) systems. Download the correct package for your system from the {downloads}, double-click on the file name, and follow the on-screen prompts in the Installer -app. Double-click and consult the `ReadMe` file for important -installation notes. +app. If you have already installed a previous version, you can retain it by changing its name in the *Applications* folder (such as from _WSJT-X_ to diff --git a/doc/user_guide/en/install-windows.adoc b/doc/user_guide/en/install-windows.adoc index 81e40642..07130437 100644 --- a/doc/user_guide/en/install-windows.adoc +++ b/doc/user_guide/en/install-windows.adoc @@ -32,36 +32,23 @@ NOTE: Having a PC clock that appears to be synchronized to UTC is not synchronization errors gradually. [[OPENSSL]] - -* _WSJT-X_ uses the _OpenSSL_ libraries, and these are usually -installed by defajult. If an incompatible OpenSSL version is already -installed on your system. you will see the following error message -shortly after requesting a fetch of the latest LoTW users database. To -fix this problem, install the _OpenSSL_ libraries. -image::LoTW_TLS_error.png[align="center",alt="SSL/TLS"] - -You can download a suitable _OpenSSL_ package for Windows from -{win_openssl_packages}; you need the latest *Windows Light* -version. For the 32-bit _WSJT-X_ build, use the latest Win32 v1.1.1 -version of the _OpenSSL_ libraries, for the 64-bit _WSJT-X_ use the -latest Win64 v1.1.1 version of the _OpenSSL_ libraries (Note: it is OK -to install both versions on a 64-bit system) which, at the time of -writing, were {win32_openssl} and {win64_openssl} respectively. +* _WSJT-X_ uses the _OpenSSL_ libraries for TLS network connections. +Current _WSJT-X_ Windows installers include the required _OpenSSL_ +runtime DLLs. If they are missing or cannot be loaded, you may see the +following error message when using features such as _SuperFox_ +verification, *Update Hamlib*, _LoTW_ downloads, or _eQSL_ uploads. -Install the package and accept the default options, including the -option to copy the _OpenSSL_ DLLs to the Windows system -directory. There is no obligation to donate to the _OpenSSL_ -project. Un-check all the donation options if desired. + +image::LoTW_TLS_error.png[align="center",alt="SSL/TLS"] -NOTE: If you still get the same network error after installing the - _OpenSSL_ libraries then you also need to install the - {msvcpp_redist} component. From the download page select - `vcredist_x86.exe` for use with the 32-bit _WSJT-X_ build or - `vcredist_x64.exe` with the 64-bit build, then run it to - install. +If you installed _WSJT-X_ from the official Windows installer, first +try updating to the latest installer package. Reinstalling the same +package may help if files in the local installation were removed or +damaged. The _OpenSSL_ DLLs must match the Qt libraries used to build +the program and are normally installed with _WSJT-X_, so installing +unrelated system-wide _OpenSSL_ DLLs is not the recommended fix. -TIP: If you cannot install the _OpenSSL_ libraries or do not have an +TIP: If you cannot update or reinstall _WSJT-X_, or do not have an Internet connection on the computer used to run _WSJT-X_ {VERSION_MAJOR}.{VERSION_MINOR}, you can download the _LoTW_ file manually. Go to diff --git a/doc/user_guide/en/intro_subsections.adoc b/doc/user_guide/en/intro_subsections.adoc index b51138a7..80f0a979 100644 --- a/doc/user_guide/en/intro_subsections.adoc +++ b/doc/user_guide/en/intro_subsections.adoc @@ -57,15 +57,16 @@ image::Main_Window_ja.png[align="center"] _WSJT-X_ is part of an open-source project released under the {gnu_gpl} (GPLv3). If you have programming or documentation skills or would like to contribute to the project in other ways, please make -your interests known to the development team. We especially encourage -those with translation skills to volunteer their help, either for -this _User Guide_ or for the program's user interface. - -The project's source-code repository can be found at {devrepo}. Bug -reports and suggestions for new features, improvements to the _WSJT-X -User Guide_, etc., may be sent to one of the email lists listed in the -<<SUPPORT,Support>> section. You must join the group in order to post -messages to the email list. +your interests known to the development team. The project's public +source-code repository can be found at {devrepo}, and you can open +Issues and submit explicit pull requests there. We encourage those +with translation skills to volunteer their help by translating this +_User Guide_ or the program's user interface. + +Bug reports and suggestions for new features or improvements to the +_User Guide_ may be submitted at the {devrepo} site or sent to +one of the email lists listed in the <<SUPPORT,Support>> section. You +must join the group in order to post messages there. === License diff --git a/doc/user_guide/en/introduction.adoc b/doc/user_guide/en/introduction.adoc index 4bad7e74..287df6ab 100644 --- a/doc/user_guide/en/introduction.adoc +++ b/doc/user_guide/en/introduction.adoc @@ -13,9 +13,9 @@ and 2016, respectively. Bill Somerville died unexpectedly in December afterward and worked with us until February 2026. Brian Moran, N9ADG, joined the team in 2022; John Nelson, G4KLA and Charlie Suckling, DL3WDG in 2024; Roger Rehr, W3SZ, in 2025; and Terrell Deppe, KJ5HST, -in 2026. Over the years many other hams have contributed to _WSJT-X_ -development in more limited ways. We are extremely grateful for all of -these contributions. +and David Christle, KD0BTO, in 2026. Over the years many other hams +have contributed to _WSJT-X_ development in more limited ways. We are +extremely grateful for all of these contributions. _WSJT-X_ provides flexible rig control for nearly all modern radios used by amateurs and a wide variety of special aids such as automatic @@ -24,17 +24,17 @@ testing. The program analyzes received passbands up to 5 kHz wide and runs equally well on Windows, Macintosh, and Linux systems. *Version Numbers* for our programs have major, minor, and patch -numbers separated by periods: for example, _WSJT-X 2.7.0. Temporary +numbers separated by periods: for example, _WSJT-X 3.0.0_. Temporary release candidates are sometimes made in advance of a new general-availability (GA) release, in order to obtain user feedback. Release candidates are given version labels such as -2.7.0-rc1, 2.7.0-rc2, etc., leading up to the general availability -(GA) release of version 2.7.0. Release candidates should be used only +3.0.0-rc1, 3.0.0-rc2, etc., leading up to the general availability +(GA) release of version 3.0.0. Release candidates should be used only during a defined testing period, and they carry an implicit obligation to provide feedback to the program developers. Release candidates should not be used on the air after a GA release with the same number. -*_MAP65_* and *_QMAP_* are companion programs written by K1JT to +*_MAP65_* and *_QMAP_* are companion programs originally written by K1JT to facilitate Earth-Moon-Earth (EME, or "Moonbounce") communication with digital protocols developed for _WSJT_ and _WSJT-X_. When used with radio-frequency hardware providing coherent signal channels for two diff --git a/doc/user_guide/en/measurement_tools.adoc b/doc/user_guide/en/measurement_tools.adoc index b2d937d9..77e69c71 100644 --- a/doc/user_guide/en/measurement_tools.adoc +++ b/doc/user_guide/en/measurement_tools.adoc @@ -102,15 +102,23 @@ records. [[REFERENCE_SPECTRUM]] === Reference Spectrum +_(Not yet fully implemented.)_ + _WSJT-X_ provides a tool that can be used to determine the detailed shape of your receiver's passband. Tune to a quiet frequency with no signals or birdies. With _WSJT-X_ running in one of the slow modes and *Monitor* active, make sure that *Flatten* is checked on the *Wide Graph* and then select *Measure reference spectrum* from the *Tools* menu. Wait for about a minute and then click *Stop*. A file named -`refspec.dat` will appear in your log directory. When you check *Ref -Spec* on the *Wide Graph*, the recorded reference spectrum will then -be used to flatten your overall effective passband. +`refspec.dat` will appear in your log directory and the *Ref Spec* +checkbox on the *Wide Graph* will become available. When you check +*Ref Spec*, the recorded reference spectrum will then be used to +flatten your overall effective passband. + +Select *Erase reference spectrum* from the *Tools* menu to remove the +saved reference spectrum and stop applying its correction to new +received data. Existing waterfall rows remain on the display until +they scroll off normally. === Phase Equalization diff --git a/doc/user_guide/en/new_features.adoc b/doc/user_guide/en/new_features.adoc index 013594a1..6a8f34cc 100644 --- a/doc/user_guide/en/new_features.adoc +++ b/doc/user_guide/en/new_features.adoc @@ -93,10 +93,8 @@ the sub-modes 15A, 15B and 15C can be decoded with EME delay. mode. New checkboxes on the *File | Settings | Reporting* tab provide new support for certain contests. -- *OpenSSL* is now installed automatically with _WSJT-X_. Manual -intervention is necessary only if another, incompatible OpenSSL -version is already installed on the computer. +- *OpenSSL* runtime DLLs are now installed automatically with _WSJT-X_ +on Windows. - *High Resolution Monitors* are supported with better scaling of fonts and widget sizes. - diff --git a/doc/user_guide/en/support.adoc b/doc/user_guide/en/support.adoc index 32ed31d1..9bde8ee6 100644 --- a/doc/user_guide/en/support.adoc +++ b/doc/user_guide/en/support.adoc @@ -1,11 +1,11 @@ === Help with Setup -The best source of help in setting up your station or configuring -_WSJT-X_ will be one of these email lists: {wsjt-devel} or -{wsjtx_group}. The chances are good that someone with similar -interests and equipment has already solved your problem and will be -happy to help. To post messages in any of these forums you will need -to join the group. +The best source of help in setting up your station or configuring or +using _WSJT-X_ will be one of these email lists: {wsjtx_group}, +{wsjt_group}, or {wsjt-devel}. The chances are good that someone with +similar interests and equipment has already solved your problem and +will be happy to help. To post messages in any of these forums you +will need to join the group. === Bug Reports @@ -27,6 +27,6 @@ information: Suggestions from users often result in new program features. Good ideas are always welcome: if there's a feature you would like to see in _WSJT-X_, spell it out in as much detail as seems useful and send -it to us at one of the email addresses given a few lines above. Be -sure to explain why you think the feature is desirable, and what sort -of other users might find it so. +it to us at the public {devrepo} site or one of the email addresses +given above. Be sure to explain why you think the feature is +desirable, and what sort of other users might find it so. diff --git a/doc/user_guide/en/wsjtx-main.adoc b/doc/user_guide/en/wsjtx-main.adoc index 062d3c93..0e54555b 100644 --- a/doc/user_guide/en/wsjtx-main.adoc +++ b/doc/user_guide/en/wsjtx-main.adoc @@ -1,6 +1,6 @@ // This is a comment line, anything with // is ignored at process time. = _WSJT-X_ User Guide -//Joseph H Taylor, Jr, K1JT et al. +Copyright 2026 by Joe Taylor, K1JT :revnumber: {VERSION} // For web-pages, adding :badges: is ok, but is a security issue for // package building .deb, .rpm, etc as it exposes the IP address and the images @@ -10,7 +10,7 @@ :imagesdir: {docdir}/images :icons: font :numbered: -:keywords: amateur radio weak signal communication K1JT WSJT JT65 JT9 +:keywords: amateur radio weak signal communication K1JT WSJT FT8 Q65 MSK!44 JT65 :description: Software for Amateur Radio Weak-Signal Communication :prog: WSJT-X diff --git a/lib/77bit/packjt77.f90 b/lib/77bit/packjt77.f90 index 35236b37..eab4ff6c 100644 --- a/lib/77bit/packjt77.f90 +++ b/lib/77bit/packjt77.f90 @@ -90,22 +90,63 @@ end subroutine hash22 integer function ihashcall(c0,m) + implicit none - integer*8 n8 - character*13 c0 + character(len=13), intent(in) :: c0 + integer, intent(in) :: m + integer(kind=8) :: n8 + integer :: i,j character*38 c data c/' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ/'/ - n8=0 + n8=0_8 do i=1,11 j=index(c,c0(i:i)) - 1 - n8=38*n8 + j + n8=38_8*n8 + j enddo - ihashcall=ishft(47055833459_8*n8,m-64) + + ihashcall=ihashcall_from_n8(n8,m) return end function ihashcall +integer function ihashcall_from_n8(n8,m) + implicit none + + integer(kind=8), intent(in) :: n8 + integer, intent(in) :: m + integer(kind=8), parameter :: hash_factor(0:3) = (/2419_8, 62655_8, 10_8, 0_8/) + integer(kind=8) :: b(0:3), p(0:3) + integer(kind=8) :: carry, term + integer(kind=8) :: x + integer :: i,j + + x=n8 + do i=0,3 + b(i)=mod(x,65536_8) + x=x/65536_8 + enddo + + ! Return the top m bits of the low 64 bits of 47055833459*n8. + carry=0_8 + do i=0,3 + term=carry + do j=0,i + term=term+hash_factor(j)*b(i-j) + enddo + p(i)=mod(term,65536_8) + carry=term/65536_8 + enddo + + if(m.le.16) then + ihashcall_from_n8=int(p(3)/(2_8**(16-m))) + else + ihashcall_from_n8=int(p(3)*(2_8**(m-16)) + p(2)/(2_8**(32-m))) + endif + + return +end function ihashcall_from_n8 + subroutine save_hash_call(c13,n10,n12,n22) character*13 c13,cw @@ -1765,18 +1806,21 @@ subroutine hash22var(n22,c13,nthr) end subroutine hash22var integer function ihashcallvar(c0,m) + implicit none - integer*8 n8 - character*13 c0 - character*38 c + character(len=13), intent(in) :: c0 + integer, intent(in) :: m + integer(kind=8) :: n8 + integer :: i,j + character*38 :: c data c/' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ/'/ - n8=0 + n8=0_8 do i=1,11 j=index(c,c0(i:i)) - 1 - n8=38*n8 + j + n8=38_8*n8 + j enddo - ihashcallvar=ishft(47055833459_8*n8,m-64) + ihashcallvar=ihashcall_from_n8(n8,m) return end function ihashcallvar diff --git a/lib/decoder.f90 b/lib/decoder.f90 index 6d8e2fe0..4dbb0515 100644 --- a/lib/decoder.f90 +++ b/lib/decoder.f90 @@ -23,7 +23,6 @@ subroutine multimode_decoder(ss,id2,params,nfsample) use packjt77, only : lcommonft8b,ihash22var,calls12var,calls22var include 'jt9com.f90' - include 'timer_common.inc' type, extends(jt4_decoder) :: counting_jt4_decoder integer :: decoded diff --git a/lib/ft8var/cwfilter.f90 b/lib/ft8var/cwfilter.f90 index 913c7e3e..d3ec35fb 100644 --- a/lib/ft8var/cwfilter.f90 +++ b/lib/ft8var/cwfilter.f90 @@ -17,7 +17,12 @@ subroutine cwfilter(first) !note that with new, larger ALLCALL7.TXT files, dimensions of various ncall arrays may need to be increased in jt65_mod9.f90 !on 20250709 callj dim was increased from 9000 to 10000 when updated ALLCALL7.TXT file was added if(first) then - open(24,file='ALLCALL7.TXT',status='unknown') ! accepting Australian 7-char callsigns + ! Open the shipped read-only ALLCALL7.TXT for reading only. status='old' with + ! action='read' makes a missing/unreadable file degrade cleanly to an empty + ! callsign DB (handled by the count check below) instead of status='unknown' + ! attempting a create in the read-only app bundle, which aborts the decoder. + open(24,file=trim(share_dir)//'/ALLCALL7.TXT',status='old',action='read',iostat=ios) ! accepting Australian 7-char callsigns + if(ios.ne.0) go to 20 do i=1,MAXC read(24,1004,end=20) line 1004 format(a80) diff --git a/lib/get_q3list.f90 b/lib/get_q3list.f90 index a6b6de81..0b483759 100644 --- a/lib/get_q3list.f90 +++ b/lib/get_q3list.f90 @@ -127,6 +127,8 @@ end subroutine rm_q3list subroutine jpl_setup(fname) character*256 fname,jpleph_file_name common/jplcom/jpleph_file_name - jpleph_file_name=fname + j=index(fname,char(0)) + jpleph_file_name(1:j)=fname(1:j) + jpleph_file_name(j:)=' ' return end subroutine jpl_setup diff --git a/lib/jt9.f90 b/lib/jt9.f90 index 64901c09..c6c80164 100644 --- a/lib/jt9.f90 +++ b/lib/jt9.f90 @@ -134,6 +134,8 @@ program jt9 exe_dir = optarg(:arglen) case ('a') data_dir = optarg(:arglen) + case ('r') + share_dir = optarg(:arglen) ! read-only shipped-data dir (cty.dat, ALLCALL7.TXT, ...) case ('b') nsubmode = ichar (optarg(:1)) - ichar ('A') case ('t') @@ -220,7 +222,7 @@ program jt9 print *, 'Usage: jt9 [OPTIONS] file1 [file2 ...]' print *, ' Reads data from *.wav files.' print *, '' - print *, ' jt9 -s <key> [-w patience] [-m threads] [-e path] [-a path] [-t path]' + print *, ' jt9 -s <key> [-w patience] [-m threads] [-e path] [-a path] [-t path] [-r path]' print *, ' Gets data from shared memory region with key==<key>' print *, '' print *, 'OPTIONS:' diff --git a/lib/jt9a.f90 b/lib/jt9a.f90 index 35f8c0c2..f45661c7 100644 --- a/lib/jt9a.f90 +++ b/lib/jt9a.f90 @@ -120,6 +120,7 @@ subroutine jt9a() endif elseif (local_params%nmode.eq.8 .and. local_params%lmultift8 .and. .not. & local_params%ndiskdat) then + npts1=180000 dd(1:npts1)=shared_data%id2(1:npts1) rms=sum(abs(dd(1:10))) + sum(abs(dd(76001:76010))) + sum(abs(dd(151670:151680))) dd8(1:npts1)=dd(1:npts1) diff --git a/lib/map65_mmdec.f90 b/lib/map65_mmdec.f90 index 14871857..3d7512a9 100644 --- a/lib/map65_mmdec.f90 +++ b/lib/map65_mmdec.f90 @@ -1,20 +1,28 @@ +module map65_mmdec_mod + implicit none +contains + subroutine map65_mmdec(nutc,id2,nqd,ntrperiod, nsubmode,nfa,nfb,nfqso, & ntol,newdat,nagain,max_drift,ndepth,mycall,hiscall,hisgrid) use prog_args use timer_module, only: timer use q65_decode + use iso_fortran_env, only: int16 include 'jt9com.f90' - include 'timer_common.inc' type, extends(q65_decoder) :: counting_q65_decoder integer :: decoded end type counting_q65_decoder logical single_decode,bVHF,lnewdat,lagain,lclearave,lapcqonly - integer*2 id2(300*12000) + integer(int16) id2(300*12000) integer nqf(20) + integer nutc,nqd,ntrperiod,nsubmode,nfa,nfb,nfqso,ntol + integer newdat,nagain,max_drift,ndepth,navg0,ncontest + integer nqsoprogress,ntr0 + real emedelay ! type(params_block) :: params character(len=12) :: mycall, hiscall character(len=6) :: hisgrid @@ -88,3 +96,4 @@ contains end subroutine q65_decoded end subroutine map65_mmdec +end module map65_mmdec_mod
\ No newline at end of file diff --git a/lib/refspectrum.f90 b/lib/refspectrum.f90 index 68b514f9..862d38f0 100644 --- a/lib/refspectrum.f90 +++ b/lib/refspectrum.f90 @@ -35,7 +35,16 @@ subroutine refspectrum(id2,bclear,brefspec,buseref,fname) xs=0. first=.false. endif - if(bclear) s=0. + if(bclear) then + s=0. + fil=1.0 + ref=0.0 + filter=0.0 + cfil=0.0 + xs=0.0 + nsave=0 + blastuse=.false. + endif if(brefspec) then x(0:NH-1)=0.001*id2(1:NH) diff --git a/map65/CMakeLists.txt b/map65/CMakeLists.txt index 7de82d12..9d1b45bb 100644 --- a/map65/CMakeLists.txt +++ b/map65/CMakeLists.txt @@ -6,17 +6,20 @@ 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 main.cpp mainwindow.cpp messages.cpp meterwidget.cpp plotter.cpp - PSKReporter.cpp + ../Network/PSKReporter.cpp + ../Network/PSKReporterIPFIX.cpp Radio.cpp set570.cpp signalmeter.cpp @@ -26,10 +29,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 +53,55 @@ 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) +# Executable: only the .rc file is Windows-only +if (WIN32) + add_executable(map65 + ${map65_CXXSRCS} + ${map65_CSRCS} + ${map65_GENUISRCS} + map65.rc + ) +else() + add_executable(map65 + ${map65_CXXSRCS} + ${map65_CSRCS} + ${map65_GENUISRCS} + ) +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 (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..1d92e0c3 100644 --- a/map65/about.cpp +++ b/map65/about.cpp @@ -11,10 +11,10 @@ CAboutDlg::CAboutDlg(QWidget *parent) : + 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 />" + "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 Group."); + "Develolpment Group."); } CAboutDlg::~CAboutDlg() 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..bbef8ed0 --- /dev/null +++ b/map65/commons.cpp @@ -0,0 +1,8 @@ +#include "commons.h" + +extern "C" { + float* dd = nullptr; + float* ss = nullptr; + float* savg = nullptr; +} + diff --git a/map65/commons.h b/map65/commons.h index 16aecb89..d717f82c 100644 --- a/map65/commons.h +++ b/map65/commons.h @@ -5,12 +5,15 @@ #include <QString> -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 +48,93 @@ 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; + 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_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_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); + 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); } extern QStringList allDecodes; @@ -54,5 +144,149 @@ extern QString guiDate; extern bool m_w3szUrl; extern QString m_otherUrl; extern bool m_spot_to_psk_reporter; +extern bool m_psk_reporter_tcpip; + +// 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..2b1e9e8f 100644 --- a/map65/devsetup.cpp +++ b/map65/devsetup.cpp @@ -4,11 +4,54 @@ #include <QDebug> #include <cstdio> #include <portaudio.h> +#include <vector> +#include <QDir> +#include <QStringList> +#include <QSerialPortInfo> +#include <QRegularExpression> + +#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); + + if (ma.hasMatch() && mb.hasMatch()) + return ma.captured(1).toInt() < mb.captured(1).toInt(); + + return a < b; + }); + + return result; +} -#define MAXDEVICES 200 +#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 m_restartSoundIn=false; @@ -17,8 +60,13 @@ DevSetup::DevSetup(QWidget *parent) : QDialog(parent) 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(); + }); } @@ -29,97 +77,160 @@ DevSetup::~DevSetup() 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 (!(96000 >= minSpeed[id] && 96000 <= 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 - 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", + 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; + + // 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 + + 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)); + ui.networkRadioButton->setChecked(mw->m_network); + ui.soundCardRadioButton->setChecked(!mw->m_network); + ui.rb96000->setChecked(mw->m_fs96000); + ui.rb95238->setChecked(!mw->m_fs96000); + 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 +249,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,49 +267,63 @@ 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(); + 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_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(); + + 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=ui.faddEntry->text().toDouble(); + mw->m_network=ui.networkRadioButton->isChecked(); + mw->m_fs96000=ui.rb96000->isChecked(); + 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(); - m_spot_to_psk_reporter = ui.pskBox->isChecked(); + mw->m_spot_to_psk_reporter = ui.pskBox->isChecked(); + mw->m_psk_reporter_tcpip = ui.pskReporterTcpIpBox->isChecked(); QDialog::accept(); } @@ -218,36 +344,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 +432,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 +525,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..9ae4bad9 100644 --- a/map65/devsetup.h +++ b/map65/devsetup.h @@ -5,58 +5,21 @@ #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; - - QString m_otherUrl; //liveCQ - bool m_w3szUrl; //liveCQ - bool m_spot_to_psk_reporter; //PSKReporter public slots: void accept(); @@ -90,6 +53,7 @@ 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; }; diff --git a/map65/devsetup.ui b/map65/devsetup.ui index c15e06f0..e9d2746c 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> @@ -403,7 +344,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 +367,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 +400,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 +448,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 +578,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 +643,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 +727,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 +745,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 +788,7 @@ <item> <spacer name="horizontalSpacer_5"> <property name="orientation"> - <enum>Qt::Horizontal</enum> + <enum>Qt::Orientation::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> @@ -870,7 +811,7 @@ <item> <spacer name="horizontalSpacer_6"> <property name="orientation"> - <enum>Qt::Horizontal</enum> + <enum>Qt::Orientation::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> @@ -890,7 +831,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,7 +918,7 @@ <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> @@ -986,10 +927,10 @@ <item> <spacer name="horizontalSpacer_17"> <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> @@ -1009,10 +950,10 @@ <item> <spacer name="horizontalSpacer_19"> <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> @@ -1032,10 +973,10 @@ <item> <spacer name="horizontalSpacer_20"> <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> @@ -1055,10 +996,10 @@ <item> <spacer name="horizontalSpacer_18"> <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> @@ -1084,7 +1025,7 @@ <string>Background</string> </property> <property name="alignment"> - <set>Qt::AlignCenter</set> + <set>Qt::AlignmentFlag::AlignCenter</set> </property> </widget> </item> @@ -1115,10 +1056,10 @@ <item> <spacer name="horizontalSpacer_14"> <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> @@ -1144,7 +1085,7 @@ <string>Newest</string> </property> <property name="alignment"> - <set>Qt::AlignCenter</set> + <set>Qt::AlignmentFlag::AlignCenter</set> </property> </widget> </item> @@ -1213,7 +1154,7 @@ <string>2nd</string> </property> <property name="alignment"> - <set>Qt::AlignCenter</set> + <set>Qt::AlignmentFlag::AlignCenter</set> </property> </widget> </item> @@ -1285,7 +1226,7 @@ <string>3rd</string> </property> <property name="alignment"> - <set>Qt::AlignCenter</set> + <set>Qt::AlignmentFlag::AlignCenter</set> </property> </widget> </item> @@ -1360,7 +1301,7 @@ <string>Oldest</string> </property> <property name="alignment"> - <set>Qt::AlignCenter</set> + <set>Qt::AlignmentFlag::AlignCenter</set> </property> </widget> </item> @@ -1426,7 +1367,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 +1387,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 +1444,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 +1469,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 +1521,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 +1573,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 +1622,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 +1665,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 +1693,104 @@ <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="4" column="0"> + <widget class="QCheckBox" name="pskReporterTcpIpBox"> + <property name="text"> + <string>Use TCP/IP for 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="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/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..67e4961e 100644 --- a/map65/libm65/CMakeLists.txt +++ b/map65/libm65/CMakeLists.txt @@ -1,14 +1,27 @@ 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 + 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 +29,7 @@ set (libm65_FSRCS chkmsg.f90 coord.f90 dcoord.f90 + debug_log.f90 decode0.f90 decode1a.f90 decode65b.f90 @@ -29,13 +43,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 +66,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 @@ -73,6 +91,7 @@ set (libm65_FSRCS smo.f90 sun.f90 symspec.f90 + test_astro_pipeline.f90 # timer.f90 timf2.f90 tm2.f90 @@ -103,18 +122,32 @@ 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 - ) +#set (libm65_CXXSRCS +# ipcomm.cpp +# ) add_definitions (-DBIGSYM=1) set_source_files_properties (sec_midn.f90 PROPERTIES COMPILE_FLAGS -fno-second-underscore) +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,12 +161,45 @@ 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 should not choose between wsjt_fort and wsjt_fort_omp locally. The +# common interface target keeps the variant policy in one place and still +# resolves to wsjt_fort_omp when OPENMP_ONLY leaves no non-OpenMP library. +# Default BOTH builds intentionally use the non-OpenMP common target here; +# release Windows and Linux builds pin OPENMP_ONLY when MAP65 needs OpenMP. +target_link_libraries (m65impl PUBLIC Qt5::Core) +wsjt_link_common_fortran (m65impl) + +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_include_directories(mapsim PRIVATE ${CMAKE_BINARY_DIR}/mod ) target_link_libraries (mapsim m65impl ${FFTW3_LIBRARIES}) #add_executable (synctest synctest.f90) @@ -141,7 +207,7 @@ target_link_libraries (mapsim 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..8083d924 100644 --- a/map65/libm65/afc65b.f90 +++ b/map65/libm65/afc65b.f90 @@ -1,70 +1,111 @@ +module afc65b_mod + implicit none +contains + subroutine afc65b(cx,cy,npts,fsample,nflip,ipol,xpol,ndphi,a,ccfbest,dtbest) + use debug_log + use fchisq_mod + + implicit none + + logical :: xpol + integer :: npts, nflip, ipol, ndphi + complex :: cx(npts), cy(npts) + real :: a(5), deltaa(5) + integer :: iter, j, nterms + real :: ccfbest, dtbest + real :: chisq1, chisq2, chisq3, chisqr, chisqr0 + real :: delta, dtmax, fn, tmp + real :: fsample, ccfmax - 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 - 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 + ! 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 + + ! Don't fit polarization when solving for dphi + if (ndphi /= 0) nterms = 3 + + ! Start the iteration + chisqr = 0.0 + chisqr0 = 1.0e6 + + do iter = 1, 3 ! One iteration is enough? + do j = 1, nterms + chisq1 = fchisq(cx,cy,npts,fsample,nflip,a,ccfmax,dtmax) + fn = 0.0 + delta = deltaa(j) + + ! Find first step where chisq changes + do + a(j) = a(j) + delta + chisq2 = fchisq(cx,cy,npts,fsample,nflip,a,ccfmax,dtmax) + if (chisq2 /= chisq1) exit + end do + + ! If we stepped uphill, reverse direction and swap labels + if (chisq2 > chisq1) then + delta = -delta + a(j) = a(j) + delta + tmp = chisq1 + chisq1 = chisq2 + chisq2 = tmp 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. + ! Walk while chisq keeps improving + do + fn = fn + 1.0 + a(j) = a(j) + delta + chisq3 = fchisq(cx,cy,npts,fsample,nflip,a,ccfmax,dtmax) + if (chisq3 < chisq2) then + chisq1 = chisq2 + chisq2 = chisq3 + else + exit + endif + end do + + ! Guard against division by zero in flat regions + if (chisq3 == chisq2) cycle + + ! Find minimum of parabola defined by last three points + delta = delta*(1.0/(1.0 + (chisq1 - chisq2)/(chisq3 - chisq2)) + 0.5) + a(j) = a(j) - delta + deltaa(j) = deltaa(j)*fn/3.0 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 (chisqr/chisqr0 > 0.9999) exit + chisqr0 = chisqr enddo -30 ccfbest=ccfmax * (1378.125/fsample)**2 - dtbest=dtmax + ccfbest = ccfmax * (1378.125/fsample)**2 + dtbest = dtmax + + ! Wrap polarization angle into [0,180) + if (a(4) < 0.0) a(4) = a(4) + 180.0 + if (a(4) >= 180.) a(4) = a(4) - 180.0 + if (nint(a(4)) == 180) a(4) = 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 (a(4) < 0.0 .or. a(4) >= 180.0) then + ! print *, 'afc65b: bad a(4) after wrap, set to 0. was ', a(4) + a(4) = 0.0 + endif - return + ipol = nint(a(4)/45.0) + 1 + if (ipol > 4) ipol = ipol - 4 + end subroutine afc65b + +end module afc65b_mod diff --git a/map65/libm65/astro.f90 b/map65/libm65/astro.f90 index d34819cc..d8304671 100644 --- a/map65/libm65/astro.f90 +++ b/map65/libm65/astro.f90 @@ -1,105 +1,151 @@ -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_int16, 246_int16, 257_int16, 267_int16, 275_int16, 280_int16, 283_int16, 286_int16, 291_int16, 298_int16, & + 305_int16, 313_int16, 322_int16, 331_int16, 341_int16, 351_int16, 361_int16, 369_int16, 376_int16, 381_int16, & + 383_int16, 382_int16, 379_int16, 374_int16, 370_int16, 366_int16, 363_int16, 361_int16, 363_int16, 368_int16, & + 376_int16, 388_int16, 401_int16, 415_int16, 428_int16, 440_int16, 453_int16, 467_int16, 487_int16, 512_int16, & + 544_int16, 579_int16, 607_int16, 618_int16, 609_int16, 588_int16, 563_int16, 539_int16, 512_int16, 482_int16, & + 450_int16, 422_int16, 398_int16, 379_int16, 363_int16, 349_int16, 334_int16, 319_int16, 302_int16, 282_int16, & + 262_int16, 242_int16, 226_int16, 213_int16, 205_int16, 200_int16, 198_int16, 197_int16, 196_int16, 197_int16, & + 200_int16, 202_int16, 204_int16, 205_int16, 204_int16, 203_int16, 202_int16, 201_int16, 203_int16, 206_int16, & + 212_int16, 218_int16, 223_int16, 227_int16, 231_int16, 236_int16, 240_int16, 243_int16, 247_int16, 257_int16, & + 276_int16, 301_int16, 324_int16, 339_int16, 346_int16, 344_int16, 339_int16, 331_int16, 323_int16, 316_int16, & + 312_int16, 310_int16, 312_int16, 317_int16, 327_int16, 341_int16, 358_int16, 375_int16, 392_int16, 407_int16, & + 422_int16, 437_int16, 451_int16, 466_int16, 480_int16, 494_int16, 511_int16, 530_int16, 552_int16, 579_int16, & + 612_int16, 653_int16, 702_int16, 768_int16, 863_int16,1008_int16,1232_int16,1557_int16,1966_int16,2385_int16, & + 2719_int16,2924_int16,3018_int16,3038_int16,2986_int16,2836_int16,2570_int16,2213_int16,1823_int16,1461_int16, & + 1163_int16, 939_int16, 783_int16, 677_int16, 602_int16, 543_int16, 494_int16, 452_int16, 419_int16, 392_int16, & + 373_int16, 360_int16, 353_int16, 350_int16, 350_int16, 350_int16, 350_int16, 350_int16, 350_int16, 348_int16, & + 344_int16, 337_int16, 329_int16, 319_int16, 307_int16, 295_int16, 284_int16, 276_int16, 272_int16, 272_int16, & + 273_int16, 274_int16, 274_int16, 271_int16, 266_int16, 260_int16, 252_int16, 245_int16, 238_int16, 231_int16 ] + + 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_real64, poloffset2 = 0.0_real64 + 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 = real(nfreq,real64)*1.0e6_real64 + if (nfreq == 2) freq = 1.8e6_real64 + if (nfreq == 4) freq = 3.5e6_real64 + + 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_real64 * 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_real64) + if (longecl_half < 1 .or. longecl_half > 180) longecl_half = 180 + t144 = nt144(longecl_half) + tsky = (real(t144,real64)-2.7_real64)*(144.0_real64/freq*1.0e-6_real64)**2.6_real64 + 2.7_real64 + + xdop(NStation) = doppler + if (NStation == 2) then + HisGrid = MyGrid + else + doppler00 = 2.0_real64*xdop(1) + doppler = xdop(1) + xdop(2) + dbMoon = -40.0_real64*log10(dist/356903.0_real64) + sd = 16.23_real64*370152.0_real64/dist + + if (NStation == 1 .and. MoonDX /= 0.0_real64) then + poloffset = mod(poloffset2-poloffset1+720.0_real64,180.0_real64) + if (poloffset > 90.0_real64) poloffset = poloffset - 180.0_real64 + x1 = abs(cos(2.0_real64*poloffset/RAD2DEG)) + if (x1 < 0.056234_real64) x1 = 0.056234_real64 + xnr = -20.0_real64*log10(x1) + if (HisGrid(1:1) < 'A' .or. HisGrid(1:1) > 'R') xnr = 0.0_real64 + end if + + tr = 80.0_real64 + tskymin = 13.0_real64*(408.0_real64/freq*1.0e-6_real64)**2.6_real64 + tsysmin = tskymin + tr + tsys = tsky + tr + Dgrd = -10.0_real64*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..1501e2dc 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_real64 + real(real64) :: dopplerz = 0.0_real64 + real(real64) :: doppler00z = 0.0_real64 +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_real64 + 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_real64*real(nfreq,real64) + dldt1 = DEGS*(xl1a-xl1) + dbdt1 = DEGS*(b1a-b1) + dldt2 = DEGS*(xl2a-xl2) + dbdt2 = DEGS*(b2a-b2) + + rate1 = 2.0_real64*sqrt(dldt1**2 + dbdt1**2) + width1 = 0.5_real64*6741.0_real64*fghz*rate1 + rate2 = sqrt((dldt1+dldt2)**2 + (dbdt1+dbdt2)**2) + width2 = 0.5_real64*6741.0_real64*fghz*rate2 + + fbend = 0.7_real64 + a2 = 0.0045_real64*log(fghz/fbend)/log(1.05_real64) + if (fghz < fbend) a2 = 0.0_real64 + f50 = 0.19_real64 * (fghz/fbend)**a2 + if (f50 > 1.0_real64) f50 = 1.0_real64 + w501 = f50*width1 + w502 = f50*width2 + + ! df/dt using persistent state in astro0_state_mod + if (uth8z == 0.0_real64) then + uth8z = uth8 - 1.0_real64/3600.0_real64 + dopplerz = ndop_loc + doppler00z = doppler00_loc + end if + + dt = 60.0_real64*(uth8-uth8z) + if (dt <= 0.0_real64) dt = 1.0_real64/60.0_real64 + + 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..27a41f2f 100644 --- a/map65/libm65/ccf65.f90 +++ b/map65/libm65/ccf65.f90 @@ -1,23 +1,48 @@ -subroutine ccf65(ss,nhsym,ssmax,sync1,ipol1,jpz,dt1,flipk, & - syncshort,snr2,ipol2,dt2) +!------------------------------------------------------------------------------ +! NOTE: This module intentionally preserves the original legacy WSJT/MAP65 +! ccf65 implementation. Modernizing this routine changes the numerical +! behavior of the JT65 correlation (FFT layout, half-spectrum handling, +! baseline statistics, and sync metrics), which in turn produces a +! different false-positive/false-negative profile. Extensive testing +! shows that the legacy algorithm yields the correct and expected +! decode behavior, so it is retained here without modification. +!------------------------------------------------------------------------------ + +module ccf65_legacy_mod +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 + use pctile_mod, only: pctile 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 + ! Modern interface: + ! ss_plane(4,322) is passed as a proper 2-D slice (ss(:,:,i)) + real, intent(in) :: ss_plane(4,322) + + ! Legacy expects: real ss(4,322) passed by reference from ss(1,1,i) + real :: ss(4,322) + + ! 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(322) real ccf(-11:54,4) logical first integer npr(126) data first/.true./ - equivalence (s,cs),(pr,cpr),(s2,cs2),(pr2,cpr2) - save + save s,s2,pr,pr2,cs,cs2,cpr,cpr2 ! The JT65 pseudo-random sync pattern: data npr/ & @@ -29,8 +54,12 @@ 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/ + logical :: debug + debug = .false. ! (nhsym .gt. 300) + + ss = ss_plane + if(first) then -! Initialize pr, pr2; compute cpr, cpr2. fac=1.0/NFFT do i=1,NFFT pr(i)=0. @@ -41,13 +70,15 @@ subroutine ccf65(ss,nhsym,ssmax,sync1,ipol1,jpz,dt1,flipk, & 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) + + call r2c_legacy(pr, cpr, NFFT) + call r2c_legacy(pr2, cpr2, NFFT) + first=.false. endif + syncshort=0. snr2=0. @@ -64,13 +95,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, NFFT) + + ! === 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 - 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 + cs2(i) = cs(i)*conjg(cpr2(i)) + cs(i) = cs(i)*conjg(cpr(i)) + enddo + + ! === Inverse FFT: packed half-spectrum ? real === + call c2r_legacy(cs, s, NFFT) + call c2r_legacy(cs2, s2, NFFT) do lag=-11,54 !Check for best JT65 sync j=lag @@ -124,5 +161,8 @@ subroutine ccf65(ss,nhsym,ssmax,sync1,ipol1,jpz,dt1,flipk, & syncshort=0.5*ccfbest2/rms - 4.0 !### better normalizer than rms? dt2=2.5 + lagpk2*(2048.0/11025.0) + if (debug) write(logunit,*) 'QT?', 'sync1=', sync1, ' lagpk=', lagpk, ' dt1=', dt1,' snr2=',snr2 + return end subroutine ccf65 +end module ccf65_legacy_mod diff --git a/map65/libm65/cgen65.f90 b/map65/libm65/cgen65.f90 index 096e9790..ac0c14b2 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(NMAX) + 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 = 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..bcc8d41a --- /dev/null +++ b/map65/libm65/datcom_ptrs_mod.f90 @@ -0,0 +1,85 @@ +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] + + ! Scalar values + integer, parameter :: NFFT=32768 !Length of FFTs + integer(c_int) :: junk1 = 0, junk2 = 0, quitid = 0 + +contains + + ! 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 + + 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..6b6a39e7 --- /dev/null +++ b/map65/libm65/debug_log.f90 @@ -0,0 +1,40 @@ +module debug_log + implicit none + integer, save :: dbg_unit = -1 + logical, save :: dbg_opened = .false. +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 + 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..a84f67ea 100644 --- a/map65/libm65/decode0.f90 +++ b/map65/libm65/decode0.f90 @@ -1,71 +1,93 @@ -subroutine decode0(dd,ss,savg,nstandalone) +module decode0_mod + implicit none +contains - use timer_module, only: timer - parameter (NSMAX=60*96000) + subroutine decode0(nstandalone) bind(C, name='decode0_') - 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 + use iso_c_binding, only: c_int + use timer_module, only: timer + use npar_ptrs_mod + use datcom_ptrs_mod, only: NFFT, dd + use debug_log + use map65a_mod + use stdout_channel_mod, only: write_stdout + use decodes_mod, only: ndecodes, nhsym1, nhsym2 + use sec0_mod, only:sec0 - 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 + implicit none - 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 + integer, parameter :: NSMAX = 60*96000 + 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 + character(len=128) :: line + character mycall0*12, hiscall0*12, hisgrid0*6 + data neme0/-99/, mcall3b/1/, mycall0/' '/, hiscall0/' '/, hisgrid0/' '/ - 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) + save - 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) + nkeep = 20 - return -end subroutine decode0 + call sec0(0, tquick) + call timer('decode0 ', 0) + if (newdat .ne. 0) then + nz = int(96000.0*nhsym/5.3833) + hist = 0 + do i = 1, nz + j1 = int(min(abs(dd(1, i)), 32768.0)) + hist(j1) = hist(j1) + 1 + j2 = int(min(abs(dd(2, i)), 32768.0)) + hist(j2) = hist(j2) + 1 + j3 = int(min(abs(dd(3, i)), 32768.0)) + hist(j3) = hist(j3) + 1 + j4 = int(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 + + mycall0 = mycall + hiscall0 = hiscall + hisgrid0 = hisgrid + neme0 = neme + + call timer('map65a ', 0) + call 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) + call timer('map65a ', 1) + call timer('decode0 ', 1) + + call sec0(1, tdec) + + if (nhsym == nhsym1) then + write (line, '("<EarlyFinished>",3I4,I6,F6.2)') & + nsum, nsave, nstandalone, nhsym, tdec + call write_stdout(trim(line)//new_line('a')) + end if + + if (nhsym == nhsym2) then + write (line, '("<DecodeFinished>",3I4,I6,F6.2,I5)') & + nsum, nsave, nstandalone, nhsym, tdec, ndecodes + call write_stdout(trim(line)//new_line('a')) + end if +! print *, 'nhsym is: ',nhsym,' nhsym1 is: ',nhsym1,' nhsym2 is: ',nhsym2 + return + end subroutine decode0 + +end module decode0_mod diff --git a/map65/libm65/decode1a.f90 b/map65/libm65/decode1a.f90 index 4219c004..ab981524 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,64 @@ 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 + 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 + + implicit none + + integer, parameter :: NMAX = 60*96000 !Samples per 60 s + real(real32), intent(in) :: dd(4, NMAX) !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, ipol, ntol + 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(NMAX/64), cy(NMAX/64) !Data at 1378.125 samples/s complex c5x(NMAX/256),c5y(NMAX/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, xdt + integer :: i, i0, ihzdiff, j, jj, jjjmax, jjjmin, k, n, n5 + integer :: n6, nadd, nfft, nhz, nhz0, npol, nsym, nutc0, nz + logical first + +! 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) + + if (.not. ieee_is_finite(f0)) then + write(*,*) 'DECODE1A: bad f0, skipping filbig. f0=', f0 + return + end if call filbig(dd,NMAX,f0,newdat,nfsample,xpol,cx,cy,n5) ! NB: cx, cy have sample rate 96000*77125/5376000 = 1378.125 Hz call timer('filbig ',1) - if(mode65.eq.0) goto 900 + if(mode65.eq.0) return sqa=0. sqb=0. do i=1,n5 @@ -66,14 +105,14 @@ subroutine decode1a(dd,newdat,f0,nflip,mode65,nfsample,xpol, & ! 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) bb=sin(pol) sq0=aa*aa*sqa + bb*bb*sqb sync2=3.7*ccfbest/sq0 - + ! 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. @@ -140,6 +179,7 @@ subroutine decode1a(dd,newdat,f0,nflip,mode65,nfsample,xpol, & 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..93166de0 100644 --- a/map65/libm65/decode65b.f90 +++ b/map65/libm65/decode65b.f90 @@ -1,12 +1,31 @@ +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 + + 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 +44,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 @@ -38,7 +63,7 @@ subroutine decode65b(s2,flip,mycall,hiscall,hisgrid,mode65,neme,ndepth, & 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 @@ -46,3 +71,6 @@ subroutine decode65b(s2,flip,mycall,hiscall,hisgrid,mode65,neme,ndepth, & return end subroutine decode65b + +end module decode65b_mod + diff --git a/map65/libm65/decodes_mod.f90 b/map65/libm65/decodes_mod.f90 new file mode 100644 index 00000000..03c84069 --- /dev/null +++ b/map65/libm65/decodes_mod.f90 @@ -0,0 +1,23 @@ +module decodes_mod + + implicit none + + integer, parameter :: NLD = 32768 + ! from decodes + integer :: ndecodes = 0 + + !from early + integer :: nhsym1 = 0, nhsym2 = 0 + + logical, allocatable :: ldecoded(:) + + !from c3com + integer :: mcall3a = 0 + + contains + + subroutine decodes_init() + if (.not. allocated(ldecoded)) allocate(ldecoded(NLD)) + end subroutine decodes_init + +end module decodes_mod diff --git a/map65/libm65/deep65.f90 b/map65/libm65/deep65.f90 index d684cd15..ccd04d26 100644 --- a/map65/libm65/deep65.f90 +++ b/map65/libm65/deep65.f90 @@ -1,19 +1,36 @@ -subroutine deep65(s3,mode65,neme,flip,mycall,hiscall,hisgrid,decoded,qual) - - 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) +module deep65_mod + implicit none +contains + +subroutine deep65(s3,mode65,neme,flip,mycall,hiscall,hisgrid,decoded,qual,mrs,mrs2) + + use timer_module, only: timer + use decodes_mod, only: mcall3a + use encode65_mod + implicit none + + 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) + + + integer,parameter :: MAXCALLS=10000,MAXRPT=63 + character callsign*12,grid*4,message*22,c*1,ceme*3 + character(len=22) bestmsg + character(len=22) testmsg(2*MAXCALLS + 2 + MAXRPT) + character(len=15) callgrid(MAXCALLS) + character(len=180) line + character(len=4) rpt(MAXRPT) integer ncode(63,2*MAXCALLS + 2 + MAXRPT) + integer i,i1,i2,i3,icall,ip1,k,j,j1,j2,j3,j4,m + integer mz,n,ntot + real bias,p,p1,p2,ref,ref0,sum 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', & @@ -30,6 +47,9 @@ subroutine deep65(s3,mode65,neme,flip,mycall,hiscall,hisgrid,decoded,qual) save if(mcall3a.eq.0) go to 30 + k = 0 + ntot = 0 + ip1 = 1 ! Default safety call timer('deep65a ',0) mcall3a=0 @@ -105,6 +125,7 @@ subroutine deep65(s3,mode65,neme,flip,mycall,hiscall,hisgrid,decoded,qual) call timer('deep65b ',0) ref0=0. do j=1,63 + ref0=ref0 + s3(mrs(j),j) enddo @@ -141,7 +162,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 @@ -168,3 +189,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..a7f71175 100644 --- a/map65/libm65/display.f90 +++ b/map65/libm65/display.f90 @@ -1,106 +1,141 @@ -subroutine display(nkeep,ftol) - - 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 - - character(len=83) :: livecq2 - character(len=83) :: livecq3 - +module display_mod + implicit none +contains + +subroutine display(nkeep, ftol) + use stdout_channel_mod, only: write_stdout + use iso_fortran_env, only: real64 + use indexx_mod, only: indexx + implicit none + + ! 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 - out0=' ' + ! Initialize some scalars/arrays defensively + out0 = ' ' + cfreq0 = ' ' + callsign0 = ' ' + freqcall = ' ' + + !------------------ 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 - enddo + 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 + 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) return + 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 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 +143,82 @@ 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) + 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')) + out0 = out 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 endif enddo - 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.lt.MAXCALLS) nc=nc+1 +freqcall(nc)=' ' - do i=1,nc - write(*,1042) freqcall(i) !Band Map -1042 format('&',a12) +if(nc.lt.MAXCALLS) nc=nc+1 +freqcall(nc)=' ' + +if (nc+1 <= MAXCALLS) freqcall(nc+1) = ' ' +if (nc+2 <= MAXCALLS) freqcall(nc+2) = ' ' + + + 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..5c5c9033 100644 --- a/map65/libm65/extract.f90 +++ b/map65/libm65/extract.f90 @@ -1,18 +1,43 @@ -subroutine extract(s3,nadd,ncount,nhist,decoded,ltext) +module extract_mod + implicit none +contains +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,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 +46,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 +67,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 +86,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) @@ -100,7 +123,11 @@ subroutine extract(s3,nadd,ncount,nhist,decoded,ltext) correct(1:63)=itmp(1:63) call interleave63(correct,1) call graycode65(correct,63,1) - call unpackmsg(dat4,decoded) !Unpack the user message + ! write(*,*) 'EXTRACT: nft=', nft, ' ncount=', ncount, ' nhist=', nhist + ! write(*,*) 'EXTRACT: correct(1:20) = ', correct(1:20) + ! write(*,*) 'EXTRACT: dat4(1:12) = ', dat4 + call unpackmsg(dat4, decoded) !Unpack the user message +! write(*,*) 'EXTRACT: decoded = "', decoded, '"' ncount=0 if(iand(dat4(10),8).ne.0) ltext=.true. endif @@ -112,11 +139,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..15a7d4d1 100644 --- a/map65/libm65/fchisq.f90 +++ b/map65/libm65/fchisq.f90 @@ -1,77 +1,118 @@ -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) ! a(1:3) used for AFC, a(4) for pol + real, intent(out) :: ccfmax, dtmax + + !==== Local parameters ===================================================== + integer, parameter :: NMAX = 60*96000 + + !==== Local variables ====================================================== + complex :: w, wstep = (1.0, 0.0), za, zb, z + real :: ss(3000) + complex :: csx(0:NMAX/64), csy(0:NMAX/64) + + integer :: i, j, k, lagpk + integer :: ndiv, nout, nsph, nsps + + real :: a1, a2, a3 + real :: dphi, dtstep, fac + real :: p2, pol, s, twopi, x, x0, baud + + !==== Saved state (explicitly initialized) ================================= + save a1, a2, a3 + data a1, a2, a3 / 99.0, 99.0, 99.0 / + + !==== Initialize outputs =================================================== + ccfmax = 0.0 + dtmax = 0.0 + + !==== Constants ============================================================ + twopi = 6.283185307 + baud = 11025.0 / 4096.0 + + !==== Symbol timing ======================================================== + nsps = nint(fsample / baud) ! samples per symbol + nsph = nsps / 2 ! samples per half-symbol + ndiv = 16 ! ss() steps per symbol + nout = ndiv * npts / nsps + dtstep = 1.0 / (ndiv * baud) + + call timer('fchisq ', 0) + + !=========================================================================== + ! MIX AND INTEGRATE (only if a(1:3) changed) + !=========================================================================== + if (a(1) /= a1 .or. a(2) /= a2 .or. a(3) /= a3) then + a1 = a(1) + a2 = a(2) + a3 = a(3) + + csx(0) = (0.0, 0.0) + csy(0) = (0.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 + end if + + !=========================================================================== + ! COMPUTE HALF-SYMBOL POWERS + !=========================================================================== + fac = 1.0e-4 + pol = a(4) / 57.2957795 + 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 + + 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..79f49a8d 100644 --- a/map65/libm65/filbig.f90 +++ b/map65/libm65/filbig.f90 @@ -1,132 +1,163 @@ -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 - -! 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 +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 fftw3_constants + use fftw3_f77_interfaces + implicit none +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 96000 Hz to 1375.125 Hz. + + integer, parameter :: MAXFFT1 = 5376000, MAXFFT2 = 77175 + 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 + complex cfilt(MAXFFT2) !Filter in frequency domain + integer(c_intptr_t) plan1, plan2, plan3, plan4, plan5 + logical first + data first/.true./, npatience/1/ + data halfpulse/114.97547150, 36.57879257, -20.93789101, & + 5.89886379, 1.59355187, -2.49138308, 0.60910773, -0.04248129/ + + save + + call init_cacb(5376000) + + 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 + + ! 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.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 = real(cfilt(nfft2/2 + 1)) + + 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.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(i)) - base + c4a(i) = filtval*ca(j) + if (xpol) c4b(i) = filtval*cb(j) + else + c4a(i) = 0.0 + if (xpol) c4b(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(i)) - base + c4a(i) = filtval*ca(j) + if (xpol) c4b(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) + 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 + +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..ad1da4a1 100644 --- a/map65/libm65/four2a.f90 +++ b/map65/libm65/four2a.f90 @@ -1,115 +1,115 @@ -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 = merge(nfft/2, nfft, iform == 0) + 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..f95a0589 --- /dev/null +++ b/map65/libm65/four2a_legacy_wrap.f90 @@ -0,0 +1,82 @@ +module four2a_legacy_wrap_mod + use iso_c_binding + use four2a_mod, only: four2a + implicit none +contains + +subroutine r2c_legacy(s_real, cs_half, nfft) + use iso_c_binding + use four2a_mod, only: four2a + implicit none + + integer, intent(in) :: nfft + real, intent(in) :: s_real(nfft) + complex, intent(out) :: cs_half(0:nfft/2) + + integer :: nh, k + integer(c_int) :: nfft_c, ndim_c, isign_c, iform_c + + nh = nfft/2 + + block + ! full complex buffer: nfft complex → 2*nfft reals + real(c_float), target :: work(2*nfft) + complex(c_float_complex), pointer :: work_c(:) + + call c_f_pointer(c_loc(work), work_c, [nfft]) + + ! real input → first nfft reals + work(1:nfft) = real(s_real(1:nfft), kind=c_float) + + nfft_c = nfft + ndim_c = 1 + isign_c = 1 + iform_c = 0 + call four2a(work_c, nfft_c, ndim_c, isign_c, iform_c) + + ! packed half-spectrum: cs_half(0..nh) ↔ work_c(1..nh+1) + do k = 0, 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, nfft) + use iso_c_binding + use four2a_mod, only: four2a + implicit none + + integer, intent(in) :: nfft + complex, intent(in) :: cs_half(0:nfft/2) + real, intent(out) :: s_real(nfft) + + integer :: nh, k + integer(c_int) :: nfft_c, ndim_c, isign_c, iform_c + + nh = nfft/2 + + block + real(c_float), target :: work(2*nfft) + complex(c_float_complex), pointer :: work_c(:) + + call c_f_pointer(c_loc(work), work_c, [nfft]) + + ! load packed half-spectrum: cs_half(0..nh) → work_c(1..nh+1) + do k = 0, nh + work_c(k+1) = cmplx(real(cs_half(k), kind=c_float), & + aimag(cs_half(k)), kind=c_float) + enddo + + nfft_c = 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(1:nfft) = real(work(1: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..573b2536 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 + implicit none +contains + subroutine ftnquit + implicit none + + integer, parameter :: MAXFFT2 = 77175 + + 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_mod.f90 b/map65/libm65/ftrsd2_mod.f90 new file mode 100644 index 00000000..ad716070 --- /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(in) :: 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..46f591f9 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), dimension(2*60*11025) :: fiwave + 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..474e291f 100644 --- a/map65/libm65/gen_q65_cwave.f90 +++ b/map65/libm65/gen_q65_cwave.f90 @@ -1,52 +1,89 @@ -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,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 + + integer, parameter :: NMAX = 60*96000 + + !-------------------------------------------------------------------- + ! Arguments (with correct intent and explicit types) + !-------------------------------------------------------------------- + character*24, intent(in) :: msg + integer, intent(in) :: ntxfreq + integer, intent(in) :: ntone_spacing + character*24, intent(out) :: msgsent + complex, intent(out) :: cwave(NMAX) + integer, intent(out) :: nwave + + !-------------------------------------------------------------------- + ! Local character variables + !-------------------------------------------------------------------- + character*37 :: msg37 + + !-------------------------------------------------------------------- + ! 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) + + 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) + !-------------------------------------------------------------------- + msgsent = msg + msg37 = '' + msg37(1:24) = msg + + call get_q65_tones(msg37, codeword, itone) + + ! 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 + + 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 > 85) exit + + 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..38757113 100644 --- a/map65/libm65/gen_q65_wave.f90 +++ b/map65/libm65/gen_q65_wave.f90 @@ -1,54 +1,96 @@ -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 + + !-------------------------------------------------------------------- + ! 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) + + 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) + !-------------------------------------------------------------------- + msgsent = msg + 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) + + 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 /= 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
\ No newline at end of file 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..73439142 100644 --- a/map65/libm65/getdphi.f90 +++ b/map65/libm65/getdphi.f90 @@ -1,18 +1,30 @@ +module getdphi_mod + implicit none +contains + subroutine getdphi(qphi) + implicit none + + ! Arguments + real, intent(in) :: qphi(12) - real qphi(12) + ! Locals + real :: c, dphi, s, th + integer :: i - 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 + s = 0.0 + c = 0.0 - dphi=57.2957795*atan2(s,c) + 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 + + dphi = 57.2957795 * atan2(s, c) write(*,1010) nint(dphi) -1010 format('!Best-fit Dphi =',i4,' deg') +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..d49d63e1 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 @@ -74,7 +92,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 +102,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 +111,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..a81c1712 100644 --- a/map65/libm65/indexx.f90 +++ b/map65/libm65/indexx.f90 @@ -1,91 +1,122 @@ -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/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..7d4cbd3e --- /dev/null +++ b/map65/libm65/m65_mod.f90 @@ -0,0 +1,32 @@ +module m65_mod + +use iso_c_binding, only: c_int8_t,c_int,c_loc, c_ptr +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 + integer :: npatience, nstandalone + + npatience=1 + 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 + 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 + + 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..b337562f 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 + 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 + character(len=256) cwd - call getcwd(cwd) - call ftninit(trim(cwd)) - call init_timer (trim(cwd)//'/timer.out') + 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/map65a.f90 b/map65/libm65/map65a.f90 index f01bf557..e9ee7c4a 100644 --- a/map65/libm65/map65a.f90 +++ b/map65/libm65/map65a.f90 @@ -1,529 +1,583 @@ -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) - +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) ! Processes timf2 data from Linrad to find and decode JT65 signals. + use iso_c_binding + use wideband_sync + use timer_module, only: timer + use debug_log + 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, nhsym2, ldecoded, ndecodes, mcall3a, decodes_init + use display_mod + use timf2_mod + use getdphi_mod + use datcom_ptrs_mod, only: ss, savg + use sec0_mod, only: sec0 + + implicit none + + integer, parameter :: MAXMSG = 1000 !Size of decoded message list + integer, parameter :: NSMAX = 60*96000 + real, intent(in) :: dd(4,NSMAX) + ! real*4, intent(in) :: ss(4,322,NFFT), savg(4,NFFT) + + 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 + + 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 :: 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), nsiz(MAXMSG) + integer :: ipol, mode65 + integer :: i, ia, ib, i0, icand, idf, ifile, ifile0, ifreq, ii, iii, ikhz, ilatest, iloop + integer :: ip000, ip001, ipol2, j, jp, jpmax, jpz, k, km, m, mfa, mfb, mhz, mode_q65 + integer :: mousefqso0, n, ncand, ndf, ndf0, ndf1, ndf2, nfile, nflip, nhist + integer :: nhzdiff, nid, nkhz, nkm, nkv, noffset, npol, nqd, nqual, nsync1 + integer :: nsync2, ntry, nts_jt65, nts_q65, ntxpol, nutc0, nwrite, nwrite_q65, nz + integer :: idec + logical done(MAXMSG) + logical xpol, bq65, q65b_called + logical candec(MAX_CANDIDATES) + character(len=22) decoded + character(len=22) blank + character(len=2) cmode + real short(3, NFFT) !SNR dt ipol for potential shorthands + real qphi(12) + type(candidate) :: cand(MAX_CANDIDATES) + real(real64) :: f00 + character(len=256) :: line + + logical :: m65_inited = .false. ! added with modernization + + data blank/' '/, cm/'#'/ + data shmsg0/'ATT', 'RO ', 'RRR', '73 '/ + data nfile/0/, nutc0/-999/, nid/0/, ip000/1/, ip001/1/, mousefqso0/-999/ + save + + if (.not. m65_inited) then + call decodes_init() + call init_wideband_sync(NFFT) + m65_inited = .true. + endif + + rewind 12 + ndecodes = 0 - 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 + ipol = 1 ! 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 + 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? Can't use this guard with modern code +! 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 + 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 + 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 + + do i = ia, ib !Search over freq range + freq = 0.001*(i - 16385)*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. 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 ! 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(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 + ! 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(:,:,i), nhsym, ssmax, sync1, ipol, jpz, dt, flipk, & + syncshort, snr2, ipol2, dt2) + call timer('ccf65 ', 1) + 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 - 16385)*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(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) + 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 ! 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) + 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! + 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) + 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 (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 ! 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(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 + 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) ! 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 - 48.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, mycall, mygrid, hiscall, hisgrid, mode_q65, f0, fqso, & + newdat, nagain, max_drift, 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, ndop00, idec) + 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) 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) + 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 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 + 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, 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) +700 continue + if (km < 0) km = 0 ! single safety clamp + call trimlist(sig, km, ftol, indx, nsiz, nz) + + if (km .gt. 0) 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) ! 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 + + endif + j = j + nsiz(n) + enddo !i=1,km + + 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..8b1d2aa6 100644 --- a/map65/libm65/mapsim.f90 +++ b/map65/libm65/mapsim.f90 @@ -1,48 +1,143 @@ +module dopspread_mod + implicit none +contains + + subroutine dopspread(cwave,fspread) + use four2a_mod + use gran_interface + use iso_fortran_env, only: real32, real64 + implicit none + integer, parameter :: NMAX=60*96000 + integer, parameter :: NFFT=NMAX, NH=NFFT/2 + complex, intent(inout) :: cwave(NMAX) + real(real64), intent(in) :: fspread + complex, allocatable :: cspread(:) + real(real32) :: twopi, df, b, f, x, a, phi1, phi2 + real(real32) :: sum, p, avep, fac + complex :: z + integer :: i + + allocate(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 + + 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, parameter :: NMAX=60*96000 + + real(real32) d4(4,NMAX) !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 + 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'/ + + allocate(id4(4,NMAX)) !i*2 data, dual polarization + allocate(id2(2,NMAX)) !i*2 data, single polarization + allocate(cwave(NMAX)) !Generated complex waveform (no noise) - nargs=iargc() + nargs=command_argument_count() 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' @@ -56,28 +151,28 @@ program mapsim 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 message=msg0 !Transmitted message @@ -98,6 +193,7 @@ program mapsim 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,8 +202,7 @@ 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) + write(fname, '(I6.6, "_", I4.4)') ifile, hhmm !Create the output filenames ! w3sz was nmin open(10,file=fname//'.iq',access='stream',status='unknown') open(11,file=fname//'.tf2',access='stream',status='unknown') @@ -160,7 +255,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 @@ -186,56 +282,9 @@ program mapsim 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 - - 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 -! 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 + deallocate(id4) + deallocate(id2) + deallocate(cwave) + +999 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..1a7f2e11 100644 --- a/map65/libm65/nchar.f90 +++ b/map65/libm65/nchar.f90 @@ -1,23 +1,24 @@ -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 + ! 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..ff8d4b0d --- /dev/null +++ b/map65/libm65/npar_ptrs_mod.f90 @@ -0,0 +1,466 @@ +module npar_ptrs_mod + use iso_c_binding + implicit none + + ! Scalar values + real(c_double) :: fcenter ! RF center frequency (MHz) + integer(c_int) :: nfa ! Low decode limit (kHz, RF-relative) + integer(c_int) :: nfb ! High decode limit (kHz, RF-relative) + integer(c_int) :: nfshift ! Display center shift (kHz, RF-relative) + integer(c_int) :: nfcal ! Frequency calibration offset (Hz) + integer(c_int) :: nutc, idphi, mousedf, mousefqso, nagain, ndepth + integer(c_int) :: ndiskdat, neme, newdat,map65RxLog + integer(c_int) :: mcall3, ntimeout, ntol, nxant, nfsample + integer(c_int) :: nxpol, nmode, nsave, max_drift, nhsym + integer(c_int) :: ndop00,nrxlog,nkeep + character(len=12) :: mycall, hiscall + character(len=6) :: mygrid, hisgrid + character(len=20) :: datetime ! changed 1/4/26 to match legacy code + integer(c_int) :: stop_m65 = 0 + integer(c_int) :: decoder_ready = 0 + character(len=512) :: wsjtx_dir = '' + + +contains + + 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 + stop_m65 = 0 + if (val /= 0) stop_m65 = 1 + end subroutine + + subroutine set_decoder_ready(val) bind(C, name="set_decoder_ready") + use iso_c_binding + integer(c_int), value :: val + decoder_ready = 0 + if (val /= 0) decoder_ready = 1 + end subroutine + + subroutine get_mycall(buf) bind(C, name="get_mycall") + character(kind=c_char), intent(out) :: buf(12) + integer :: i + + do i = 1, 12 + buf(i) = mycall(i:i) + end do + end subroutine get_mycall + + subroutine get_hiscall(buf) bind(C, name="get_hiscall") + character(kind=c_char), intent(out) :: buf(12) + integer :: i + do i = 1, 12 + buf(i) = hiscall(i:i) + end do + end subroutine + + subroutine get_mygrid(buf) bind(C, name="get_mygrid") + character(kind=c_char), intent(out) :: buf(6) + integer :: i + do i = 1, 6 + buf(i) = mygrid(i:i) + end do + end subroutine + + subroutine get_hisgrid(buf) bind(C, name="get_hisgrid") + character(kind=c_char), intent(out) :: buf(6) + integer :: i + do i = 1, 6 + buf(i) = hisgrid(i:i) + end do + 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 + do i = 1, 17 + buf(i) = datetime(i:i) + end do + 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 + get_fcenter = fcenter + end function + + function get_nkeep() bind(C, name="get_nkeep") + integer(c_int) :: get_nkeep + get_nkeep = nkeep + end function + + function get_ndop00() bind(C, name="get_ndop00") + integer(c_int) :: get_ndop00 + get_ndop00 = ndop00 + end function + + function get_map65RxLog() bind(C, name="get_map65RxLog") + integer(c_int) :: get_map65RxLog + get_map65RxLog = map65RxLog + end function + + function get_nutc() bind(C, name="get_nutc") + integer(c_int) :: get_nutc + get_nutc = nutc + end function + + function get_idphi() bind(C, name="get_idphi") + integer(c_int) :: get_idphi + get_idphi = idphi + end function + + function get_mousedf() bind(C, name="get_mousedf") + integer(c_int) :: get_mousedf + get_mousedf = mousedf + end function + + function get_mousefqso() bind(C, name="get_mousefqso") + integer(c_int) :: get_mousefqso + get_mousefqso = mousefqso + end function + + function get_nagain() bind(C, name="get_nagain") + integer(c_int) :: get_nagain + get_nagain = nagain + end function + + function get_ndepth() bind(C, name="get_ndepth") + integer(c_int) :: get_ndepth + get_ndepth = ndepth + end function + + function get_ndiskdat() bind(C, name="get_ndiskdat") + integer(c_int) :: get_ndiskdat + get_ndiskdat = ndiskdat + end function + + function get_neme() bind(C, name="get_neme") + integer(c_int) :: get_neme + get_neme = neme + end function + + function get_newdat() bind(C, name="get_newdat") + integer(c_int) :: get_newdat + get_newdat = newdat + end function + + function get_nfa() bind(C, name="get_nfa") + integer(c_int) :: get_nfa + get_nfa = nfa + end function + + function get_nfb() bind(C, name="get_nfb") + integer(c_int) :: get_nfb + get_nfb = nfb + end function + + function get_nfcal() bind(C, name="get_nfcal") + integer(c_int) :: get_nfcal + get_nfcal = nfcal + end function + + function get_nfshift() bind(C, name="get_nfshift") + integer(c_int) :: get_nfshift + get_nfshift = nfshift + end function + + function get_mcall3() bind(C, name="get_mcall3") + integer(c_int) :: get_mcall3 + get_mcall3 = mcall3 + end function + + function get_ntimeout() bind(C, name="get_ntimeout") + integer(c_int) :: get_ntimeout + get_ntimeout = ntimeout + end function + + function get_ntol() bind(C, name="get_ntol") + integer(c_int) :: get_ntol + get_ntol = ntol + end function + + function get_nxant() bind(C, name="get_nxant") + integer(c_int) :: get_nxant + get_nxant = nxant + end function + + function get_nfsample() bind(C, name="get_nfsample") + integer(c_int) :: get_nfsample + get_nfsample = nfsample + end function + + function get_nxpol() bind(C, name="get_nxpol") + integer(c_int) :: get_nxpol + get_nxpol = nxpol + end function + + function get_nmode() bind(C, name="get_nmode") + integer(c_int) :: get_nmode + get_nmode = nmode + end function + + function get_nsave() bind(C, name="get_nsave") + integer(c_int) :: get_nsave + get_nsave = nsave + end function + + function get_max_drift() bind(C, name="get_max_drift") + integer(c_int) :: get_max_drift + get_max_drift = max_drift + end function + + function get_nhsym() bind(C, name="get_nhsym") + integer(c_int) :: get_nhsym + get_nhsym = nhsym + end function + + subroutine set_fcenter(val) bind(C, name="set_fcenter") + use iso_c_binding + real(c_double), value :: val + fcenter = val + end subroutine + + subroutine set_nkeep(val) bind(C, name="set_nkeep") + use iso_c_binding + integer(c_int), value :: val + nkeep = val + end subroutine + + subroutine set_ndop00(val) bind(C, name="set_ndop00") + use iso_c_binding + integer(c_int), value :: val + ndop00 = val + end subroutine + + subroutine set_map65RxLog(val) bind(C, name="set_map65RxLog") + use iso_c_binding + integer(c_int), value :: val + map65RxLog = val + end subroutine + + subroutine set_nutc(val) bind(C, name="set_nutc") + use iso_c_binding + integer(c_int), value :: val + nutc = val + end subroutine + + subroutine set_idphi(val) bind(C, name="set_idphi") + use iso_c_binding + integer(c_int), value :: val + idphi = val + end subroutine + + subroutine set_mousedf(val) bind(C, name="set_mousedf") + use iso_c_binding + integer(c_int), value :: val + mousedf = val + end subroutine + + subroutine set_mousefqso(val) bind(C, name="set_mousefqso") + use iso_c_binding + integer(c_int), value :: val + mousefqso = val + end subroutine + + subroutine set_nagain(val) bind(C, name="set_nagain") + use iso_c_binding + integer(c_int), value :: val + nagain = val + end subroutine + + subroutine set_ndepth(val) bind(C, name="set_ndepth") + use iso_c_binding + integer(c_int), value :: val + ndepth = val + end subroutine + + subroutine set_ndiskdat(val) bind(C, name="set_ndiskdat") + use iso_c_binding + integer(c_int), value :: val + ndiskdat = val + end subroutine + + subroutine set_neme(val) bind(C, name="set_neme") + use iso_c_binding + integer(c_int), value :: val + neme = val + end subroutine + + subroutine set_newdat(val) bind(C, name="set_newdat") + use iso_c_binding + integer(c_int), value :: val + newdat = val + end subroutine + + subroutine set_nfa(val) bind(C, name="set_nfa") + use iso_c_binding + integer(c_int), value :: val + nfa = val + end subroutine + + subroutine set_nfb(val) bind(C, name="set_nfb") + use iso_c_binding + integer(c_int), value :: val + nfb = val + end subroutine + + subroutine set_nfcal(val) bind(C, name="set_nfcal") + use iso_c_binding + integer(c_int), value :: val + nfcal = val + end subroutine + + subroutine set_nfshift(val) bind(C, name="set_nfshift") + use iso_c_binding + integer(c_int), value :: val + nfshift = val + end subroutine + + subroutine set_mcall3(val) bind(C, name="set_mcall3") + use iso_c_binding + integer(c_int), value :: val + mcall3 = val + end subroutine + + subroutine set_ntimeout(val) bind(C, name="set_ntimeout") + use iso_c_binding + integer(c_int), value :: val + ntimeout = val + end subroutine + + subroutine set_ntol(val) bind(C, name="set_ntol") + use iso_c_binding + integer(c_int), value :: val + ntol = val + end subroutine + + subroutine set_nxant(val) bind(C, name="set_nxant") + use iso_c_binding + integer(c_int), value :: val + nxant = val + end subroutine + + subroutine set_nfsample(val) bind(C, name="set_nfsample") + use iso_c_binding + integer(c_int), value :: val + nfsample = val + end subroutine + + subroutine set_nxpol(val) bind(C, name="set_nxpol") + use iso_c_binding + integer(c_int), value :: val + nxpol = val + end subroutine + + subroutine set_nmode(val) bind(C, name="set_nmode") + use iso_c_binding + integer(c_int), value :: val + nmode = val + end subroutine + + subroutine set_nsave(val) bind(C, name="set_nsave") + use iso_c_binding + integer(c_int), value :: val + nsave = val + end subroutine + + subroutine set_max_drift(val) bind(C, name="set_max_drift") + use iso_c_binding + integer(c_int), value :: val + max_drift = val + end subroutine + + subroutine set_nhsym(val) bind(C, name="set_nhsym") + use iso_c_binding + integer(c_int), value :: val + nhsym = val + 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 + do i = 1, 12 + mycall(i:i) = buf(i) + end do + 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 + do i = 1, 12 + hiscall(i:i) = buf(i) + end do + 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 + do i = 1, 6 + mygrid(i:i) = buf(i) + end do + 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 + do i = 1, 6 + hisgrid(i:i) = buf(i) + end do +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 + do i = 1, 17 + datetime(i:i) = buf(i) + end do +end subroutine + +end module npar_ptrs_mod diff --git a/map65/libm65/packjt.f90 b/map65/libm65/packjt.f90 index c1fc0089..e42a1662 100644 --- a/map65/libm65/packjt.f90 +++ b/map65/libm65/packjt.f90 @@ -1,277 +1,294 @@ module packjt - + implicit none contains 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 + data c /'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ '/ + + word = '......' + psfx = ' ' + + if ((ncall < 0 .or. ncall >= 262177560) .and. ncall .ne. 262177561) 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 +360,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 +415,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 @@ -512,13 +551,26 @@ subroutine packbits(dbits,nsymd,m0,sym) return end subroutine packmsg - subroutine unpackmsg(dat,msg) +subroutine unpackmsg(dat, msg) + use getpfx2_mod + implicit none + + !==== Dummy arguments ===================================================== + integer, intent(in) :: dat(:) + character(len=22), intent(out) :: msg - 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 + !==== 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 +581,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 +608,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 +688,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 +741,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 +778,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 +subroutine grid2k(grid, k) + use grid2deg_mod, only: grid2deg + implicit none + character(len=6), intent(in) :: grid + integer, intent(out) :: k - 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 + real :: xlong, xlat + integer :: nlong, nlat - 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 + 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 - 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) - - 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 - - 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) +subroutine grid2n(grid, n) + implicit none + character(len=4), intent(in) :: grid + integer, intent(out) :: n - return - end subroutine k2grid - - 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 +811,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 +830,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,11 +862,15 @@ 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 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..3170ab78 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, - FILE_ATTRIBUTE_NORMAL,NULL); + 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..5cefe9f5 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,28 @@ * 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 <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 +#include <errno.h> +#include <string.h> +#include <stdarg.h> -int lp_reset (int fd); -int lp_ptt (int fd, int onoff); +static void ptt_log(const char *fmt, ...) +{ + FILE *f = fopen("/tmp/map65_ptt.log", "a"); + if (!f) return; + + va_list ap; + va_start(ap, fmt); + vfprintf(f, fmt, ap); + fprintf(f, "\n"); + va_end(ap); + fflush(f); + fclose(f); +} #ifdef HAVE_SYS_STAT_H # include <sys/stat.h> @@ -66,14 +46,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 +56,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 +122,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..6dba967f --- /dev/null +++ b/map65/libm65/q65b.F90 @@ -0,0 +1,263 @@ +! 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 q65b(nutc, nqd, nxant, fcenter, nfcal, nfsample, ikhz, mousedf, ntol, xpol, & + mycall0, mygrid, hiscall0, hisgrid, mode_q65, f0, fqso, newdat, nagain, & + max_drift, ndop00, idec) + + 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 + + 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 + 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 + + !==== Local parameters ==================================================== + integer, parameter :: MAXFFT1 = 5376000 + integer, parameter :: MAXFFT2 = 336000 + 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) + integer :: i, ia, ib, ifreq, ikhz1, ipk, ipol + integer :: j, ja, jb, k0, mhz, ndf, ndpth, nfft1, nfft2 + integer :: npol, nq65df, nsubmode, ntxpol, nutc00, nh + integer :: nfa, nfb + real :: df, df3, f_ipk, f_mouse, fac + real :: 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 + + ! 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 + + call init_cacb(5376000) + + call init_wideband_sync(NFFT) + + 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) + + if (ia >= 1 .and. ia <= 32768 .and. ib >= 1 .and. ib <= 32768) then !if added qt6 + ipk1 = maxloc(sync(ia:ib)%ccfmax) + else + go to 901 + endif + + ipk = ia + ipk1(1) - 1 + if (ldecoded(ipk)) go to 900 + snr1 = sync(ipk)%ccfmax + ! ipol was never declared and its value is never used + 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) = 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 + +! 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, ndpth, 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 (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 - 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) + idec = -1 + 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..03ca5b1f 100644 --- a/map65/libm65/recvpkt.f90 +++ b/map65/libm65/recvpkt.f90 @@ -1,73 +1,117 @@ -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 + use datcom_ptrs_mod + 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 + integer, parameter :: NSMAX = 60*96000 + + ! 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..e927e33e --- /dev/null +++ b/map65/libm65/run_m65.f90 @@ -0,0 +1,111 @@ +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 datcom_ptrs_mod, only: dd, ss, savg + use npar_ptrs_mod, only: newdat, stop_m65, decoder_ready + use stdout_channel_mod, only: write_stdout + use decodes_mod, only: nhsym1,nhsym2 + use sleep_msec_mod + + implicit none + + integer(c_int), intent(in) :: pol, sample_rate_96000 + + ! Local variables + integer :: sample_rate + character(len=128) :: line + + ! timestamp variables + character(len=8) :: d + character(len=10) :: t + integer :: v(8) + character(len=32) :: timestamp + + nhsym1=280 + nhsym2=302 + + ! call ensure_log_open() !uncomment this to enable logging to file + + 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 date_and_time(d, t, values=v) + + !write(timestamp, '(I4.4,"-",I2.2,"-",I2.2," ",I2.2,":",I2.2,":",I2.2,".",I3.3)') & + ! v(1), v(2), v(3), v(5), v(6), v(7), v(8) + + !print *, trim(timestamp), ' CALLING M65A' + + + call init_timer() + + !print *, 'IN RUN_M65, just passed init_timer' + do while (stop_m65 == 0) + if (decoder_ready /=0 .and. newdat /= 0) then + ! call date_and_time(d, t, values=v) + + ! write(timestamp, '(I4.4,"-",I2.2,"-",I2.2," ",I2.2,":",I2.2,":",I2.2,".",I3.3)') & + ! v(1), v(2), v(3), v(5), v(6), v(7), v(8) + + ! print *, trim(timestamp), ' CALLING M65A' + call m65a() + end if +!print *, ' ENTERING SLEEP_MSEC' +call sleep_msec(50) +!print *, ' RETURNED FROM SLEEP_MSEC' +!print *, ' LOOP: stop_m65 =', stop_m65, & +! ' decoder_ready=', decoder_ready, & +! ' newdat=', newdat + +! stop_m65 = .true. + end do + +! print *, 'RUN_M65 exiting main loop.' +! flush (6) + 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..780d8a4c 100644 --- a/map65/libm65/s3avg.f90 +++ b/map65/libm65/s3avg.f90 @@ -1,14 +1,28 @@ -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, 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, ntol + real, intent(in) :: xdt + real, intent(in) :: s3(64,63) !Synchronized spectra for 63 symbols + integer, intent(inout) :: nsum, nkv + character(len=22), intent(inout) :: decoded + real s3a(64,63,64) !Saved spectra real s3b(64,63) !Average spectra integer iutc(64),ihz(64),ipol(64) + integer :: i,ihzdiff,nadd,ncount,nhist + integer :: mrs(63), mrs2(63) !Dummy arguments for extract + real :: dtdiff real dt(64) - character*22 decoded logical ltext,first data first/.true./ save @@ -48,7 +62,7 @@ subroutine s3avg(nsave,mode65,nutc,nhz,xdt,npol,ntol,s3,nsum,nkv,decoded) 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 +72,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..a5f3b01f --- /dev/null +++ b/map65/libm65/stdout_channel_mod.f90 @@ -0,0 +1,123 @@ +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) :: dataSize + 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 + implicit none + + !==== Dummy argument ===================================================== + character(len=*), intent(in) :: msg + + !==== Local variables ==================================================== + integer(c_int32_t) :: n, i, rc + integer(c_int32_t) :: w, idx + 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 + + ! 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..c45d8852 --- /dev/null +++ b/map65/libm65/stdout_shared_layout.h @@ -0,0 +1,20 @@ +// 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 dataSize; // Bytes of new data just written + 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..0fbcab3a --- /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.dataSize = 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..d1c27fc2 100644 --- a/map65/libm65/symspec.f90 +++ b/map65/libm65/symspec.f90 @@ -1,47 +1,57 @@ +module symspec_mod + implicit none +contains + 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/ + 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: fcenter + 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, nfsample + 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) + + + ! ---- 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) :: w(NFFT), w2a(NFFT), w2b(NFFT) + complex :: z, zfac, zsumx, zsumy, cx(NFFT), cy(NFFT), cx00(NFFT), cy00(NFFT) + 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 + +if (k.gt.5751000) goto 999 +if (k.lt.NFFT) then + ihsym = 0 + goto 999 +endif + if(k0.eq.99999999) then pi=4.0*atan(1.0) w2a=0. @@ -56,18 +66,21 @@ 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 + hsym=2048.d0*96000.d0/11025.d0 if(nfsample.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. +endif + +k0 = k + nzap=0 sigmas=1.5*(10.0**(0.01*nbslider)) + 0.7 peaklimit=sigmas*max(10.0,rms) @@ -83,7 +96,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 @@ -108,17 +122,18 @@ subroutine symspec(k,nxpol,ndiskdat,nb,nbslider,idphi,nfsample, & npts=NFFT !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 @@ -182,7 +197,7 @@ subroutine symspec(k,nxpol,ndiskdat,nb,nbslider,idphi,nfsample, & 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,6 +225,11 @@ 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)) @@ -222,3 +242,6 @@ subroutine symspec(k,nxpol,ndiskdat,nb,nbslider,idphi,nfsample, & 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/test_astro_pipeline.f90 b/map65/libm65/test_astro_pipeline.f90 new file mode 100644 index 00000000..07a67ccc --- /dev/null +++ b/map65/libm65/test_astro_pipeline.f90 @@ -0,0 +1,32 @@ +program test_astro_pipeline + use iso_fortran_env, only: real64 + use astrosub_mod + implicit none + + integer :: nyear, month, nday, nfreq, ndop00 + real(real64) :: uth + character(len=6) :: mygrid + + ! Simple test case + nyear = 2025 + month = 1 + nday = 15 + uth = 12.0_real64 ! 12:00 UTC + nfreq = 1440000000/1000000 ! e.g. 1440 MHz → 1440 + mygrid = 'FN20rx' ! or whatever grid you like + ndop00 = 0 + + call astrosub00(nyear,month,nday,uth,nfreq,mygrid,ndop00,len(mygrid)) + + print *, 'Test astro pipeline:' + print *, ' nyear =', nyear + print *, ' month =', month + print *, ' nday =', nday + print *, ' uth =', uth + print *, ' nfreq =', nfreq + print *, ' mygrid =', mygrid + print *, ' ndop00 =', ndop00 + +end program test_astro_pipeline + +!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/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..5017bc89 100644 --- a/map65/libm65/trimlist.f90 +++ b/map65/libm65/trimlist.f90 @@ -1,28 +1,39 @@ -subroutine trimlist(sig,km,ftol,indx,nsiz,nz) - - parameter (MAXMSG=1000) !Size of decoded message list - real sig(MAXMSG,30) - integer indx(MAXMSG),nsiz(MAXMSG) - -! 1 2 3 4 5 6 7 8 -! nfile nutc freq snr dt ipol flip sync - - call indexx(sig(1,3),km,indx) !Sort list by frequency - - 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 - - return -end subroutine trimlist +module trimlist_mod + implicit none +contains + subroutine trimlist(sig,km,ftol,indx,nsiz,nz) + use indexx_mod + implicit none + + integer, parameter :: MAXMSG=1000 !Size of decoded message list + real, intent(in) :: sig(MAXMSG,30) + integer, intent(in) :: km + real, intent(in) :: ftol + integer, intent(out) :: indx(MAXMSG) + integer, intent(out) :: nsiz(MAXMSG) + integer, intent(out) :: nz + + integer :: n, i0, i, j0, j + + ! 1 2 3 4 5 6 7 8 + ! nfile nutc freq snr dt ipol flip sync + + call indexx(sig(1,3),km,indx) !Sort list by frequency + + 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 + + end subroutine trimlist +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..a39b42f2 100644 --- a/map65/libm65/wideband_sync.f90 +++ b/map65/libm65/wideband_sync.f90 @@ -1,273 +1,328 @@ 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.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 + + integer, parameter :: NFFT = 32768 + integer, parameter :: MAX_CANDIDATES = 50 + real(real32), parameter :: SNR1_THRESHOLD = 4.5 + type(sync_dat), allocatable :: sync(:) !NFFT + 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 + use indexx_mod, only: indexx + use iso_fortran_env, only: real64 + + implicit none + + !==== Dummy arguments ===================================================== + real, intent(in) :: ss(4,322,NFFT) + real, intent(in) :: savg(4,NFFT) + 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 + 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, 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 + 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 = int((sync(n)%xdt + 1.0)/tstep - 1.0) + j2 = int((sync(n)%xdt + 52.0)/tstep + 1.0) + if (flip .ne. 0) j2 = int((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 ! 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, jz, nfa, nfb) + use iso_c_binding + use debug_log + use indexx_mod + use txpol_mod + use trimlist_mod + use pctile_mod + use polfit_mod + implicit none -! Compute "orange sync curve" using the Q65 sync pattern + !==== Dummy arguments ===================================================== + real, intent(in) :: ss(4,322,NFFT) + real, intent(in) :: savg(4,NFFT) + logical, intent(in) :: xpol + 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 + real(c_float) :: savg_med(4) + real ccf4(4), ccf4best(4), a(3) + real base, bw, ccf, ccfmax, df3, fac, flip, poldeg, spk, syncmin, tstep + integer i, i0, ia, ib, ipolbest, j, ja, jb, k, lag, lagbest + integer nbw, nguard, npol, ipol + logical first + integer isync(22) + integer jsync0(63), jsync1(63) + 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 = 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 ! 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 - - 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 - - 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 - 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 + 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 + + 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 + + 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 + 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 = int(flip) + sync(i)%birdie = .false. + if (ccfmax/(savg(ipolbest, i)/savg_med(ipolbest)) .lt. 3.0) sync(i)%birdie = .true. + + ! --- 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 + + bw = 65*4*1.66666667 !Q65-60C bandwidth + nbw = int(bw/df3 + 1) !Number of bins to blank + syncmin = 2.0 + nguard = 10 + do i = ia, ib + if (sync(i)%ccfmax .lt. syncmin) cycle + if ((i .lt. 1) .or. (i .gt. (NFFT - nbw))) cycle !w3sz debug + 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 + if (ja .lt. 1) cycle !ja = 1 !w3sz debug + if (jb .lt. 1) cycle !jb = 1 !w3sz debug + if (ja .gt. NFFT) cycle !ja = NFFT !w3sz debug + if (jb .gt. NFFT) cycle !jb = NFFT !w3sz debug + sync(ja:jb)%ccfmax = 0. + sync(i0)%ccfmax = spk + enddo ! do i=ia,ib ! write(15,3015) 0.001*(i-1)*df3+32.0,sync(i)%ccfmax,sync(i)%xdt, & @@ -275,7 +330,13 @@ 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 + + subroutine init_wideband_sync(n) + implicit none + integer, intent(in) :: n + if (.not. allocated(sync)) allocate (sync(n)) + 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..55ef209a 100644 --- a/map65/main.cpp +++ b/map65/main.cpp @@ -5,9 +5,16 @@ #include <QtGui> #endif #include <QApplication> +#ifdef _WIN32 +#include <windows.h> +#endif + #include "revision_utils.hpp" #include "mainwindow.h" +#include "fortran_mutex.hpp" + +#include <cstdio> extern "C" { // Fortran procedures we need @@ -16,19 +23,35 @@ extern "C" { 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"); + a.setApplicationVersion ("3.6"); // switch off as we share an Info.plist file with WSJT-X a.setAttribute (Qt::AA_DontUseNativeMenuBar); 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..7a47d5b6 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,15 +22,95 @@ #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 <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" + +#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 -short int iwave[2*60*12000]; //Wave file for Tx audio + +QByteArray g_TxTuneGeometry; + +namespace { +struct Map65TxWaveStorage { short int samples[2*60*12000]; }; +struct Map65RxSamplesStorage { qint16 samples[4*60*96000]; }; + +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; +} +} // namespace + +short int (&iwave)[2*60*12000] = (new Map65TxWaveStorage{})->samples; //Wave file for Tx audio int nwave; //Length of Tx waveform bool btxok; //True if OK to transmit bool bTune; @@ -36,35 +119,95 @@ double outputLatency; //Latency in seconds int txPower; int iqAmp; int iqPhase; -qint16 id[4*60*96000]; +qint16 (&id)[4*60*96000] = (new Map65RxSamplesStorage{})->samples; +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; +bool m_psk_reporter_tcpip; + +struct MainWindow::DecoderContext +{ + StdoutChannel* stdoutChan; + DecoderContext(); + ~DecoderContext(); +}; + +MainWindow::DecoderContext::DecoderContext() +{ + stdoutChan = new StdoutChannel( + L"MAP65_STDOUT_MAPPING", + L"MAP65_STDOUT_EVENT", + 64 * 1024 + ); +} + +MainWindow::DecoderContext::~DecoderContext() +{ + delete stdoutChan; +} //-------------------------------------------------- MainWindow constructor MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), m_appDir {QApplication::applicationDirPath ()}, - m_settings_filename {m_appDir + "/map65.ini"}, + m_dataDir {writableMap65DataDir ()}, + 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 NFFT IS: " << NFFT; + // Legacy C++ and Fortran paths still use relative opens for runtime files. + if (!QDir::setCurrent(m_dataDir)) { + qWarning() << "Unable to set MAP65 working directory:" << m_dataDir; + } + constexpr int baseSeconds = 56; + constexpr int sampleRate = 96000; + 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); + + std::cout << "dd pointer set to: " << dd + << " size: " << ddSize + << " (channels=" << channels + << ", pairsWorst=" << pairsWorst << ")\n"; + + ss = new float[4 * 322 * NFFT]; + savg = new float[4 * NFFT]; + set_ss_ptr(ss, 4, 322, NFFT); + std::cout << "ss pointer set to: " << ss << std::endl; + set_savg_ptr(savg, 4, NFFT); + std::cout << "savg pointer set to: " << savg << std::endl; + + 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( \ @@ -108,11 +251,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))); + // 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 (program_title ()); + qDebug() << "MAINWINDOW about to start soundInThread SIGNAL/SLOT connections"; connect(&soundInThread, SIGNAL(readyForFFT(int)), this, SLOT(dataSink(int))); @@ -121,19 +353,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 +371,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; @@ -187,42 +408,16 @@ 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 - - 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 - - fftwf_import_wisdom_from_filename (QDir {m_appDir}.absoluteFilePath ("map65_wisdom.dat").toLocal8Bit ()); + fftwf_import_wisdom_from_filename (QDir {m_dataDir}.absoluteFilePath ("map65_wisdom.dat").toLocal8Bit ()); + readSettings(); //Restore user's setup params 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"); + QFile quitFile(QDir {m_dataDir}.absoluteFilePath (".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 +432,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 +451,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>; @@ -278,8 +475,6 @@ MainWindow::MainWindow(QWidget *parent) : m_monitoring=true; // Start with Monitoring ON 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); @@ -291,7 +486,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; @@ -321,19 +516,42 @@ MainWindow::MainWindow(QWidget *parent) : 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 +562,312 @@ 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_ "; + + QByteArray runtimeDir = QDir::toNativeSeparators(m_dataDir).toLocal8Bit(); + set_wsjtx_dir_(runtimeDir.constData(), runtimeDir.size()); + + QFutureWatcher<void>* watcher_m65 = new QFutureWatcher<void>(this); + connect(watcher_m65, &QFutureWatcher<void>::finished, + this, &MainWindow::onRunM65Finished); + + watcher_m65->setFuture(QtConcurrent::run([=]() { + // 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; + int rate_flag = m_fs96000 ? 1 : 0; + run_m65_(&xpol_flag, &rate_flag); + + })); +} + +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; + + 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 + ); + } + } + } + + }); +} + +void MainWindow::processStdOut(QString t) +{ + +// qDebug().noquote() << QDateTime::currentMSecsSinceEpoch() << "PROCESS STDOUT:" << t; + + //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 (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(); + lab5->setText(QString::number(ndecodes)); + m_map65RxLog = 0; + } + + 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 + const QString decode_line = t.mid(1, n - m); + + // Suppress *second* narrowband GUI entry, but keep everything else + if (m_RxState != 2 || m_diskData) { + if (n >= 30 || t.indexOf("Best-fit") >= 0) + 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 +} + +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 +881,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,9 +896,6 @@ 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); @@ -424,6 +939,19 @@ 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() @@ -435,33 +963,35 @@ void MainWindow::readSettings() restoreGeometry(settings.value("geometry").toByteArray()); ui->dxCallEntry->setText(settings.value("DXcall","").toString()); ui->dxGridEntry->setText(settings.value("DXgrid","").toString()); - m_path = settings.value("MRUdir", m_appDir + "/save").toString(); + m_path = settings.value("MRUdir", QDir {m_dataDir}.absoluteFilePath("save")).toString(); m_txFirst = settings.value("TxFirst",false).toBool(); 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(); 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(); @@ -533,7 +1063,37 @@ void MainWindow::readSettings() m_w3szUrl=settings.value("w3szUrl",true).toBool(); m_otherUrl=settings.value("otherUrl","").toString(); m_spot_to_psk_reporter=settings.value("spotPSK",true).toBool(); + m_psk_reporter_tcpip=settings.value("PSKReporterTCPIP",false).toBool(); + + 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() @@ -545,11 +1105,12 @@ void MainWindow::dataSink(int k) static int nzap=0; static int ntrz=0; static int nkhz; - static int nfsample=96000; - static int nxpol=0; + int nfsample= m_fs96000 ? 96000 : 95238; + 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; @@ -559,14 +1120,16 @@ void MainWindow::dataSink(int k) 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; @@ -574,11 +1137,11 @@ void MainWindow::dataSink(int k) 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, + &nfsample, &m_adjustIQ, &m_applyIQcal, &m_gainx, &m_gainy, &m_phasex, &m_phasey, &rejectx, &rejecty, &px, &py, s, &nkhz, &ihsym, &nzap, &slimit, lstrong); @@ -627,7 +1190,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) ); @@ -653,13 +1216,13 @@ void MainWindow::dataSink(int k) // 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)) { + int ntr1 = (ms/1000) % m_TRperiod; + if((m_diskData && ihsym <= m_waterfallAvg) || (!m_diskData && ntr1<ntrz)) { for (int i=0; i<NFFT; i++) { splot[i] = 1.e30; } } - ntrz=ntr; + ntrz=ntr1; n=0; } @@ -667,19 +1230,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(ihsym); 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(ihsym); QDateTime t = QDateTime::currentDateTimeUtc(); m_dateTime=t.toString("yyyy-MMM-dd hh:mm"); decode(); //Start the decoder @@ -688,151 +1254,239 @@ 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=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*96000; + 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) +{ + setDecoderReady(0); + int npts = 2 * 56 * 96000; + if (xpol) npts = 2 * npts; + + // j indexes dd[], which has 4 channels per pair + int j = 0; + + // Clear id[] properly + memset(id, 0, npts * sizeof(id[0])); + + // Open file + FILE* fp = fopen(fname.toUtf8().constData(), "rb"); + if (!fp) { + qWarning() << "Failed to open file:" << fname; + return; + } + + // Read fcenter + double fcenter = 0.0; + if (fread(&fcenter, sizeof(fcenter), 1, fp) != 1) { + fclose(fp); + return; + } + + setFcenter(fcenter); + + // Skip the 8-byte zero padding + uint64_t pad = 0; + if (fread(&pad, sizeof(pad), 1, fp) != 1) { + fclose(fp); + return; + } + + + // Read raw samples + size_t nRead = fread(id, 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) {QMessageBox::critical(this, tr("Error in SoundIn"), 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; - 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) { + // + // 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); + soundInThread.setRate(m_fs96000 ? 96000.0 : 95238.1); + 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(); } } + void MainWindow::on_monitorButton_clicked() //Monitor { m_monitoring=true; @@ -1023,39 +1677,39 @@ 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 + set_stop_m65(1); + if (m_gui_timer) m_gui_timer->stop(); + m_wide_graph_window->saveSettings(); - // close pipes - proc_m65.closeReadChannel (QProcess::StandardOutput); - proc_m65.closeReadChannel (QProcess::StandardError); + QFile quitFile(QDir {m_dataDir}.absoluteFilePath (".quit")); + (void)quitFile.open(QFileDevice::ReadWrite); + setQuitID(quitFile.handle()); - // flush all input - proc_m65.setReadChannel (QProcess::StandardOutput); - proc_m65.readAll (); - proc_m65.setReadChannel (QProcess::StandardError); - proc_m65.readAll (); + 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(); - 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); +#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; @@ -1127,6 +1781,9 @@ void MainWindow::on_actionOpen_triggered() //Open File { m_monitoring=false; 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 +1803,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 +1833,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,9 +1869,9 @@ 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 @@ -1215,6 +1886,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() @@ -1314,8 +1986,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 +1996,126 @@ 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); 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); + setNagain(0); + 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); + setNfsample(96000); + if(!m_fs96000) setNfsample(95238); + 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); + + setNagain(0); //added 12-30-25 to agree with legacy + if (!m_diskData) setNdiskdat(0); //added 12-30-25 to agree with legacy + setDecoderReady(1); 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 +2128,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 +2140,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 +2201,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); @@ -1604,26 +2246,35 @@ void MainWindow::guiUpdate() 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 +2292,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 +2307,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) @@ -1687,7 +2338,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 +2357,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;\ } @@ -1735,10 +2389,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 +2412,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 +2651,23 @@ void MainWindow::genStdMsgs(QString rpt) //genStdMsgs() ui->txrb1->setChecked(true); } +QString MainWindow::call3Path() const +{ + QString writablePath = QDir {m_dataDir}.absoluteFilePath("CALL3.TXT"); + if (!QFile::exists(writablePath)) { + QString bundledPath = QDir {m_appDir}.absoluteFilePath("CALL3.TXT"); + if (QFile::exists(bundledPath)) { + QFile::copy(bundledPath, writablePath); + } + } + return writablePath; +} + 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 +2722,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 +2741,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 +2784,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 +2902,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 +2963,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 +2978,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); @@ -2415,13 +3075,17 @@ void MainWindow::on_actionFUNcube_Dongle_triggered() void MainWindow::on_actionEdit_wsjt_log_triggered() { - proc_editor.start (QDir::toNativeSeparators (m_editorCommand), {QDir::toNativeSeparators (m_appDir + "/wsjt.log"), }); + proc_editor.start (QDir::toNativeSeparators (m_editorCommand), + {QDir::toNativeSeparators (QDir {m_dataDir}.absoluteFilePath ("wsjt.log")), }); } 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 +3121,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 +3136,8 @@ void MainWindow::read_log() f.close(); } } + +void pa_deinit() +{ + Pa_Terminate(); +} diff --git a/map65/mainwindow.h b/map65/mainwindow.h index 97d73b03..d60e1239 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 "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,65 @@ 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}; + bool m_network; + int m_pttPortNumber = 0; + + QString m_pttPath; + QString m_appDir; + QString m_dataDir; + 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; + bool m_fs96000; + 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 +108,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(); @@ -143,34 +201,25 @@ private slots: void on_actionQ65C_triggered(); void on_actionQ65D_triggered(); void on_actionQ65E_triggered(); - void on_pbTxMode_clicked(); private: - Ui::MainWindow *ui; - QString m_appDir; - QString m_settings_filename; + virtual void keyPressEvent (QKeyEvent *) override; + virtual bool eventFilter (QObject *, QEvent *) override; + virtual void closeEvent (QCloseEvent *) override; + QString call3Path() const; + 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 +229,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 +249,40 @@ 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; + 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; @@ -253,36 +302,25 @@ 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(); @@ -297,11 +335,14 @@ 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 void getDev(int* numDevices,char hostAPI_DeviceName[][50], int minChan[], int maxChan[], int minSpeed[], int maxSpeed[]); @@ -309,7 +350,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* nfsample, 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..1f6b27f6 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"> @@ -1453,6 +1482,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> diff --git a/map65/map65.pro b/map65/map65.pro index 79a2e5c4..b71140d6 100644 --- a/map65/map65.pro +++ b/map65/map65.pro @@ -35,17 +35,17 @@ SOURCES += main.cpp mainwindow.cpp plotter.cpp about.cpp \ astro.cpp displaytext.cpp getdev.cpp \ txtune.cpp meterwidget.cpp signalmeter.cpp \ cqdatasender.cpp liveCQSender.cpp Radio.cpp \ - PSKReporter.cpp + ../Network/PSKReporter.cpp ../Network/PSKReporterIPFIX.cpp win32 { -SOURCES += killbyname.cpp set570.cpp +SOURCES += 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 + liveCQSender.hpp Radio.hpp ../Network/PSKReporter.hpp ../Network/PSKReporterIPFIX.hpp FORMS += mainwindow.ui about.ui devsetup.ui widegraph.ui \ messages.ui bandmap.ui astro.ui \ diff --git a/map65/map65_decode_lifecycle.txt b/map65/map65_decode_lifecycle.txt new file mode 100644 index 00000000..d3aaba57 --- /dev/null +++ b/map65/map65_decode_lifecycle.txt @@ -0,0 +1,385 @@ +/* +=============================================================================== + MAP65 DECODE LIFECYCLE — MODERNIZED AND LEGACY‑ACCURATE +=============================================================================== + + This document describes the sequencing rules for disk and live-input decoding + in modern MAP65. The goal is deterministic, race‑free behavior that matches + the legacy MAP65 decode pipeline while eliminating timing-dependent behavior. + +------------------------------------------------------------------------------- + OVERVIEW +------------------------------------------------------------------------------- + A decode cycle consists of: + 1. Preparing input data (disk or live) + 2. Preparing decode parameters (C++ decode()) + 3. Triggering the Fortran decoder loop (newdat + decoder_ready) + 4. Receiving <DecodeFinished> from stdout + 5. Detecting decoder silence (idle timer) + 6. Clearing busy and optionally auto‑advancing + + The Fortran decoder loop runs ONLY when: + decoder_ready == 1 AND newdat == 1 + +------------------------------------------------------------------------------- + STATE FLAGS +------------------------------------------------------------------------------- + newdat: + - Set to 1 by the caller (disk or live) BEFORE calling decode(). + - Indicates that new data is ready for decoding. + - Cleared internally by the decoder after each pass. + - Only one pass per file/minute is expected (legacy behavior). + + decoder_ready: + - Set to 0 BEFORE calling decode() (disk or live). + - Set to 1 at the END of decode() after all parameters are prepared. + - Prevents the decoder loop from running early with stale parameters. + + decoderBusy: + - Set to true ONLY inside decode(). + - Set to false ONLY in the idle timer after <DecodeFinished> + silence. + - Reflects actual decoder activity, not file loading. + +------------------------------------------------------------------------------- + DISK INPUT SEQUENCE +------------------------------------------------------------------------------- + getfile(): + setDecoderReady(0); // block decoder loop + load file data + setNewdat(1); // legacy behavior + decode(); // prepares parameters, sets decoder_ready=1 + +------------------------------------------------------------------------------- + LIVE INPUT SEQUENCE +------------------------------------------------------------------------------- + dataSink(): + when a full 60s block is ready: + setDecoderReady(0); // block decoder loop + setNewdat(1); // legacy behavior + decode(); // prepares parameters, sets decoder_ready=1 + +------------------------------------------------------------------------------- + DECODE() SEQUENCE +------------------------------------------------------------------------------- + decode(): + decodeBusy(true); // decoder is now officially active + prepare all decode parameters (nfa, nfb, nfshift, mode, etc.) + setDecoderReady(1); // allow decoder loop to run + // newdat was already set by caller + +------------------------------------------------------------------------------- + FORTRAN LOOP +------------------------------------------------------------------------------- + do while (.not. stop_m65) + if (decoder_ready .and. newdat .ne. 0) call m65a() + call sleep_msec(50) + end do + +------------------------------------------------------------------------------- + STDOUT PROCESSING +------------------------------------------------------------------------------- + processStdOut(): + On "<DecodeFinished>": + m_decodeFinishedCount++ + // no second pass expected (legacy behavior) + +------------------------------------------------------------------------------- + IDLE TIMER +------------------------------------------------------------------------------- + Idle timer fires when decoder stdout is silent: + if (m_decodeFinishedCount == 0) + ignore (decoder not finished yet) + + decodeBusy(false); // decoder is done + + if (m_loopall && m_diskData) + on_actionOpen_next_in_directory_triggered(); + +------------------------------------------------------------------------------- + NOTES +------------------------------------------------------------------------------- + - Only ONE decode pass per file/minute is expected (legacy MAP65 behavior). + - No second-pass logic is required. + - No failsafe timer is required. + - This lifecycle eliminates all timing races present in earlier versions. +=============================================================================== +*/ +/* +=============================================================================== + LIVE MODE VS DISK MODE — BUSY‑CLEARING RULES +=============================================================================== + + Modern MAP65 supports two fundamentally different input modes: + + 1. Disk mode (file-based decoding) + 2. Live mode (real-time network or audio decoding) + + These modes differ in how decoder stdout behaves, and therefore require + different rules for clearing the decoderBusy flag. + +------------------------------------------------------------------------------- + DISK MODE (FILE INPUT) +------------------------------------------------------------------------------- + - Decoder stdout is finite. + - After <DecodeFinished>, the decoder emits a tail of late decodes, + bandmap lines, and summary lines. + - Once this tail completes, stdout becomes silent. + - The idle timer detects this silence (~2500 ms) and clears busy. + + Correct behavior in disk mode: + Wait for <DecodeFinished> + THEN wait for ~2500 ms of silence + THEN clear busy + THEN auto-advance (if loopall is enabled) + + This reproduces legacy MAP65’s blocking behavior exactly. + +------------------------------------------------------------------------------- + LIVE MODE (REAL-TIME INPUT) +------------------------------------------------------------------------------- + In live mode, the decoder *never* becomes silent: + + - The decoder emits continuous tracking lines (e.g., "@1296.xxx") every + 120 ms throughout the entire minute. + - These lines continue even after <DecodeFinished>. + - Therefore, the idle timer will NEVER observe a 2500 ms silent period. + - If busy were cleared only by the idle timer, it would remain stuck TRUE + forever, causing the GUI to remain greyed out. + + To match legacy behavior and maintain correct GUI state, MAP65 must clear + busy *immediately* upon receiving <DecodeFinished> in live mode. + + Correct behavior in live mode: + On <DecodeFinished>: + clear busy immediately + (do NOT wait for silence) + (do NOT auto-advance) + + This mirrors legacy MAP65, where the blocking read returned immediately + after <DecodeFinished> during live decoding. + +------------------------------------------------------------------------------- + SUMMARY OF BUSY‑CLEARING RULES +------------------------------------------------------------------------------- + Disk mode: + <DecodeFinished> → wait for silence → busy = false → auto-advance + + Live mode: + <DecodeFinished> → busy = false immediately (no idle timer) + +------------------------------------------------------------------------------- + RATIONALE +------------------------------------------------------------------------------- + - Disk mode produces finite stdout; silence detection is meaningful. + - Live mode produces continuous stdout; silence detection is impossible. + - Legacy MAP65 implicitly handled both cases correctly via blocking I/O. + - Modern MAP65 must explicitly differentiate the two modes to reproduce + legacy behavior and avoid GUI lockout. + +=============================================================================== +*/ + +/* +=============================================================================== + WHY LEGACY MAP65 DID NOT NEED AN IDLE TIMER +=============================================================================== + + Legacy MAP65 used a synchronous, blocking I/O model for running the decoder. + This architecture *implicitly* waited for the decoder to finish producing ALL + stdout before advancing to the next file. No timers, heuristics, or silence + detection were required. + +------------------------------------------------------------------------------- + LEGACY ARCHITECTURE (SYNCHRONOUS / BLOCKING) +------------------------------------------------------------------------------- + - The decoder was launched as a child process. + - MAP65 read stdout using a blocking read loop. + - The read call did not return until the decoder flushed all output. + - The program could not proceed until stdout was fully drained. + - <DecodeFinished> was just a marker, not a signal to advance. + - Late decodes, bandmap lines, and summary lines always arrived before the + blocking read returned. + + Result: + Legacy MAP65 *automatically* waited long enough to capture all decodes, + including those emitted 1–3 seconds after <DecodeFinished>. + +------------------------------------------------------------------------------- + MODERN ARCHITECTURE (ASYNCHRONOUS / EVENT-DRIVEN) +------------------------------------------------------------------------------- + Modern MAP65 uses Qt's QProcess, which delivers decoder stdout asynchronously: + + - stdout arrives in bursts via readyReadStandardOutput() signals + - the GUI thread continues running while the decoder works + - <DecodeFinished> does NOT mean the decoder is done talking + - late decodes and summary lines may arrive up to ~2500 ms later + - the decoder does not close stdout between passes or files + + Because the program is no longer blocked waiting for stdout, MAP65 must + explicitly detect when the decoder has gone silent. + +------------------------------------------------------------------------------- + WHY AN IDLE TIMER IS REQUIRED +------------------------------------------------------------------------------- + In the asynchronous model, MAP65 must decide when the decoder is "done." + The correct criterion is: + + <DecodeFinished> has been seen + AND + no stdout has arrived for ~2500 ms + + This silence window reproduces the behavior of legacy MAP65's blocking read: + it ensures that all late decodes, bandmap lines, and summary lines have been + received before auto-advancing. + +------------------------------------------------------------------------------- + SUMMARY +------------------------------------------------------------------------------- + Legacy MAP65: + - Blocking I/O naturally waited for all decoder output. + - No idle timer needed. + + Modern MAP65: + - Asynchronous I/O requires explicit silence detection. + - A 2500 ms idle window faithfully reproduces legacy behavior. + +=============================================================================== +*/ +/* +=============================================================================== + FILE INPUT MODE DECODER OUTPUT TIMING DIAGRAM +=============================================================================== + + This diagram illustrates the typical sequence of decoder stdout during a + single decode pass when using file input. It shows why legacy MAP65 naturally + waited for all output, and why modern MAP65 must explicitly wait for a period + of silence. + + Time flows left → right. + +------------------------------------------------------------------------------- + LEGEND +------------------------------------------------------------------------------- + |====| Decoder producing stdout + <DF> "<DecodeFinished>" marker + .... Silence (no stdout) + [2500 ms silence] Idle timer threshold in modern MAP65 + +------------------------------------------------------------------------------- + TYPICAL DECODER STDOUT TIMELINE +------------------------------------------------------------------------------- + + QuickDecode FullDecode Post-Processing + (fast) (heavy FFT) (late decodes, bandmap, summary) + |====================|====================|====================| + ^ ^ ^ ^ + | | | | + Start <DF> Late output Final flush + continues then silence + + 0 ms ~800–1200 ms ~1200–2200 ms ~2200–2500+ ms + ---------------------------------------------------------------------------→ time + + After <DecodeFinished>, the decoder may continue emitting: + - late decodes + - bandmap lines + - candidate summaries + - sync statistics + - final housekeeping output + + This tail can last up to ~2500 ms depending on CPU speed and decode load. + +------------------------------------------------------------------------------- + LEGACY MAP65 BEHAVIOR (BLOCKING I/O) +------------------------------------------------------------------------------- + Legacy MAP65 used a blocking read loop: + - It did not return until ALL stdout was flushed. + - It implicitly waited for the entire tail of output. + - It always captured all decodes. + + No idle timer was needed. + +------------------------------------------------------------------------------- + MODERN MAP65 BEHAVIOR (ASYNCHRONOUS I/O) +------------------------------------------------------------------------------- + Modern MAP65 receives stdout via Qt signals: + - <DecodeFinished> does NOT mean the decoder is done. + - Late output arrives asynchronously after <DF>. + - The GUI thread continues running. + - MAP65 must explicitly detect when the decoder has gone silent. + + Correct behavior: + - Wait for <DecodeFinished> + - THEN wait for ~2500 ms of silence + - THEN auto-advance + + This reproduces legacy behavior exactly. + +=============================================================================== +*/ +/* +=============================================================================== + LIVE MODE TIMING DIAGRAM (REAL‑TIME NETWORK / AUDIO INPUT) +=============================================================================== + + This diagram illustrates why live-mode decoding cannot rely on the idle timer + to detect decoder completion. Unlike disk-mode decoding, live-mode produces + continuous stdout throughout the entire minute, even AFTER <DecodeFinished>. + + Time flows left → right. + +------------------------------------------------------------------------------- + LEGEND +------------------------------------------------------------------------------- + |====| Decoder producing stdout (continuous live tracking output) + <DF> "<DecodeFinished>" marker for early or full decode + .... (Never occurs in live mode — no silence) + [X] Idle timer never fires in live mode + +------------------------------------------------------------------------------- + LIVE-MODE STDOUT TIMELINE (52s + 56s DECODE CYCLES) +------------------------------------------------------------------------------- + + Live tracking output (continuous @1296.xxx lines every ~120 ms) + |=========================================================================| + ^ ^ + | | + Start of minute End of minute + + Early Decode (~52s) Full Decode (~56s) + |====================| |====================| + ^ ^ ^ ^ + | | | | + Trigger <DF> Trigger <DF> + (ihsym>=280) EarlyFinished (ihsym>=302) DecodeFinished + + ---------------------------------------------------------------------------→ time + + IMPORTANT: + - Live tracking output continues uninterrupted across BOTH decode cycles. + - There is NO period of silence after <DecodeFinished>. + - Therefore the idle timer NEVER observes a 2500 ms quiet window. + - If busy were cleared only by the idle timer, it would remain TRUE forever. + +------------------------------------------------------------------------------- + CORRECT LIVE-MODE BEHAVIOR +------------------------------------------------------------------------------- + On <DecodeFinished> (early or full): + - Clear busy IMMEDIATELY. + - Do NOT wait for silence (there is none). + - Do NOT auto-advance (live mode never advances files). + + This matches legacy MAP65, where the blocking read returned immediately after + <DecodeFinished> during live decoding. + +------------------------------------------------------------------------------- + SUMMARY +------------------------------------------------------------------------------- + Disk mode: + <DecodeFinished> → wait for silence → busy=false → auto-advance + + Live mode: + <DecodeFinished> → busy=false immediately (no idle timer) + +=============================================================================== +*/ diff --git a/map65/messages.cpp b/map65/messages.cpp index 07936c4e..876c04f0 100644 --- a/map65/messages.cpp +++ b/map65/messages.cpp @@ -6,7 +6,7 @@ #include "qt_helpers.hpp" #include "../revision_utils.hpp" #include "../Logger.hpp" -#include "PSKReporter.hpp" +#include "../Network/PSKReporter.hpp" #include "liveCQSender.hpp" #include <QCoreApplication> //liveCQ @@ -79,27 +79,14 @@ 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); - + pskReporter_.reset (new PSKReporter { + {settings2.value ("PSKReporterTCPIP", false).toBool (), + QCoreApplication::applicationDirPath () + "/eclipse.txt", + QString {"MAP65 v" + QCoreApplication::applicationVersion () + " " + revision ()}.simplified ()} }); - connect(pskThread, &QThread::finished, pskThread, &QObject::deleteLater); - pskThread->start(); - if (m_spot_to_psk_reporter) { - initializePSKReporting(); + if (m_spot_to_psk_reporter) + { + initializePSKReporting (); } } @@ -133,7 +120,10 @@ 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)"); + if (pskReporter_) + { + pskReporter_->setLocalStation(receiverCallsign, receiverLocator, "N/A", "N/A (MAP65)"); + } } void Messages::sendLiveCQData(QStringList decodeList) { @@ -162,7 +152,7 @@ void Messages::sendLiveCQData(QStringList decodeList) { 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(); @@ -180,8 +170,8 @@ void Messages::sendLiveCQData(QStringList decodeList) { 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 { @@ -206,7 +196,7 @@ void Messages::sendLiveCQData(QStringList decodeList) { 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 +206,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) { @@ -237,7 +227,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 +237,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) { @@ -344,7 +334,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,13 +370,11 @@ 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 } } @@ -437,11 +424,35 @@ void Messages::sendPSKReporterData(QStringList decodeList) { QTime time2(h, m, s); QDateTime qSpotTime; if (sTime + m_TRperiod < 236000) { - qSpotTime = QDateTime(QDateTime::currentDateTimeUtc().date(), time2, Qt::UTC); + #if QT_VERSION >= QT_VERSION_CHECK(6, 6, 0) + qSpotTime = QDateTime( + QDateTime::currentDateTimeUtc().date(), + time2, + QTimeZone::UTC + ); + #else + qSpotTime = QDateTime( + QDateTime::currentDateTimeUtc().date(), + time2, + Qt::UTC + ); + #endif } else { - qSpotTime = QDateTime((QDateTime::currentDateTimeUtc().addDays(-1)).date(), time2, Qt::UTC); - } + #if QT_VERSION >= QT_VERSION_CHECK(6, 6, 0) + qSpotTime = QDateTime( + QDateTime::currentDateTimeUtc().addDays(-1).date(), + time2, + QTimeZone::UTC + ); + #else + qSpotTime = QDateTime( + QDateTime::currentDateTimeUtc().addDays(-1).date(), + time2, + Qt::UTC + ); + #endif + } // Handle CQ CALL but NO GRID -- dot at 7 if(thePostLine.at(7).contains(".")) { @@ -449,8 +460,8 @@ void Messages::sendPSKReporterData(QStringList decodeList) { 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(); + if(modeChar.contains("#")) mode = QString("JT65") + modeChar.back(); + else if(modeChar.contains(":")) mode = QString("Q65-60") + modeChar.back(); // Handle CQ CALL GRID or CQ XXX CALL -- dot at 8 } else if (thePostLine.at(8).contains(".")) { @@ -468,9 +479,9 @@ void Messages::sendPSKReporterData(QStringList decodeList) { modeChar = thePostLine.at(9).trimmed(); if(modeChar.contains("#")) { - mode = "JT65" + modeChar.back(); + mode = QString("JT65") + modeChar.back(); } else if(modeChar.contains(":")) { - mode = "Q65-60" + modeChar.back(); + mode = QString("Q65-60") + modeChar.back(); } // Handle CQ XXX CALL GRID } else if(thePostLine.at(9).contains(".")) { @@ -482,16 +493,19 @@ void Messages::sendPSKReporterData(QStringList decodeList) { modeChar = thePostLine.at(10).trimmed(); if(modeChar.contains("#")) { - mode = "JT65" + modeChar.back(); + mode = QString("JT65") + modeChar.back(); } else if(modeChar.contains(":")) { - mode = "Q65-60" + modeChar.back(); + mode = QString("Q65-60") + modeChar.back(); } } else { continue; } - emit sendRemoteStationData(senderCallsign, senderLocator, frequency, mode, sNR, qSpotTime); + if (pskReporter_) + { + pskReporter_->addRemoteStation(senderCallsign, senderLocator, frequency, mode, sNR, qSpotTime); + } } } } diff --git a/map65/messages.h b/map65/messages.h index 89170545..67973c53 100644 --- a/map65/messages.h +++ b/map65/messages.h @@ -3,7 +3,7 @@ #include <QDialog> #include "commons.h" -#include "PSKReporter.hpp" +#include "../Network/PSKReporter.hpp" #include <memory> #include <QNetworkReply> #include <QDateTime> @@ -30,8 +30,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,7 +53,7 @@ private: QString m_color2; QString m_color3; - QThread* pskThread; + std::unique_ptr<PSKReporter> pskReporter_; QThread* livecqThread; bool m_closingForShutdown = false; 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..1c158928 100644 --- a/map65/plotter.cpp +++ b/map65/plotter.cpp @@ -1,8 +1,13 @@ #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 @@ -169,6 +174,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; } @@ -265,9 +275,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; @@ -520,10 +530,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 +588,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 +610,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,7 +628,7 @@ 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); @@ -623,8 +643,15 @@ 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); @@ -767,23 +794,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; 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..1147b12e 100644 --- a/map65/plotter.h +++ b/map65/plotter.h @@ -10,9 +10,11 @@ #include <QtGui> #include <QFrame> #include <QImage> +#include <QList> #include <QToolTip> #include <cstring> #include "commons.h" +#include "decode_label.h" #define VERT_DIVS 7 //specify grid screen divisions #define HORZ_DIVS 20 @@ -75,6 +77,26 @@ public: double txFreq(); // 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,6 +114,18 @@ private: int XfromFreq(float f); float FreqfromX(int x); qint64 RoundFreq(qint64 freq, int resolution); + // 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; 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..ff233d20 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> @@ -11,44 +14,8 @@ #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,84 +27,89 @@ 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(!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; - } + if ((statusFlags & paInputOverflow) != 0) { + qDebug() << "Input Overflow"; } - 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 + 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 @@ -146,27 +118,33 @@ 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 } }; } +//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 +152,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 @@ -208,31 +186,28 @@ 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, + 96000.0, + 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; //---------------------------------------------- Soundcard input loop @@ -250,18 +225,20 @@ void SoundInThread::run() //SoundInThread::run() m_TRperiod0=m_TRperiod; } k=udata.kin; - udata.iqswap=m_IQswap; + udata.iqswap= (m_IQswap != 0); udata.dB=m_dB; if(m_monitoring) { + double fcenter; if(m_bForceCenterFreq) { - datcom_.fcenter=m_dForceCenterFreq; + fcenter = m_dForceCenterFreq; } else { - datcom_.fcenter=144.125; + fcenter = 144.125; // default center } + 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 @@ -314,7 +291,6 @@ void SoundInThread::setFadd(double x) m_fAdd=x; } - void SoundInThread::quit() //quit() { quitExecution = true; @@ -344,10 +320,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 +358,7 @@ void SoundInThread::inputUDP() int msec; float userfreq; int iptr; - quint16 iblk; + quint16 iblk; //was quint16 qint8 nrx; char iusb; double d8[174]; @@ -392,7 +370,6 @@ void SoundInThread::inputUDP() int ntr; int nhsym0=0; int iz=174; - int nBusy=0; // Main loop for input of UDP packets over the network: while (!qe) { @@ -401,8 +378,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 @@ -427,25 +407,32 @@ void SoundInThread::inputUDP() if ((k+iz) <= 60*96000) { 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; - } +m_hsym = (k-2048)*11025.0/(2048.0*m_rate); +if (m_hsym != nhsym0) { + if (m_dataSinkBusy) { + } else { + m_dataSinkBusy = true; + + QDateTime now = QDateTime::currentDateTime(); + QString ts = now.toString("yyyy-MM-dd hh:mm:ss.zzz"); + + emit readyForFFT(k); + } + nhsym0 = m_hsym; +} + } } } delete udpSocket; + udpSocket = nullptr; } diff --git a/map65/soundin.h b/map65/soundin.h index 78947338..7dc78839 100644 --- a/map65/soundin.h +++ b/map65/soundin.h @@ -6,6 +6,8 @@ #include <QDebug> #include <valarray> +class MainWindow; //Forward declaration + // Thread gets audio data from soundcard and signals when a buffer of // specified size is available. class SoundInThread : public QThread @@ -55,6 +57,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..0828afe4 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]; 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,125 @@ 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; + + // Debug: Check this value in your console once to ensure it's ~0.229 for ASIO + static bool debugOnce = true; + if(debugOnce) { + qDebug() << "Stream Rate:" << udata->streamSampleRate << "Step:" << step; + qDebug() << "channels:" << channels; + debugOnce = false; + } + + + 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, dphi; 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; - - if(bTune) { - ic=0; - dphi=6.28318530718*1270.46/11025.0; - } - 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; + 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_exact = 0; + // CHANGE: Use the actual stream sample rate, not 11025 + dphi = 6.28318530718 * 1270.46 / udata->streamSampleRate; } - if(btxok and !btxok0) { //Start (or re-start) a transmission - n=nsec/nTRperiod; - tstart=tsec - n*nTRperiod - 1.0; + if(bTune0 && !bTune) btxok = false; + bTune0 = bTune; + if(nsec != nsec0) nsec0 = nsec; - if(tstart<1.0) { - ic=0; //Start of Tx cycle, set starting index to 0 - nStart=n; + // 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; + + // 2. Linear Interpolation to clean up the noise +if (btxok && (2 * i1 + 1) < 1440000) { + + // Interpolate message waveform + qreal I = (1.0 - frac) * iwave[2*i0] + frac * iwave[2*i1]; + qreal Q = (1.0 - frac) * iwave[2*i0 + 1] + frac * iwave[2*i1 + 1]; + + if (bTune) { + // --- TUNE MODE (unchanged) --- + phi += dphi; + I = xAmp * qCos(phi); + Q = yAmp * qSin(phi + dPhase); + + } else { + // --- MESSAGE TX: scale using the Tune slider percentage --- + qreal gain = txPower / 100.0; // 0.0 ? 1.0 + + I *= gain; + Q *= gain; } - } else { - for(i=0 ; i<framesToProcess; i++ ) { - *wptr++ = 0; + + // Clamp to 16-bit + i2a = short(qBound(-32768.0, I, 32767.0)); + i2b = short(qBound(-32768.0, Q, 32767.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 +158,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 +176,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; + } + + udata.nTRperiod = m_TRperiod; + udata.streamSampleRate = outRate; - 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; + 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; - 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; + // 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); } - 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; + + // --- SAFETY CHECK 4: Final guard before opening --- + paerr = Pa_OpenStream(&outStream, NULL, &outParam, outRate, + framesPerBuffer, paClipOff, + d2aCallback, &udata); + + if(paerr != paNoError) { + qDebug() << "Pa_OpenStream 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); + + paerr = Pa_StartStream(outStream); + if(paerr != paNoError) { + qDebug() << "Pa_StartStream failed:" << Pa_GetErrorText(paerr); + return; } + + // --- 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..40b650f2 100644 --- a/map65/widegraph.cpp +++ b/map65/widegraph.cpp @@ -1,6 +1,13 @@ #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" @@ -49,6 +56,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() @@ -83,6 +192,120 @@ 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, @@ -96,7 +319,6 @@ 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(nkhz != nkhz0) { ui->widePlot->setNkhz(nkhz); //Why do we need both? @@ -357,7 +579,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; diff --git a/map65/widegraph.h b/map65/widegraph.h index ea740bb5..81f804a3 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; @@ -38,16 +43,55 @@ public: void updateFreqLabel(); void enableSetRxHardware(bool b); + // 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); @@ -84,6 +128,19 @@ private: 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/qmap/CMakeLists.txt b/qmap/CMakeLists.txt index bd943589..81f710dc 100644 --- a/qmap/CMakeLists.txt +++ b/qmap/CMakeLists.txt @@ -8,6 +8,7 @@ set (qmap_CXXSRCS mainwindow.cpp meterwidget.cpp plotter.cpp + runtime_paths.cpp signalmeter.cpp soundin.cpp widegraph.cpp @@ -45,15 +46,3 @@ target_link_libraries (qmap wsjt_qt qmap_impl ${FFTW3_LIBRARIES} Qt5::Widgets Qt if (WSJT_CREATE_WINMAIN) set_target_properties (qmap PROPERTIES WIN32_EXECUTABLE ON) endif (WSJT_CREATE_WINMAIN) - -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\")" - ) -endif () diff --git a/qmap/libqmap/CMakeLists.txt b/qmap/libqmap/CMakeLists.txt index 2eb3a0bb..7ecc22ef 100644 --- a/qmap/libqmap/CMakeLists.txt +++ b/qmap/libqmap/CMakeLists.txt @@ -1,5 +1,6 @@ set (libq65_FSRCS # Modules come first: + cacb_mod.f90 # Non-module Fortran routines: astro.f90 @@ -53,5 +54,5 @@ set_property (SOURCE ${libq65_C_and_CXXSRCS} APPEND PROPERTY OBJECT_DEPENDS ${CM # build our targets # add_library (qmap_impl STATIC ${libq65_FSRCS} ${libq65_CSRCS} ${libq65_CXXSRCS}) -target_link_libraries (qmap_impl wsjt_fort wsjt_cxx Qt5::Core) - +target_link_libraries (qmap_impl PUBLIC Qt5::Core) +wsjt_link_common_fortran (qmap_impl) diff --git a/qmap/libqmap/cacb_mod.f90 b/qmap/libqmap/cacb_mod.f90 new file mode 100644 index 00000000..ed4af75c --- /dev/null +++ b/qmap/libqmap/cacb_mod.f90 @@ -0,0 +1,23 @@ +module cacb_mod + implicit none + + complex, allocatable :: ca(:) ! FFT of raw I/Q data from Linrad + +contains + + subroutine init_cacb(n) + integer, intent(in) :: n + + if (allocated(ca)) then + if (size(ca) >= n) return + deallocate(ca) + endif + + allocate(ca(n)) + end subroutine init_cacb + + subroutine free_cacb() + if (allocated(ca)) deallocate(ca) + end subroutine free_cacb + +end module cacb_mod diff --git a/qmap/libqmap/fftbig.f90 b/qmap/libqmap/fftbig.f90 index 085fd39f..5fc2af6e 100644 --- a/qmap/libqmap/fftbig.f90 +++ b/qmap/libqmap/fftbig.f90 @@ -6,13 +6,12 @@ subroutine fftbig(dd,nmax) use FFTW3 use timer_module, only: timer + use cacb_mod, only: ca, init_cacb, free_cacb parameter (MAXFFT1=5376000) real*4 dd(2,nmax) !Input data - complex ca(MAXFFT1) !FFT of input real*8 df type(C_PTR) :: plan1 !Pointer to FFTW plan logical first - common/cacb/ca equivalence (rfilt,cfilt) data first/.true./,npatience/0/ save @@ -20,6 +19,7 @@ subroutine fftbig(dd,nmax) if(nmax.lt.0) go to 900 nfft1=MAXFFT1 + call init_cacb(nfft1) if(first) then nflags=FFTW_ESTIMATE if(npatience.eq.1) nflags=FFTW_ESTIMATE_PATIENT @@ -50,7 +50,9 @@ subroutine fftbig(dd,nmax) call timer('FFTbig ',1) go to 999 -900 call fftwf_destroy_plan(plan1) +900 if(.not.first) call fftwf_destroy_plan(plan1) + call free_cacb() + first=.true. 999 return end subroutine fftbig diff --git a/qmap/libqmap/q65b.f90 b/qmap/libqmap/q65b.f90 index 8409b798..4ac1bd1e 100644 --- a/qmap/libqmap/q65b.f90 +++ b/qmap/libqmap/q65b.f90 @@ -6,20 +6,22 @@ subroutine q65b(nutc,nqd,fcenter,nfcal,nfsample,ikhz,mousedf,ntol, & ! This routine provides an interface between QMAP and the Q65 decoder ! in WSJT-X. All arguments are input data obtained from the QMAP GUI. ! Raw Rx data are available as the 96 kHz complex spectrum ca(MAXFFT1) -! in common/cacb. Decoded messages are sent back to the GUI. +! in cacb_mod. Decoded messages are sent back to the GUI. use q65_decode use wavhdr use timer_module, only: timer + use map65_mmdec_mod, only: map65_mmdec + use iso_fortran_env, only: int16 + use cacb_mod, only: ca, init_cacb 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 - integer*2 iwave(60*12000) + integer(int16) iwave(300*12000) integer offset - complex ca(MAXFFT1) !FFT of raw I/Q data from Linrad complex cx(0:MAXFFT2-1),cz(0:MAXFFT2) real*8 fcenter,freq0,freq1 logical*1 bClickDecode @@ -36,9 +38,10 @@ subroutine q65b(nutc,nqd,fcenter,nfcal,nfsample,ikhz,mousedf,ntol, & common/decodes/ndecodes,ncand2,nQDecoderDone,nWDecoderBusy, & nWTransmitting,kHzRequested,result(50) common/decodes2/result2(50) !liveCQ - common/cacb/ca data ifile/0/ save + + call init_cacb(MAXFFT1) if(mycall0(1:1).ne.' ') mycall=mycall0 if(hiscall0(1:1).ne.' ') hiscall=hiscall0 diff --git a/qmap/main.cpp b/qmap/main.cpp index 63a707a0..3ef9def2 100644 --- a/qmap/main.cpp +++ b/qmap/main.cpp @@ -5,9 +5,14 @@ #include <QtGui> #endif #include <QApplication> +#include <QDir> +#include <QFile> +#include <QFileInfo> +#include <QDebug> #include "revision_utils.hpp" #include "mainwindow.h" +#include "runtime_paths.h" extern "C" { // Fortran procedures we need @@ -21,20 +26,33 @@ extern "C" { int main(int argc, char *argv[]) { - QApplication a {argc, argv}; - -// Initialize libgfortran: - _gfortran_set_args(argc, argv); - _gfortran_set_convert(0); - ftninit_(); + QString appDir = QFileInfo {argc > 0 ? QString::fromLocal8Bit (argv[0]) : QString {}}.absoluteDir ().absolutePath (); // Read optional file to disable highDPI scaling - QFile f("DisableHighDpiScaling"); + QFile f(QDir {appDir}.absoluteFilePath ("DisableHighDpiScaling")); if (!f.exists()) QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); + QApplication a {argc, argv}; + // Override programs executable basename as application name. a.setApplicationName ("QMAP"); - a.setApplicationVersion ("0.6"); + a.setApplicationVersion ("0.7"); + + QString dataDir = qmapDataDir(); + QFileInfo dataDirInfo {dataDir}; + if (!dataDirInfo.exists() || !dataDirInfo.isDir() || !dataDirInfo.isWritable() + || !QDir::setCurrent(dataDir)) { + QString message {"Unable to use QMAP working directory: " + dataDir}; + qWarning() << message; + QMessageBox::critical(nullptr, QObject::tr("QMAP Startup Error"), message); + return 1; + } + + // QMAP C++ and Fortran code still use relative opens for runtime files. + // Start from the writable data directory before Fortran initializes them. + _gfortran_set_args(argc, argv); + _gfortran_set_convert(0); + ftninit_(); // switch off as we share an Info.plist file with WSJT-X a.setAttribute (Qt::AA_DontUseNativeMenuBar); MainWindow w; diff --git a/qmap/mainwindow.cpp b/qmap/mainwindow.cpp index 47524ad4..70141b2d 100644 --- a/qmap/mainwindow.cpp +++ b/qmap/mainwindow.cpp @@ -5,11 +5,13 @@ #include <QSettings> #include <QTimer> #include <QToolTip> +#include <QDebug> #include "revision_utils.hpp" #include "qt_helpers.hpp" #include "SettingsGroup.hpp" #include "widgets/MessageBox.hpp" #include "ui_mainwindow.h" +#include "runtime_paths.h" #include "devsetup.h" #include "plotter.h" #include "about.h" @@ -39,7 +41,8 @@ MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), m_appDir {QApplication::applicationDirPath ()}, - m_settings_filename {m_appDir + "/qmap.ini"}, + m_dataDir {qmapDataDir ()}, + m_settings_filename {qmapSettingsFile (m_appDir, m_dataDir)}, m_astro_window {new Astro {m_settings_filename}}, m_wide_graph_window {new WideGraph {m_settings_filename}}, m_gui_timer {new QTimer {this}} @@ -182,7 +185,7 @@ MainWindow::MainWindow(QWidget *parent) : // Read items for fAddComboBox ui->fAddComboBox->addItem (0); ui->fAddComboBox->setItemText(0, QString::number(m_fAdd)); - QFile g("fadd.txt"); + QFile g(QDir {m_dataDir}.absoluteFilePath("fadd.txt")); QTextStream stream(&g); if(g.open (QIODevice::ReadOnly | QIODevice::Text)) { while (!stream.atEnd()) { @@ -273,7 +276,7 @@ void MainWindow::readSettings() { SettingsGroup g {&settings, "MainWindow"}; restoreGeometry(settings.value("geometry").toByteArray()); - m_path = settings.value("MRUdir", m_appDir + "/save").toString(); + m_path = settings.value("MRUdir", QDir {m_dataDir}.absoluteFilePath("save")).toString(); } SettingsGroup g {&settings, "Common"}; @@ -281,10 +284,10 @@ void MainWindow::readSettings() m_myGrid=settings.value("MyGrid","").toString(); m_astroFont=settings.value("AstroFont",18).toInt(); m_myCallColor=settings.value("MyCallColor",1).toInt(); - 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(); 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_dB = settings.value("Scale_dB",0).toInt(); @@ -1251,8 +1254,10 @@ void MainWindow::sendLiveCQData(QList<QStringList>decodeList) QNetworkAccessManager *manager = new QNetworkAccessManager(this); 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"); for (const QStringList &thePostLine : decodeList) { @@ -1589,7 +1594,8 @@ void MainWindow::on_pbAdd_clicked() { m_fAdd=ui->fAddComboBox->currentText().toDouble(); if (ui->fAddComboBox->currentText() != "") { - QFile g("fadd.txt"); + QString fAddFile = QDir {m_dataDir}.absoluteFilePath("fadd.txt"); + QFile g(fAddFile); if(g.open(QIODevice::Text | QIODevice::Append)) { QString addedEntry = (ui->fAddComboBox->currentText()); QTextStream out(&g); @@ -1599,10 +1605,10 @@ void MainWindow::on_pbAdd_clicked() #else Qt::endl #endif - ; + ; g.close(); if (ui->fAddComboBox->findText(addedEntry) < 0) ui->fAddComboBox->addItem (QString::number(m_fAdd)); - ui->decodedTextBrowser->append("Adding " + QString::number(m_fAdd) + " to file fadd.txt"); + ui->decodedTextBrowser->append("Adding " + QString::number(m_fAdd) + " to file " + fAddFile); } } } diff --git a/qmap/mainwindow.h b/qmap/mainwindow.h index d8895df5..6f1b4a23 100644 --- a/qmap/mainwindow.h +++ b/qmap/mainwindow.h @@ -96,6 +96,7 @@ private slots: private: Ui::MainWindow *ui; QString m_appDir; + QString m_dataDir; QString m_settings_filename; QScopedPointer<Astro> m_astro_window; QScopedPointer<WideGraph> m_wide_graph_window; diff --git a/qmap/runtime_paths.cpp b/qmap/runtime_paths.cpp new file mode 100644 index 00000000..b4f2291e --- /dev/null +++ b/qmap/runtime_paths.cpp @@ -0,0 +1,40 @@ +#include "runtime_paths.h" + +#include <QDebug> +#include <QDir> +#include <QFile> +#include <QStandardPaths> + +QString qmapDataDir() +{ + QString dataDir = QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation); + if (dataDir.isEmpty()) { + dataDir = QDir::home().absoluteFilePath(".qmap"); + } + + if (!QDir{}.mkpath(dataDir)) { + qWarning() << "Unable to create QMAP data directory:" << dataDir; + } + + QDir dir {dataDir}; + if (!dir.mkpath("save")) { + qWarning() << "Unable to create QMAP save directory:" << dir.absoluteFilePath("save"); + } + return dataDir; +} + +QString qmapSettingsFile(QString const& appDir, QString const& dataDir) +{ + QString settingsFile = QDir {dataDir}.absoluteFilePath("qmap.ini"); + QString legacySettingsFile = QDir {appDir}.absoluteFilePath("qmap.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 QMAP settings from" << legacySettingsFile + << "to" << settingsFile; + } + } + return settingsFile; +} diff --git a/qmap/runtime_paths.h b/qmap/runtime_paths.h new file mode 100644 index 00000000..d99eb7af --- /dev/null +++ b/qmap/runtime_paths.h @@ -0,0 +1,9 @@ +#ifndef QMAP_RUNTIME_PATHS_H +#define QMAP_RUNTIME_PATHS_H + +#include <QString> + +QString qmapDataDir(); +QString qmapSettingsFile(QString const& appDir, QString const& dataDir); + +#endif diff --git a/qt_helpers.cpp b/qt_helpers.cpp index dd474e19..5e4b233a 100644 --- a/qt_helpers.cpp +++ b/qt_helpers.cpp @@ -6,6 +6,8 @@ #include <QStyle> #include <QVariant> #include <QDateTime> +#include <QCoreApplication> +#include <QDir> QString font_as_stylesheet (QFont const& font) { @@ -48,3 +50,21 @@ QDateTime qt_truncate_date_time_to (QDateTime dt, int milliseconds) dt.setMSecsSinceEpoch (dt.toMSecsSinceEpoch () / milliseconds * milliseconds); return dt; } + +QString app_sounds_directory (QString const& subdirectory) +{ +#if defined (__APPLE__) + QString root {QCoreApplication::applicationDirPath () + "/../Resources/sounds"}; +#else + QString root {QCoreApplication::applicationDirPath () + "/sounds"}; +#endif + auto child = subdirectory; + while (child.startsWith (QChar {'/'})) + { + child.remove (0, 1); + } + + QDir dir {root}; + auto path = child.isEmpty () ? dir.absolutePath () : dir.absoluteFilePath (child); + return QDir::cleanPath (path) + QChar {'/'}; +} diff --git a/qt_helpers.hpp b/qt_helpers.hpp index f264f354..d450686e 100644 --- a/qt_helpers.hpp +++ b/qt_helpers.hpp @@ -133,6 +133,8 @@ QDateTime qt_round_date_time_to (QDateTime dt, int milliseconds); // truncate a QDateTime to an integral interval of milliseconds QDateTime qt_truncate_date_time_to (QDateTime dt, int milliseconds); +QString app_sounds_directory (QString const& subdirectory = QString {}); + template <class T> class VPtr { diff --git a/revision_utils.cpp b/revision_utils.cpp index 2406288e..9c8f6964 100644 --- a/revision_utils.cpp +++ b/revision_utils.cpp @@ -4,6 +4,7 @@ #include <QCoreApplication> #include <QRegularExpression> +#include <QSysInfo> #include "scs_version.h" @@ -64,6 +65,25 @@ QString revision (QString const& scs_rev_string) return result.trimmed (); } +QString display_revision () +{ + auto build_revision = revision (); + +#if defined (CMAKE_BUILD) && defined (WSJT_SOURCE_REVISION) + QString source_revision {WSJT_SOURCE_REVISION}; + if (!source_revision.isEmpty ()) + { + source_revision = source_revision.left (6); + if (source_revision != build_revision.left (6)) + { + return QString {"source %1 (build %2)"}.arg (source_revision, build_revision); + } + } +#endif + + return build_revision; +} + QString version (bool include_patch) { #if defined (CMAKE_BUILD) @@ -83,3 +103,15 @@ QString program_title (QString const& revision) QString id {QCoreApplication::applicationName () + " v" + QCoreApplication::applicationVersion ()}; return id + " " + revision ; } + +QString http_user_agent () +{ + // See User-Agent format definition https://www.rfc-editor.org/rfc/rfc9110#name-user-agent + QString const platform { + "(" + QSysInfo::prettyProductName () + "; " + + QSysInfo::productType () + " " + QSysInfo::productVersion () + "; " + + QSysInfo::currentCpuArchitecture () + "; " + + QString {"rv:%1"}.arg (QSysInfo::kernelVersion ()) + ")"}; + + return QString {"WSJT-X/" + version () + "_" + revision ()}.simplified () + " " + platform; +} diff --git a/revision_utils.hpp b/revision_utils.hpp index ba237255..601c519a 100644 --- a/revision_utils.hpp +++ b/revision_utils.hpp @@ -4,7 +4,9 @@ #include <QString> QString revision (QString const& svn_rev_string = QString {}); +QString display_revision (); QString version (bool include_patch = true); QString program_title (QString const& revision = QString {}); +QString http_user_agent (); #endif diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 4b346233..bf086f99 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -21,3 +21,17 @@ include_directories (${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_SOURCE_DIR}) add_executable (test_qt_helpers test_qt_helpers.cpp) target_link_libraries (test_qt_helpers wsjt_qt Qt5::Test) add_test (test_qt_helpers test_qt_helpers) +add_subdirectory (unit/hrd) +add_subdirectory (unit/packjt77) + +add_executable (test_http_user_agent test_http_user_agent.cpp) +target_link_libraries (test_http_user_agent wsjt_qt Qt5::Test) +add_test (test_http_user_agent test_http_user_agent) + +add_executable (test_emulate_split_transceiver test_emulate_split_transceiver.cpp) +target_link_libraries (test_emulate_split_transceiver Boost::log wsjt_qt Qt5::Test Qt5::Network Qt5::Widgets) +add_test (test_emulate_split_transceiver test_emulate_split_transceiver) + +add_executable (test_bwf_file test_bwf_file.cpp) +target_link_libraries (test_bwf_file wsjt_qt wsjt_qtmm Qt5::Test Qt5::Multimedia) +add_test (test_bwf_file test_bwf_file) diff --git a/tests/test_bwf_file.cpp b/tests/test_bwf_file.cpp new file mode 100644 index 00000000..55f42e32 --- /dev/null +++ b/tests/test_bwf_file.cpp @@ -0,0 +1,354 @@ +#include <QtTest> + +#include <QFile> +#include <QTemporaryFile> +#include <QtMultimedia/QAudioFormat> + +#include "Audio/BWFFile.hpp" + +namespace +{ + QByteArray le16 (quint16 value) + { + QByteArray bytes (2, '\0'); + bytes[0] = static_cast<char> (value & 0xffu); + bytes[1] = static_cast<char> ((value >> 8) & 0xffu); + return bytes; + } + + QByteArray le32 (quint32 value) + { + QByteArray bytes (4, '\0'); + bytes[0] = static_cast<char> (value & 0xffu); + bytes[1] = static_cast<char> ((value >> 8) & 0xffu); + bytes[2] = static_cast<char> ((value >> 16) & 0xffu); + bytes[3] = static_cast<char> ((value >> 24) & 0xffu); + return bytes; + } + + QByteArray chunk (char const * id, QByteArray const& payload) + { + QByteArray out; + out.append (id, 4); + out.append (le32 (static_cast<quint32> (payload.size ()))); + out.append (payload); + if (payload.size () & 1) + { + out.append ('\0'); + } + return out; + } + + QByteArray wave_file (QList<QByteArray> const& chunks) + { + QByteArray payload {"WAVE", 4}; + for (auto const& current : chunks) + { + payload.append (current); + } + + QByteArray out; + out.append ("RIFF", 4); + out.append (le32 (static_cast<quint32> (payload.size ()))); + out.append (payload); + return out; + } + + QByteArray fmt_chunk (quint16 channels = 1, quint32 sample_rate = 12000, + quint16 bits_per_sample = 16, quint16 block_align = 0, + quint32 byte_rate = 0) + { + if (!block_align) + { + block_align = static_cast<quint16> (channels * (bits_per_sample / 8u)); + } + if (!byte_rate) + { + byte_rate = sample_rate * block_align; + } + + QByteArray payload; + payload.append (le16 (1)); + payload.append (le16 (channels)); + payload.append (le32 (sample_rate)); + payload.append (le32 (byte_rate)); + payload.append (le16 (block_align)); + payload.append (le16 (bits_per_sample)); + return chunk ("fmt ", payload); + } + + QByteArray data_chunk (QByteArray const& data = {}) + { + return chunk ("data", data); + } + + QByteArray info_list_chunk () + { + QByteArray payload {"INFO", 4}; + payload.append (chunk ("INAM", QByteArray {"wsjtx", 5})); + return chunk ("LIST", payload); + } + + QByteArray info_list_chunk_with_terminal_pad_outside_size () + { + QByteArray payload {"INFO", 4}; + payload.append ("ISRC", 4); + payload.append (le32 (5)); + payload.append ("K1JT", 5); + + QByteArray out; + out.append ("LIST", 4); + out.append (le32 (static_cast<quint32> (payload.size ()))); + out.append (payload); + out.append ('\0'); + return out; + } + + QByteArray bare_bext_payload () + { + return QByteArray (604, '\0'); + } + + QAudioFormat default_format () + { + QAudioFormat format; + format.setByteOrder (QAudioFormat::LittleEndian); + format.setChannelCount (1); + format.setCodec ("audio/pcm"); + format.setSampleRate (12000); + format.setSampleSize (16); + format.setSampleType (QAudioFormat::SignedInt); + return format; + } + + QString write_temp_file (QByteArray const& data) + { + QTemporaryFile file; + file.setAutoRemove (false); + if (!file.open ()) + { + return {}; + } + + if (file.write (data) != data.size ()) + { + return {}; + } + + auto const name = file.fileName (); + file.close (); + return name; + } +} + +class TestBWFFile + : public QObject +{ + Q_OBJECT + +private: + Q_SLOT void opens_valid_pcm_wave () + { + auto const name = write_temp_file (wave_file ({fmt_chunk (), data_chunk ()})); + QVERIFY (!name.isEmpty ()); + + BWFFile file {default_format (), name}; + QVERIFY (file.open (QIODevice::ReadOnly)); + QCOMPARE (file.format ().channelCount (), 1); + QCOMPARE (file.format ().sampleRate (), 12000); + file.close (); + QFile::remove (name); + } + + Q_SLOT void opens_valid_list_info_chunk () + { + auto const name = write_temp_file (wave_file ({fmt_chunk (), info_list_chunk (), data_chunk ()})); + QVERIFY (!name.isEmpty ()); + BWFFile::InfoDictionary::key_type const inam {{'I', 'N', 'A', 'M'}}; + QByteArray const expected_name {"wsjtx", 5}; + + BWFFile file {default_format (), name}; + QVERIFY (file.open (QIODevice::ReadOnly)); + QVERIFY (file.list_info ().contains (inam)); + QCOMPARE (file.list_info ().value (inam), expected_name); + file.close (); + QFile::remove (name); + } + + Q_SLOT void opens_list_info_with_terminal_subchunk_pad () + { + auto const name = write_temp_file (wave_file ({fmt_chunk (), data_chunk (), + info_list_chunk_with_terminal_pad_outside_size ()})); + QVERIFY (!name.isEmpty ()); + BWFFile::InfoDictionary::key_type const isrc {{'I', 'S', 'R', 'C'}}; + + BWFFile file {default_format (), name}; + QVERIFY (file.open (QIODevice::ReadOnly)); + QVERIFY (file.list_info ().contains (isrc)); + QCOMPARE (file.list_info ().value (isrc), QByteArray ("K1JT", 5)); + file.close (); + QFile::remove (name); + } + + Q_SLOT void bext_version_without_chunk_defaults_to_v0 () + { + auto const name = write_temp_file (wave_file ({fmt_chunk (), data_chunk ()})); + QVERIFY (!name.isEmpty ()); + + BWFFile file {default_format (), name}; + BWFFile const& const_file = file; + QVERIFY (file.open (QIODevice::ReadOnly)); + QCOMPARE (static_cast<int> (const_file.bext_version ()), + static_cast<int> (BWFFile::BextVersion::v_0)); + file.close (); + QFile::remove (name); + } + + Q_SLOT void bext_fixed_field_getter_stays_bounded () + { + QByteArray bext = bare_bext_payload (); + bext.replace (0, 256, QByteArray (256, 'B')); + auto const name = write_temp_file (wave_file ({fmt_chunk (), chunk ("bext", bext), data_chunk ()})); + QVERIFY (!name.isEmpty ()); + + BWFFile file {default_format (), name}; + QVERIFY (file.open (QIODevice::ReadOnly)); + QCOMPARE (file.bext_description (), QByteArray (256, 'B')); + file.close (); + QFile::remove (name); + } + + Q_SLOT void bext_origination_date_time_stays_bounded () + { + QByteArray bext = bare_bext_payload (); + bext.replace (320, 10, QByteArray {"2026-04-06", 10}); + bext.replace (330, 10, QByteArray {"12-34-56ZZ", 10}); + auto const name = write_temp_file (wave_file ({fmt_chunk (), chunk ("bext", bext), data_chunk ()})); + QVERIFY (!name.isEmpty ()); + + BWFFile file {default_format (), name}; + QVERIFY (file.open (QIODevice::ReadOnly)); + QCOMPARE (file.bext_origination_date_time ().date (), QDate (2026, 4, 6)); + QCOMPARE (file.bext_origination_date_time ().time (), QTime (12, 34, 56)); + file.close (); + QFile::remove (name); + } + + Q_SLOT void bext_origination_date_time_setter_handles_invalid_value () + { + QTemporaryFile temp; + temp.setAutoRemove (false); + QVERIFY (temp.open ()); + auto const name = temp.fileName (); + temp.close (); + + { + BWFFile file {default_format (), name}; + QVERIFY (file.open (QIODevice::WriteOnly)); + file.bext_origination_date_time ({}); + file.close (); + } + + { + BWFFile file {default_format (), name}; + QVERIFY (file.open (QIODevice::ReadOnly)); + QVERIFY (!file.bext_origination_date_time ().isValid ()); + file.close (); + } + + QFile::remove (name); + } + + Q_SLOT void bext_setter_truncates_without_overread () + { + QTemporaryFile temp; + temp.setAutoRemove (false); + QVERIFY (temp.open ()); + auto const name = temp.fileName (); + temp.close (); + + { + BWFFile file {default_format (), name}; + QVERIFY (file.open (QIODevice::WriteOnly)); + file.bext_description (QByteArray (300, 'A')); + file.close (); + } + + { + BWFFile file {default_format (), name}; + QVERIFY (file.open (QIODevice::ReadOnly)); + QCOMPARE (file.bext_description (), QByteArray (256, 'A')); + file.close (); + } + + QFile::remove (name); + } + + Q_SLOT void rejects_truncated_bext_chunk () + { + QByteArray bad_bext; + bad_bext.append ("bext", 4); + bad_bext.append (le32 (700)); + bad_bext.append (QByteArray (16, '\0')); + auto const name = write_temp_file (wave_file ({fmt_chunk (), bad_bext, data_chunk ()})); + QVERIFY (!name.isEmpty ()); + + BWFFile file {default_format (), name}; + QVERIFY (!file.open (QIODevice::ReadOnly)); + QFile::remove (name); + } + + Q_SLOT void rejects_list_info_subchunk_overrun () + { + QByteArray payload {"INFO", 4}; + payload.append ("INAM", 4); + payload.append (le32 (8)); + payload.append ("bad", 3); + auto const name = write_temp_file (wave_file ({fmt_chunk (), chunk ("LIST", payload), data_chunk ()})); + QVERIFY (!name.isEmpty ()); + + BWFFile file {default_format (), name}; + QVERIFY (!file.open (QIODevice::ReadOnly)); + QFile::remove (name); + } + + Q_SLOT void rejects_short_fmt_chunk () + { + QByteArray payload; + payload.append (le16 (1)); + payload.append (le16 (1)); + auto const name = write_temp_file (wave_file ({chunk ("fmt ", payload), data_chunk ()})); + QVERIFY (!name.isEmpty ()); + + BWFFile file {default_format (), name}; + QVERIFY (!file.open (QIODevice::ReadOnly)); + QFile::remove (name); + } + + Q_SLOT void rejects_zero_channel_fmt () + { + auto const name = write_temp_file (wave_file ({fmt_chunk (0), data_chunk ()})); + QVERIFY (!name.isEmpty ()); + + BWFFile file {default_format (), name}; + QVERIFY (!file.open (QIODevice::ReadOnly)); + QFile::remove (name); + } + + Q_SLOT void tolerates_inconsistent_fmt_rates () + { + auto const name = write_temp_file (wave_file ({fmt_chunk (1, 12000, 16, 4, 48000), data_chunk ()})); + QVERIFY (!name.isEmpty ()); + + BWFFile file {default_format (), name}; + QVERIFY (file.open (QIODevice::ReadOnly)); + QCOMPARE (file.format ().sampleRate (), 12000); + QCOMPARE (file.format ().sampleSize (), 16); + file.close (); + QFile::remove (name); + } +}; + +QTEST_MAIN (TestBWFFile) + +#include "test_bwf_file.moc" diff --git a/tests/test_emulate_split_transceiver.cpp b/tests/test_emulate_split_transceiver.cpp new file mode 100644 index 00000000..13482b62 --- /dev/null +++ b/tests/test_emulate_split_transceiver.cpp @@ -0,0 +1,113 @@ +#include <memory> + +#include <QtTest> + +#include "Transceiver/EmulateSplitTransceiver.hpp" + +class FakeTransceiver final + : public Transceiver +{ + Q_OBJECT + +public: + FakeTransceiver () + : Transceiver {nullptr, nullptr} + { + } + + void set (TransceiverState const& state, unsigned sequence_number) noexcept override + { + last_state = state; + last_sequence_number = sequence_number; + } + + void start (unsigned sequence_number) noexcept override + { + last_sequence_number = sequence_number; + } + + void stop () noexcept override {} + + void send_update (TransceiverState const& state, unsigned sequence_number) + { + Q_EMIT update (state, sequence_number); + } + + TransceiverState last_state; + unsigned last_sequence_number {0}; +}; + +class TestEmulateSplitTransceiver : public QObject +{ + Q_OBJECT + +private: + Q_SLOT void fakeSplitDoesNotPublishTransientTxDialAsRxDial () + { + auto * raw_fake = new FakeTransceiver; + EmulateSplitTransceiver transceiver {nullptr, std::unique_ptr<Transceiver> {raw_fake}}; + QSignalSpy updates {&transceiver, &Transceiver::update}; + + Transceiver::TransceiverState requested; + requested.online (true); + requested.frequency (7074000); + requested.tx_frequency (7072500); + requested.split (true); + requested.ptt (true); + + transceiver.set (requested, 17); + + QCOMPARE (raw_fake->last_state.frequency (), requested.tx_frequency ()); + QCOMPARE (raw_fake->last_state.tx_frequency (), Transceiver::Frequency {0}); + QVERIFY (!raw_fake->last_state.split ()); + + Transceiver::TransceiverState wrapped_update; + wrapped_update.online (true); + wrapped_update.frequency (requested.tx_frequency ()); + wrapped_update.split (false); + wrapped_update.ptt (false); + + raw_fake->send_update (wrapped_update, 17); + + QCOMPARE (updates.size (), 1); + auto const published = qvariant_cast<Transceiver::TransceiverState> (updates.takeFirst ().at (0)); + QCOMPARE (published.frequency (), requested.frequency ()); + QCOMPARE (published.tx_frequency (), requested.tx_frequency ()); + QVERIFY (published.split ()); + QVERIFY (!published.ptt ()); + } + + Q_SLOT void receiveModeStillFollowsManualRigQsy () + { + auto * raw_fake = new FakeTransceiver; + EmulateSplitTransceiver transceiver {nullptr, std::unique_ptr<Transceiver> {raw_fake}}; + QSignalSpy updates {&transceiver, &Transceiver::update}; + + Transceiver::TransceiverState requested; + requested.online (true); + requested.frequency (7074000); + requested.tx_frequency (7072500); + requested.split (true); + requested.ptt (false); + + transceiver.set (requested, 18); + + Transceiver::TransceiverState wrapped_update; + wrapped_update.online (true); + wrapped_update.frequency (14074000); + wrapped_update.split (false); + wrapped_update.ptt (false); + + raw_fake->send_update (wrapped_update, 18); + + QCOMPARE (updates.size (), 1); + auto const published = qvariant_cast<Transceiver::TransceiverState> (updates.takeFirst ().at (0)); + QCOMPARE (published.frequency (), wrapped_update.frequency ()); + QCOMPARE (published.tx_frequency (), requested.tx_frequency ()); + QVERIFY (published.split ()); + QVERIFY (!published.ptt ()); + } +}; + +QTEST_MAIN (TestEmulateSplitTransceiver) +#include "test_emulate_split_transceiver.moc" diff --git a/tests/test_http_user_agent.cpp b/tests/test_http_user_agent.cpp new file mode 100644 index 00000000..0bc09ea1 --- /dev/null +++ b/tests/test_http_user_agent.cpp @@ -0,0 +1,33 @@ +#include <QtTest> + +#include "revision_utils.hpp" + +class TestHttpUserAgent final + : public QObject +{ + Q_OBJECT + +private Q_SLOTS: + void includesApplicationIdentityAndPlatformContext () + { + auto const user_agent = http_user_agent (); + + QVERIFY (user_agent.startsWith ("WSJT-X/")); + QVERIFY (user_agent.contains (version ())); + + auto const build_revision = revision (); + if (!build_revision.isEmpty ()) + { + QVERIFY (user_agent.contains ("_" + build_revision)); + } + + QVERIFY (user_agent.contains ('(')); + QVERIFY (user_agent.contains (')')); + QVERIFY (!user_agent.contains ('\n')); + QVERIFY (!user_agent.contains ('\r')); + } +}; + +QTEST_GUILESS_MAIN (TestHttpUserAgent) + +#include "test_http_user_agent.moc" diff --git a/tests/unit/hrd/CMakeLists.txt b/tests/unit/hrd/CMakeLists.txt new file mode 100644 index 00000000..4981b132 --- /dev/null +++ b/tests/unit/hrd/CMakeLists.txt @@ -0,0 +1,6 @@ +add_executable (test_hrd_message + test_hrd_message.cpp + ${CMAKE_SOURCE_DIR}/Transceiver/HRDMessage.cpp +) +target_link_libraries (test_hrd_message Qt5::Test) +add_test (NAME test_hrd_message COMMAND test_hrd_message) diff --git a/tests/unit/hrd/test_hrd_message.cpp b/tests/unit/hrd/test_hrd_message.cpp new file mode 100644 index 00000000..741355b4 --- /dev/null +++ b/tests/unit/hrd/test_hrd_message.cpp @@ -0,0 +1,168 @@ +#include <QtTest> + +#include "Transceiver/HRDMessage.hpp" + +namespace +{ + quint32 u32le (QByteArray const& bytes, int offset) + { + return static_cast<quint32> (static_cast<quint8> (bytes[offset])) + | (static_cast<quint32> (static_cast<quint8> (bytes[offset + 1])) << 8) + | (static_cast<quint32> (static_cast<quint8> (bytes[offset + 2])) << 16) + | (static_cast<quint32> (static_cast<quint8> (bytes[offset + 3])) << 24); + } + + void write_u32le (QByteArray * bytes, int offset, quint32 value) + { + (*bytes)[offset] = static_cast<char> (value & 0xffu); + (*bytes)[offset + 1] = static_cast<char> ((value >> 8) & 0xffu); + (*bytes)[offset + 2] = static_cast<char> ((value >> 16) & 0xffu); + (*bytes)[offset + 3] = static_cast<char> ((value >> 24) & 0xffu); + } +} + +class TestHRDMessage final + : public QObject +{ + Q_OBJECT + +private slots: + void buildsBinaryMessage () + { + auto const message = HRDMessage::make ("get radio"); + + QCOMPARE (u32le (message, 0), static_cast<quint32> (message.size ())); + QCOMPARE (u32le (message, 4), quint32 (0x1234ABCD)); + QCOMPARE (u32le (message, 8), quint32 (0xABCD1234)); + QCOMPARE (u32le (message, 12), quint32 (0)); + QCOMPARE (message.size (), HRDMessage::header_size () + (QString {"get radio"}.size () + 1) * 2); + QCOMPARE (static_cast<quint8> (message[message.size () - 2]), quint8 (0)); + QCOMPARE (static_cast<quint8> (message[message.size () - 1]), quint8 (0)); + } + + void parsesValidMessage () + { + auto const parsed = HRDMessage::parse (HRDMessage::make ("FTDX-3000")); + + QVERIFY (parsed.valid); + QVERIFY (parsed.complete); + QCOMPARE (parsed.payload, QString {"FTDX-3000"}); + } + + void preservesUtf16Payload () + { + QString payload {"Rig "}; + payload.append (QChar {0x00d8}); + + auto const parsed = HRDMessage::parse (HRDMessage::make (payload)); + + QVERIFY (parsed.valid); + QVERIFY (parsed.complete); + QCOMPARE (parsed.payload, payload); + } + + void usesDeclaredSizeForPayload () + { + auto message = HRDMessage::make ("OK"); + message.append ("ignored"); + + auto const parsed = HRDMessage::parse (message); + + QVERIFY (parsed.valid); + QVERIFY (parsed.complete); + QCOMPARE (parsed.payload, QString {"OK"}); + QCOMPARE (parsed.required_size, HRDMessage::make ("OK").size ()); + } + + void roundTripsEmptyPayload () + { + auto const parsed = HRDMessage::parse (HRDMessage::make ("")); + + QVERIFY (parsed.valid); + QVERIFY (parsed.complete); + QCOMPARE (parsed.payload, QString {}); + } + + void reportsPartialHeader () + { + auto const parsed = HRDMessage::parse (HRDMessage::make ("OK").left (8)); + + QVERIFY (parsed.valid); + QVERIFY (!parsed.complete); + QCOMPARE (parsed.required_size, HRDMessage::header_size ()); + } + + void reportsPartialBody () + { + auto const message = HRDMessage::make ("OK"); + auto const parsed = HRDMessage::parse (message.left (message.size () - 1)); + + QVERIFY (parsed.valid); + QVERIFY (!parsed.complete); + QCOMPARE (parsed.required_size, message.size ()); + } + + void rejectsInvalidMagic1 () + { + auto message = HRDMessage::make ("OK"); + write_u32le (&message, 4, 0); + + auto const parsed = HRDMessage::parse (message); + + QVERIFY (!parsed.valid); + } + + void rejectsInvalidMagic2 () + { + auto message = HRDMessage::make ("OK"); + write_u32le (&message, 8, 0); + + auto const parsed = HRDMessage::parse (message); + + QVERIFY (!parsed.valid); + } + + void rejectsHeaderSize () + { + auto message = HRDMessage::make ("OK"); + write_u32le (&message, 0, HRDMessage::header_size () - 1); + + auto const parsed = HRDMessage::parse (message); + + QVERIFY (!parsed.valid); + } + + void rejectsOversizedMessage () + { + auto message = HRDMessage::make ("OK"); + write_u32le (&message, 0, HRDMessage::max_message_size () + 1); + + auto const parsed = HRDMessage::parse (message); + + QVERIFY (!parsed.valid); + } + + void rejectsOddUtf16Payload () + { + auto message = HRDMessage::make ("OK"); + write_u32le (&message, 0, message.size () - 1); + + auto const parsed = HRDMessage::parse (message); + + QVERIFY (!parsed.valid); + } + + void rejectsMissingTerminator () + { + auto message = HRDMessage::make ("OK"); + message[message.size () - 2] = 'X'; + + auto const parsed = HRDMessage::parse (message); + + QVERIFY (!parsed.valid); + } +}; + +QTEST_MAIN (TestHRDMessage) + +#include "test_hrd_message.moc" diff --git a/tests/unit/packjt77/CMakeLists.txt b/tests/unit/packjt77/CMakeLists.txt new file mode 100644 index 00000000..f4ceff02 --- /dev/null +++ b/tests/unit/packjt77/CMakeLists.txt @@ -0,0 +1,6 @@ +add_executable (test_packjt77_hash_vectors + test_packjt77_hash_vectors.f90) +target_include_directories (test_packjt77_hash_vectors PRIVATE ${CMAKE_BINARY_DIR}) +target_link_libraries (test_packjt77_hash_vectors wsjt_fort wsjt_cxx) + +add_test (NAME test_packjt77_hash_vectors COMMAND test_packjt77_hash_vectors) diff --git a/tests/unit/packjt77/test_packjt77_hash_vectors.f90 b/tests/unit/packjt77/test_packjt77_hash_vectors.f90 new file mode 100644 index 00000000..09ea0779 --- /dev/null +++ b/tests/unit/packjt77/test_packjt77_hash_vectors.f90 @@ -0,0 +1,77 @@ +program test_packjt77_hash_vectors + + use packjt77 + implicit none + + integer :: ntests + + ntests=0 + + call expect_hash_vector('K1ABC', 712, 2851, 2920267) + call expect_hash_vector('W9XYZ', 972, 3889, 3982604) + call expect_hash_vector('PJ4/K1ABC', 346, 1387, 1420834) + call expect_hash_vector('KH1/KH7Z', 201, 806, 825805) + call expect_hash_vector('K1JT/P', 959, 3839, 3931158) + call expect_hash_vector('W3CCX', 665, 2662, 2726483) + call expect_hash_vector('3DA0ABC', 48, 192, 196695) + call expect_hash_vector('3XABC', 563, 2254, 2308721) + call expect_hash_vector('///////////', 671, 2685, 2749801) + call expect_hash_vector('ZZZZZZZZZZZ', 902, 3609, 3695718) + call expect_hash_vector('99999999999', 762, 3050, 3123740) + call expect_hash_vector('A23456789Z/', 122, 488, 499902) + call expect_hash_vector(' ', 0, 0, 0) + + write(*,1000) ntests +1000 format('packjt77 hash vector tests passed: ',i0) + +contains + + subroutine expect_hash_vector(callsign,want10,want12,want22) + character(len=*), intent(in) :: callsign + integer, intent(in) :: want10, want12, want22 + character(len=13) :: c13 + integer :: got10, got12, got22 + integer :: got10var, got12var, got22var + + c13=' ' + c13=callsign + got10=ihashcall(c13,10) + got12=ihashcall(c13,12) + got22=ihashcall(c13,22) + got10var=ihashcallvar(c13,10) + got12var=ihashcallvar(c13,12) + got22var=ihashcallvar(c13,22) + + if(got10.ne.want10 .or. got12.ne.want12 .or. got22.ne.want22) then + write(*,1010) trim(callsign), got10, got12, got22, want10, want12, want22 +1010 format('Hash vector failure for "',a,'"; got ',i0,1x,i0,1x,i0, & + ' wanted ',i0,1x,i0,1x,i0) + error stop 1 + endif + + if(got10var.ne.want10 .or. got12var.ne.want12 .or. got22var.ne.want22) then + write(*,1020) trim(callsign), got10var, got12var, got22var, & + want10, want12, want22 +1020 format('Var hash vector failure for "',a,'"; got ',i0,1x,i0,1x,i0, & + ' wanted ',i0,1x,i0,1x,i0) + error stop 1 + endif + + if(got10.ne.got10var .or. got12.ne.got12var .or. got22.ne.got22var) then + write(*,1030) trim(callsign), got10, got12, got22, got10var, got12var, got22var +1030 format('Hash helper mismatch for "',a,'"; standard ',i0,1x,i0,1x,i0, & + ' var ',i0,1x,i0,1x,i0) + error stop 1 + endif + + if(got10.lt.0 .or. got10.gt.1023 .or. got12.lt.0 .or. got12.gt.4095 .or. & + got22.lt.0 .or. got22.gt.4194303) then + write(*,1040) trim(callsign), got10, got12, got22 +1040 format('Hash range failure for "',a,'"; got ',i0,1x,i0,1x,i0) + error stop 1 + endif + + ntests=ntests+1 + end subroutine expect_hash_vector + +end program test_packjt77_hash_vectors diff --git a/widgets/about.cpp b/widgets/about.cpp index 59400929..85366124 100644 --- a/widgets/about.cpp +++ b/widgets/about.cpp @@ -15,7 +15,7 @@ CAboutDlg::CAboutDlg(QWidget *parent) : ui->labelTxt->setText ("<h2>" + QString {"WSJT-X v" + QCoreApplication::applicationVersion () - + " " + revision ()}.simplified () + "<br />" + + " " + display_revision ()}.simplified () + "<br />" "WSJT-X implements a number of digital modes designed for <br />" "weak-signal Amateur Radio communication. <br /><br />" diff --git a/widgets/activeStations.cpp b/widgets/activeStations.cpp index 7353501c..067d36b5 100644 --- a/widgets/activeStations.cpp +++ b/widgets/activeStations.cpp @@ -125,31 +125,37 @@ void ActiveStations::displayRecentStations(QString mode, QString const& t) m_clickOK=false; ui->RecentStationsPlainTextEdit->setPlainText(t); -//White background for Q65-60x decodes, yellow for Q65-30x: int i0=0; int i1=0; - int npos=0; int nlines=t.count("\n"); QTextCursor cursor=ui->RecentStationsPlainTextEdit->textCursor(); QTextCharFormat fmt; + + // Use a regular expression matcher to find the text pattern within each line bounds + QRegularExpression regex(" 30[ABCD] "); + for(int i=0; i<nlines; i++) { i1=t.indexOf("\n",i0); - npos=t.indexOf(QRegularExpression(" 30[ABCD] "), i0); - if(npos>0) { - cursor.setPosition(npos); - cursor.select(QTextCursor::LineUnderCursor); + // Isolate the current line to check for the match + QString currentLine = t.mid(i0, i1 - i0); + bool hasMatch = currentLine.contains(regex); + + // Move the cursor to the current line we are processing + cursor.setPosition(i0); + cursor.select(QTextCursor::LineUnderCursor); + + if(hasMatch) { fmt.setBackground(QBrush(Qt::yellow)); fmt.setForeground(QBrush(Qt::black)); } else { - cursor.setPosition(i0+10); - cursor.select(QTextCursor::LineUnderCursor); - fmt.clearForeground(); - fmt.clearBackground(); + // Explicitly force the background back to white + fmt.setBackground(QBrush(Qt::white)); + fmt.setForeground(QBrush(Qt::black)); } + cursor.setCharFormat(fmt); i0=i1+1; } - m_clickOK=bClickOK; } diff --git a/widgets/displaytext.cpp b/widgets/displaytext.cpp index 2494928a..5c8e4233 100644 --- a/widgets/displaytext.cpp +++ b/widgets/displaytext.cpp @@ -208,7 +208,7 @@ void DisplayText::insertText(QString const& text, QColor bg, QColor fg { temp_format = format; cursor.insertText(text.mid (text_index, call_index - text_index), format); - if (pos.value ().second.isValid ()) + if (pos.value ().first.isValid ()) { temp_format.setBackground (pos.value ().first); } @@ -872,7 +872,7 @@ void DisplayText::highlight_callsign (QString const& callsign, QColor const& bg, } else { - auto pos = highlighted_calls_.find (callsign); + auto pos = highlighted_calls_.find (callsign.toUpper ()); if (bg.isValid () || fg.isValid ()) { auto colours = qMakePair (bg, fg); @@ -918,7 +918,7 @@ void DisplayText::AudioAlerts() #ifdef WIN32 if(m_config->alert_Enabled()) { QAudioOutput info(QAudioDeviceInfo::defaultOutputDevice()); - QString audioPath = QCoreApplication::applicationDirPath() + "/sounds" + m_config->voicesPath() + "/"; + QString audioPath = app_sounds_directory (m_config->voicesPath()); QAudioFormat format; format.setCodec("audio/pcm"); format.setSampleRate (48000); @@ -930,7 +930,7 @@ void DisplayText::AudioAlerts() connect(audio, SIGNAL(stateChanged(QAudio::State)), this, SLOT(handleStateChanged(QAudio::State))); #else if(m_config->alert_Enabled()) { - QString audioPath = QCoreApplication::applicationDirPath() + "/sounds" + m_config->voicesPath() + "/"; + QString audioPath = app_sounds_directory (m_config->voicesPath()); #endif QFile *effect2 = new QFile(this); QFile *effect3 = new QFile(this); diff --git a/widgets/fastgraph.cpp b/widgets/fastgraph.cpp index 9efe5fc6..10580f82 100644 --- a/widgets/fastgraph.cpp +++ b/widgets/fastgraph.cpp @@ -98,7 +98,11 @@ void FastGraph::on_pbAutoLevel_clicked() for(int i=0; i<=fast_jh; i++) { sum += fast_green[i]; } - m_ave=sum/fast_jh; + if (fast_jh == 0) { + m_ave=0.0; + } else { + m_ave=sum/fast_jh; + } ui->gainSlider->setValue(127-int(2.2*m_ave)); ui->zeroSlider->setValue(int(m_ave)+20); ui->greenZeroSlider->setValue(160-int(3.3*m_ave)); diff --git a/widgets/mainwindow.cpp b/widgets/mainwindow.cpp index d58a98be..dc7e1d2d 100644 --- a/widgets/mainwindow.cpp +++ b/widgets/mainwindow.cpp @@ -636,6 +636,8 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, connect(m_wideGraph.data (), SIGNAL(freezeDecode2(int)),this,SLOT(freezeDecode(int))); connect(m_wideGraph.data (), SIGNAL(f11f12(int)),this,SLOT(bumpFqso(int))); connect(m_wideGraph.data (), SIGNAL(setXIT2(int)),this,SLOT(setXIT(int))); + m_wideGraph->setReferenceSpectrumAvailable( + QFile::exists(m_config.writeable_data_dir ().absoluteFilePath ("refspec.dat"))); connect (m_fastGraph.data (), &FastGraph::fastPick, this, &MainWindow::fastPick); @@ -1126,6 +1128,9 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, , "-e", QDir::toNativeSeparators (m_appDir) , "-a", QDir::toNativeSeparators (m_config.writeable_data_dir ().absolutePath ()) , "-t", QDir::toNativeSeparators (m_config.temp_dir ().absolutePath ()) + // -r: read-only shipped-data dir (cty.dat, ALLCALL7.TXT, ...) for the + // Fortran decoder; resolves to Contents/Resources/wsjtx on macOS. + , "-r", QDir::toNativeSeparators (m_config.data_dir ().absolutePath ()) }; QProcessEnvironment new_env {m_env}; new_env.insert ("OMP_STACKSIZE", "10M"); @@ -1226,6 +1231,22 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple, ui->outAttenuation->setValue(0); ui->outAttenuation->setValue(attVal); Q_EMIT m_config.transceiver_volume(m_config.volume()); + // set_mode() in the constructor emits transceiver_period() while the TCI + // rig is still offline, so TransceiverBase::set() skips do_period() and + // TCITransceiver's m_period stays at its 15.0 s default. For any mode + // whose TR period != 15 s (FT4, MSK144, Q65-15, FST4-15, ...) the + // modulator then computes against 15000 ms and readAudioData emits + // silence for the whole transmission (panadapter shows energy, no audio + // reaches the air). Re-emit the period here, now that TCI is connected. + // That same offline set_mode() also left m_TRperiod cached in + // Configuration even though the rig never applied it, so force=true + // bypasses Configuration's period de-dup and guarantees the resync + // regardless of TCI bring-up timing. + // OOB guard matches on_actionFT4_triggered() and the other mode handlers. + // Hardens public PR WSJTX/wsjtx#21 (Ramon Martinez, rampa069) for the + // Configuration de-dup cache. + if (ui->bandComboBox->currentText()!="OOB") + Q_EMIT m_config.transceiver_period(m_TRperiod, true); }); } @@ -2008,7 +2029,7 @@ void MainWindow::readSettings() #ifdef WIN32 if (m_config.alert_Enabled()) { // testing and initializing the default audio device for playing audible alerts QAudioOutput info(QAudioDeviceInfo::defaultOutputDevice()); - QString audioPath = QCoreApplication::applicationDirPath() + "/sounds" + m_config.voicesPath() + "/"; + QString audioPath = app_sounds_directory (m_config.voicesPath()); QAudioFormat format; format.setCodec("audio/pcm"); format.setSampleRate (48000); @@ -2018,7 +2039,7 @@ void MainWindow::readSettings() QAudioOutput* audio; audio = new QAudioOutput(format, this); QFile *effect = new QFile(this); - effect->setFileName(QString("%1/%2").arg(audioPath, "Testing.wav")); + effect->setFileName(QString("%1/%2").arg(audioPath, "Testing123.wav")); effect->open(QIODevice::ReadOnly); audio->start(effect); } @@ -2240,8 +2261,8 @@ void MainWindow::dataSink(qint64 frames) if(!m_diskData) { refspectrum_(&dec_data.d2[k-m_nsps/2],&m_bClearRefSpec,&m_bRefSpec, &m_bUseRef, fname.constData (), (FCL)fname.size ()); + m_bClearRefSpec=false; } - m_bClearRefSpec=false; if(m_mode=="MSK144" or m_bFast9) { fastSink(frames); @@ -3365,7 +3386,7 @@ void MainWindow::fastSink(qint64 frames) if (m_config.alert_Enabled() && ((m_config.alert_DXcall() && play_DXcall && m_hisCall!="") or (m_config.alert_Wanted() && play_Wanted))) { #ifdef WIN32 QAudioOutput info(QAudioDeviceInfo::defaultOutputDevice()); - QString audioPath = QCoreApplication::applicationDirPath() + "/sounds" + m_config.voicesPath() + "/"; + QString audioPath = app_sounds_directory (m_config.voicesPath()); QAudioFormat format; format.setCodec("audio/pcm"); format.setSampleRate (48000); @@ -3381,9 +3402,9 @@ void MainWindow::fastSink(qint64 frames) effect1->open(QIODevice::ReadOnly); audio->start(effect1); #else - QString audioPath = QCoreApplication::applicationDirPath() + "/sounds" + m_config.voicesPath() + "/"; + QString audioPath = app_sounds_directory (m_config.voicesPath()); if (m_config.alert_DXcall() && play_DXcall) QSound::play(audioPath + "DXcall.wav"); // for Linux and macOS - else if (m_config.alert_DXcall() && play_Wanted) QSound::play(audioPath + "Wanted.wav"); // for Linux and macOS + else if (m_config.alert_Wanted() && play_Wanted) QSound::play(audioPath + "Wanted.wav"); // for Linux and macOS #endif play_DXcall = false; play_Wanted = false; @@ -4517,6 +4538,8 @@ void MainWindow::on_stopButton_clicked() //stopButton m_loopall=false; if(m_bRefSpec) { MessageBox::information_message (this, tr ("Reference spectrum saved")); + m_wideGraph->setReferenceSpectrumAvailable( + QFile::exists(m_config.writeable_data_dir ().absoluteFilePath ("refspec.dat"))); m_bRefSpec=false; } if (ui->DX_Call_Button->isChecked()) ui->DX_Call_Button->click (); @@ -7192,7 +7215,7 @@ void MainWindow::readFromStdout() //readFromStdout if (m_config.alert_Enabled() && ((m_config.alert_DXcall() && play_DXcall && m_hisCall!="") or (m_config.alert_Wanted() && play_Wanted))) { #ifdef WIN32 QAudioOutput info(QAudioDeviceInfo::defaultOutputDevice()); - QString audioPath = QCoreApplication::applicationDirPath() + "/sounds" + m_config.voicesPath() + "/"; + QString audioPath = app_sounds_directory (m_config.voicesPath()); QAudioFormat format; format.setCodec("audio/pcm"); format.setSampleRate (48000); @@ -7208,9 +7231,9 @@ void MainWindow::readFromStdout() //readFromStdout effect1->open(QIODevice::ReadOnly); audio->start(effect1); #else - QString audioPath = QCoreApplication::applicationDirPath() + "/sounds" + m_config.voicesPath() + "/"; + QString audioPath = app_sounds_directory (m_config.voicesPath()); if (m_config.alert_DXcall() && play_DXcall) QSound::play(audioPath + "DXcall.wav"); // for Linux and macOS - else if (m_config.alert_DXcall() && play_Wanted) QSound::play(audioPath + "Wanted.wav"); // for Linux and macOS + else if (m_config.alert_Wanted() && play_Wanted) QSound::play(audioPath + "Wanted.wav"); // for Linux and macOS #endif play_DXcall = false; play_Wanted = false; @@ -10390,7 +10413,7 @@ void MainWindow::mousePressEvent(QMouseEvent *event) // mouse press events // Testing the default audio device #ifdef WIN32 QAudioOutput info(QAudioDeviceInfo::defaultOutputDevice()); - QString audioPath = QCoreApplication::applicationDirPath() + "/sounds" + m_config.voicesPath() + "/"; + QString audioPath = app_sounds_directory (m_config.voicesPath()); QAudioFormat format; format.setCodec("audio/pcm"); format.setSampleRate (48000); @@ -10404,7 +10427,7 @@ void MainWindow::mousePressEvent(QMouseEvent *event) // mouse press events effect->open(QIODevice::ReadOnly); audio->start(effect); #else - QString audioPath = QCoreApplication::applicationDirPath() + "/sounds" + m_config.voicesPath() + "/"; + QString audioPath = app_sounds_directory (m_config.voicesPath()); QSound::play(audioPath + "Testing_long.wav"); // for Linux and macOS #endif } @@ -13885,6 +13908,16 @@ void MainWindow::on_actionMeasure_phase_response_triggered() void MainWindow::on_actionErase_reference_spectrum_triggered() { + QFile refspec_file {m_config.writeable_data_dir ().absoluteFilePath ("refspec.dat")}; + bool refspec_available {false}; + if (refspec_file.exists () and !refspec_file.remove ()) { + refspec_available = refspec_file.exists (); + MessageBox::warning_message (this, tr ("File Error"), + tr ("Cannot remove \"%1\": %2") + .arg (refspec_file.fileName (), refspec_file.errorString ())); + } + if (m_wideGraph) m_wideGraph->clearReferenceSpectrum (refspec_available); + m_bUseRef=false; m_bClearRefSpec=true; } @@ -17341,7 +17374,11 @@ void MainWindow::on_actionErase_Ignore_List_triggered() void MainWindow::read_ALLCALL7() { - static QFile AllCall7File {"ALLCALL7.TXT"}; + // Read the shipped read-only ALLCALL7.TXT from the data dir where it installs + // (Contents/Resources/wsjtx on macOS, share/wsjtx on Linux/Windows), mirroring + // the JPLEPH idiom (m_config.data_dir()). The function-local static is built on + // the first call, after Configuration is constructed, so m_config is valid. + static QFile AllCall7File {m_config.data_dir ().absoluteFilePath ("ALLCALL7.TXT")}; QTextStream AllCall7Stream(&AllCall7File); if(AllCall7File.open(QIODevice::ReadOnly | QIODevice::Text)) { while (!AllCall7Stream.atEnd()) { @@ -17377,7 +17414,6 @@ void MainWindow::alertQSYmessage () { #ifdef WIN32 QAudioOutput info(QAudioDeviceInfo::defaultOutputDevice()); - QString binPath = QCoreApplication::applicationDirPath(); QAudioFormat format; format.setCodec("audio/pcm"); format.setSampleRate (48000); @@ -17388,11 +17424,10 @@ void MainWindow::alertQSYmessage () audio = new QAudioOutput(format, this); connect(audio, SIGNAL(stateChanged(QAudio::State)), this, SLOT(handleStateChanged(QAudio::State))); QFile *effect1 = new QFile(this); - effect1->setFileName(QString("%1/%2").arg(binPath, "/sounds/Message.wav")); + effect1->setFileName(app_sounds_directory () + "Message.wav"); effect1->open(QIODevice::ReadOnly); audio->start(effect1); #else - QString binPath = QCoreApplication::applicationDirPath(); - QSound::play(binPath + "/sounds/Message.wav"); // for Linux and macOS + QSound::play(app_sounds_directory () + "Message.wav"); // for Linux and macOS #endif } diff --git a/widgets/widegraph.cpp b/widgets/widegraph.cpp index 2bdef6bd..4aa2ea10 100644 --- a/widgets/widegraph.cpp +++ b/widgets/widegraph.cpp @@ -497,6 +497,25 @@ bool WideGraph::useRef() //Flatten return m_bRef; } +void WideGraph::setReferenceSpectrumAvailable(bool available) +{ + if(!available) { + m_bRef=false; + ui->cbRef->setChecked(false); + ui->widePlot->setFlatten(m_bFlatten,m_bRef); + } + ui->cbRef->setEnabled(available); +} + +void WideGraph::clearReferenceSpectrum(bool reference_spectrum_available) +{ + m_bRef=false; + ui->cbRef->setChecked(false); + ui->widePlot->setFlatten(m_bFlatten,m_bRef); + setReferenceSpectrumAvailable(reference_spectrum_available); + m_n=0; +} + void WideGraph::replot() { if(ui->widePlot->scaleOK()) ui->widePlot->replot(); diff --git a/widgets/widegraph.h b/widgets/widegraph.h index 2b19dc98..ff1daf72 100644 --- a/widgets/widegraph.h +++ b/widgets/widegraph.h @@ -41,6 +41,8 @@ public: void setSubMode(int n); bool flatten(); bool useRef(); + void setReferenceSpectrumAvailable(bool available); + void clearReferenceSpectrum(bool reference_spectrum_available); void setTol(int n); void setSuperFox(bool b); void setSuperHound(bool b); diff --git a/widgets/widegraph.ui b/widgets/widegraph.ui index 0f8b374e..a4ee7695 100644 --- a/widgets/widegraph.ui +++ b/widgets/widegraph.ui @@ -408,7 +408,7 @@ <item> <widget class="QCheckBox" name="cbRef"> <property name="toolTip"> - <string><html><head/><body><p>Compute and save a reference spectrum. (Not yet fully implemented.)</p></body></html></string> + <string><html><head/><body><p>Apply a saved reference spectrum to flatten the received passband. Available after a reference spectrum has been measured. (Not yet fully implemented.)</p></body></html></string> </property> <property name="text"> <string>Ref Spec</string> diff --git a/wsjtx_config.h.in b/wsjtx_config.h.in index de1b4c71..75c5455e 100644 --- a/wsjtx_config.h.in +++ b/wsjtx_config.h.in @@ -28,6 +28,7 @@ extern "C" { #cmakedefine PROJECT_MANUAL_DIRECTORY_URL "@PROJECT_MANUAL_DIRECTORY_URL@" #cmakedefine PROJECT_SAMPLES_URL "@PROJECT_SAMPLES_URL@" #cmakedefine PROJECT_DESCRIPTION "@PROJECT_DESCRIPTION@" +#cmakedefine WSJT_SOURCE_REVISION "@WSJT_SOURCE_REVISION@" #cmakedefine01 HAVE_HAMLIB_OLD_CACHING #cmakedefine01 HAVE_HAMLIB_CACHING |
